config.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. "time"
  29. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  30. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  31. )
  32. // TODO: allow all params to be configured
  33. const (
  34. LEGACY_DATA_STORE_FILENAME = "psiphon.db"
  35. DATA_STORE_FILENAME = "psiphon.boltdb"
  36. CONNECTION_WORKER_POOL_SIZE = 10
  37. TUNNEL_POOL_SIZE = 1
  38. TUNNEL_CONNECT_TIMEOUT_SECONDS = 20
  39. TUNNEL_OPERATE_SHUTDOWN_TIMEOUT = 1 * time.Second
  40. TUNNEL_PORT_FORWARD_DIAL_TIMEOUT_SECONDS = 10
  41. TUNNEL_SSH_KEEP_ALIVE_PAYLOAD_MAX_BYTES = 256
  42. TUNNEL_SSH_KEEP_ALIVE_PERIOD_MIN = 60 * time.Second
  43. TUNNEL_SSH_KEEP_ALIVE_PERIOD_MAX = 120 * time.Second
  44. TUNNEL_SSH_KEEP_ALIVE_PERIODIC_TIMEOUT_SECONDS = 30
  45. TUNNEL_SSH_KEEP_ALIVE_PERIODIC_INACTIVE_PERIOD = 10 * time.Second
  46. TUNNEL_SSH_KEEP_ALIVE_PROBE_TIMEOUT_SECONDS = 5
  47. TUNNEL_SSH_KEEP_ALIVE_PROBE_INACTIVE_PERIOD = 10 * time.Second
  48. ESTABLISH_TUNNEL_TIMEOUT_SECONDS = 300
  49. ESTABLISH_TUNNEL_WORK_TIME = 60 * time.Second
  50. ESTABLISH_TUNNEL_PAUSE_PERIOD_SECONDS = 5
  51. ESTABLISH_TUNNEL_SERVER_AFFINITY_GRACE_PERIOD = 1 * time.Second
  52. HTTP_PROXY_ORIGIN_SERVER_TIMEOUT_SECONDS = 15
  53. HTTP_PROXY_MAX_IDLE_CONNECTIONS_PER_HOST = 50
  54. FETCH_REMOTE_SERVER_LIST_TIMEOUT_SECONDS = 30
  55. FETCH_REMOTE_SERVER_LIST_RETRY_PERIOD_SECONDS = 30
  56. FETCH_REMOTE_SERVER_LIST_STALE_PERIOD = 6 * time.Hour
  57. PSIPHON_API_SERVER_TIMEOUT_SECONDS = 20
  58. PSIPHON_API_SHUTDOWN_SERVER_TIMEOUT = 1 * time.Second
  59. PSIPHON_API_STATUS_REQUEST_PERIOD_MIN = 5 * time.Minute
  60. PSIPHON_API_STATUS_REQUEST_PERIOD_MAX = 10 * time.Minute
  61. PSIPHON_API_STATUS_REQUEST_SHORT_PERIOD_MIN = 5 * time.Second
  62. PSIPHON_API_STATUS_REQUEST_SHORT_PERIOD_MAX = 10 * time.Second
  63. PSIPHON_API_STATUS_REQUEST_PADDING_MAX_BYTES = 256
  64. PSIPHON_API_CONNECTED_REQUEST_PERIOD = 24 * time.Hour
  65. PSIPHON_API_CONNECTED_REQUEST_RETRY_PERIOD = 5 * time.Second
  66. PSIPHON_API_PERSISTENT_STATS_MAX_COUNT = 100
  67. PSIPHON_API_CLIENT_VERIFICATION_REQUEST_RETRY_PERIOD = 5 * time.Second
  68. PSIPHON_API_CLIENT_VERIFICATION_REQUEST_MAX_RETRIES = 10
  69. FETCH_ROUTES_TIMEOUT_SECONDS = 60
  70. DOWNLOAD_UPGRADE_TIMEOUT_SECONDS = 60
  71. DOWNLOAD_UPGRADE_RETRY_PERIOD_SECONDS = 30
  72. DOWNLOAD_UPGRADE_STALE_PERIOD = 6 * time.Hour
  73. IMPAIRED_PROTOCOL_CLASSIFICATION_DURATION = 2 * time.Minute
  74. IMPAIRED_PROTOCOL_CLASSIFICATION_THRESHOLD = 3
  75. TOTAL_BYTES_TRANSFERRED_NOTICE_PERIOD = 5 * time.Minute
  76. TRANSFORM_HOST_NAMES_ALWAYS = "always"
  77. TRANSFORM_HOST_NAMES_NEVER = "never"
  78. )
  79. // To distinguish omitted timeout params from explicit 0 value timeout
  80. // params, these params are int pointers. nil means no param was supplied
  81. // so use the default; a non-nil pointer to 0 means no timeout.
  82. // Config is the Psiphon configuration specified by the application. This
  83. // configuration controls the behavior of the core tunnel functionality.
  84. type Config struct {
  85. // LogFilename specifies a file to receive event notices (JSON format)
  86. // By default, notices are emitted to stdout.
  87. LogFilename string
  88. // DataStoreDirectory is the directory in which to store the persistent
  89. // database, which contains information such as server entries.
  90. // By default, current working directory.
  91. //
  92. // Warning: If the datastore file, DataStoreDirectory/DATA_STORE_FILENAME,
  93. // exists but fails to open for any reason (checksum error, unexpected file
  94. // format, etc.) it will be deleted in order to pave a new datastore and
  95. // continue running.
  96. DataStoreDirectory string
  97. // PropagationChannelId is a string identifier which indicates how the
  98. // Psiphon client was distributed. This parameter is required.
  99. // This value is supplied by and depends on the Psiphon Network, and is
  100. // typically embedded in the client binary.
  101. PropagationChannelId string
  102. // PropagationChannelId is a string identifier which indicates who
  103. // is sponsoring this Psiphon client. One purpose of this value is to
  104. // determine the home pages for display. This parameter is required.
  105. // This value is supplied by and depends on the Psiphon Network, and is
  106. // typically embedded in the client binary.
  107. SponsorId string
  108. // RemoteServerListUrl is a URL which specifies a location to fetch
  109. // out-of-band server entries. This facility is used when a tunnel cannot
  110. // be established to known servers.
  111. // This value is supplied by and depends on the Psiphon Network, and is
  112. // typically embedded in the client binary.
  113. //
  114. // Deprecated: Use RemoteServerListURLs. When RemoteServerListURLs is
  115. // not nil, this parameter is ignored.
  116. RemoteServerListUrl string
  117. // RemoteServerListURLs is list of URLs which specify locations to fetch
  118. // out-of-band server entries. This facility is used when a tunnel cannot
  119. // be established to known servers.
  120. // This value is supplied by and depends on the Psiphon Network, and is
  121. // typically embedded in the client binary.
  122. // All URLs must point to the same entity with the same ETag. At least
  123. // one DownloadURL must have OnlyAfterAttempts = 0.
  124. RemoteServerListURLs []*DownloadURL
  125. // RemoteServerListDownloadFilename specifies a target filename for
  126. // storing the remote server list download. Data is stored in co-located
  127. // files (RemoteServerListDownloadFilename.part*) to allow for resumable
  128. // downloading.
  129. RemoteServerListDownloadFilename string
  130. // RemoteServerListSignaturePublicKey specifies a public key that's
  131. // used to authenticate the remote server list payload.
  132. // This value is supplied by and depends on the Psiphon Network, and is
  133. // typically embedded in the client binary.
  134. RemoteServerListSignaturePublicKey string
  135. // ObfuscatedServerListRootURL is a URL which specifies the root location
  136. // from which to fetch obfuscated server list files.
  137. // This value is supplied by and depends on the Psiphon Network, and is
  138. // typically embedded in the client binary.
  139. //
  140. // Deprecated: Use ObfuscatedServerListRootURLs. When
  141. // ObfuscatedServerListRootURLs is not nil, this parameter is ignored.
  142. ObfuscatedServerListRootURL string
  143. // ObfuscatedServerListRootURLs is a list of URLs which specify root
  144. // locations from which to fetch obfuscated server list files.
  145. // This value is supplied by and depends on the Psiphon Network, and is
  146. // typically embedded in the client binary.
  147. // All URLs must point to the same entity with the same ETag. At least
  148. // one DownloadURL must have OnlyAfterAttempts = 0.
  149. ObfuscatedServerListRootURLs []*DownloadURL
  150. // ObfuscatedServerListDownloadDirectory specifies a target directory for
  151. // storing the obfuscated remote server list downloads. Data is stored in
  152. // co-located files (<OSL filename>.part*) to allow for resumable
  153. // downloading.
  154. ObfuscatedServerListDownloadDirectory string
  155. // ClientVersion is the client version number that the client reports
  156. // to the server. The version number refers to the host client application,
  157. // not the core tunnel library. One purpose of this value is to enable
  158. // automatic updates.
  159. // This value is supplied by and depends on the Psiphon Network, and is
  160. // typically embedded in the client binary.
  161. // Note that sending a ClientPlatform string which includes "windows"
  162. // (case insensitive) and a ClientVersion of <= 44 will cause an
  163. // error in processing the response to DoConnectedRequest calls.
  164. ClientVersion string
  165. // ClientPlatform is the client platform ("Windows", "Android", etc.) that
  166. // the client reports to the server.
  167. ClientPlatform string
  168. // TunnelWholeDevice is a flag that is passed through to the handshake
  169. // request for stats purposes. Set to 1 when the host application is tunneling
  170. // the whole device, 0 otherwise.
  171. TunnelWholeDevice int
  172. // EgressRegion is a ISO 3166-1 alpha-2 country code which indicates which
  173. // country to egress from. For the default, "", the best performing server
  174. // in any country is selected.
  175. EgressRegion string
  176. // TunnelProtocol indicates which protocol to use. Valid values include:
  177. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  178. // "FRONTED-MEEK-OSSH", "FRONTED-MEEK-HTTP-OSSH". For the default, "",
  179. // the best performing protocol is used.
  180. TunnelProtocol string
  181. // EstablishTunnelTimeoutSeconds specifies a time limit after which to halt
  182. // the core tunnel controller if no tunnel has been established. The default
  183. // is ESTABLISH_TUNNEL_TIMEOUT_SECONDS.
  184. EstablishTunnelTimeoutSeconds *int
  185. // ListenInterface specifies which interface to listen on. If no interface
  186. // is provided then listen on 127.0.0.1.
  187. // If 'any' is provided then use 0.0.0.0.
  188. // If there are multiple IP addresses on an interface use the first IPv4 address.
  189. ListenInterface string
  190. // LocalSocksProxyPort specifies a port number for the local SOCKS proxy
  191. // running at 127.0.0.1. For the default value, 0, the system selects a free
  192. // port (a notice reporting the selected port is emitted).
  193. LocalSocksProxyPort int
  194. // LocalHttpProxyPort specifies a port number for the local HTTP proxy
  195. // running at 127.0.0.1. For the default value, 0, the system selects a free
  196. // port (a notice reporting the selected port is emitted).
  197. LocalHttpProxyPort int
  198. // ConnectionWorkerPoolSize specifies how many connection attempts to attempt
  199. // in parallel. The default, 0, uses CONNECTION_WORKER_POOL_SIZE which is
  200. // recommended.
  201. ConnectionWorkerPoolSize int
  202. // TunnelPoolSize specifies how many tunnels to run in parallel. Port forwards
  203. // are multiplexed over multiple tunnels. The default, 0, uses TUNNEL_POOL_SIZE
  204. // which is recommended.
  205. TunnelPoolSize int
  206. // UpstreamProxyUrl is a URL specifying an upstream proxy to use for all
  207. // outbound connections. The URL should include proxy type and authentication
  208. // information, as required. See example URLs here:
  209. // https://github.com/Psiphon-Labs/psiphon-tunnel-core/tree/master/psiphon/upstreamproxy
  210. UpstreamProxyUrl string
  211. // UpstreamProxyCustomHeaders is a set of additional arbitrary HTTP headers that are
  212. // added to all requests made through the upstream proxy specified by UpstreamProxyUrl
  213. // NOTE: Only HTTP(s) proxies use this if specified
  214. UpstreamProxyCustomHeaders http.Header
  215. // NetworkConnectivityChecker is an interface that enables the core tunnel to call
  216. // into the host application to check for network connectivity. This parameter is
  217. // only applicable to library deployments.
  218. NetworkConnectivityChecker NetworkConnectivityChecker
  219. // DeviceBinder is an interface that enables the core tunnel to call
  220. // into the host application to bind sockets to specific devices. This is used
  221. // for VPN routing exclusion. This parameter is only applicable to library
  222. // deployments.
  223. DeviceBinder DeviceBinder
  224. // IPv6Synthesizer is an interface that allows the core tunnel to call
  225. // into the host application to synthesize IPv6 addresses from IPv4 ones. This
  226. // is used to correctly lookup IPs on DNS64/NAT64 networks.
  227. IPv6Synthesizer IPv6Synthesizer
  228. // DnsServerGetter is an interface that enables the core tunnel to call
  229. // into the host application to discover the native network DNS server settings.
  230. // This parameter is only applicable to library deployments.
  231. DnsServerGetter DnsServerGetter
  232. // TransformHostNames specifies whether to use hostname transformation circumvention
  233. // strategies. Set to "always" to always transform, "never" to never transform, and
  234. // "", the default, for the default transformation strategy.
  235. TransformHostNames string
  236. // TargetServerEntry is an encoded server entry. When specified, this server entry
  237. // is used exclusively and all other known servers are ignored.
  238. TargetServerEntry string
  239. // DisableApi disables Psiphon server API calls including handshake, connected,
  240. // status, etc. This is used for special case temporary tunnels (Windows VPN mode).
  241. DisableApi bool
  242. // TargetApiProtocol specifies whether to force use of "ssh" or "web" API protocol.
  243. // When blank, the default, the optimal API protocol is used. Note that this
  244. // capability check is not applied before the "CandidateServers" count is emitted.
  245. // This parameter is intended for testing and debugging only.
  246. TargetApiProtocol string
  247. // DisableRemoteServerListFetcher disables fetching remote server lists. This is
  248. // used for special case temporary tunnels.
  249. DisableRemoteServerListFetcher bool
  250. // SplitTunnelRoutesUrlFormat is an URL which specifies the location of a routes
  251. // file to use for split tunnel mode. The URL must include a placeholder for the
  252. // client region to be supplied. Split tunnel mode uses the routes file to classify
  253. // port forward destinations as foreign or domestic and does not tunnel domestic
  254. // destinations. Split tunnel mode is on when all the SplitTunnel parameters are
  255. // supplied.
  256. // This value is supplied by and depends on the Psiphon Network, and is
  257. // typically embedded in the client binary.
  258. SplitTunnelRoutesUrlFormat string
  259. // SplitTunnelRoutesSignaturePublicKey specifies a public key that's
  260. // used to authenticate the split tunnel routes payload.
  261. // This value is supplied by and depends on the Psiphon Network, and is
  262. // typically embedded in the client binary.
  263. SplitTunnelRoutesSignaturePublicKey string
  264. // SplitTunnelDnsServer specifies a DNS server to use when resolving port
  265. // forward target domain names to IP addresses for classification. The DNS
  266. // server must support TCP requests.
  267. SplitTunnelDnsServer string
  268. // UpgradeDownloadUrl specifies a URL from which to download a host client upgrade
  269. // file, when one is available. The core tunnel controller provides a resumable
  270. // download facility which downloads this resource and emits a notice when complete.
  271. // This value is supplied by and depends on the Psiphon Network, and is
  272. // typically embedded in the client binary.
  273. //
  274. // Deprecated: Use UpgradeDownloadURLs. When UpgradeDownloadURLs
  275. // is not nil, this parameter is ignored.
  276. UpgradeDownloadUrl string
  277. // UpgradeDownloadURLs is list of URLs which specify locations from which to
  278. // download a host client upgrade file, when one is available. The core tunnel
  279. // controller provides a resumable download facility which downloads this resource
  280. // and emits a notice when complete.
  281. // This value is supplied by and depends on the Psiphon Network, and is
  282. // typically embedded in the client binary.
  283. // All URLs must point to the same entity with the same ETag. At least
  284. // one DownloadURL must have OnlyAfterAttempts = 0.
  285. UpgradeDownloadURLs []*DownloadURL
  286. // UpgradeDownloadClientVersionHeader specifies the HTTP header name for the
  287. // entity at UpgradeDownloadURLs which specifies the client version (an integer
  288. // value). A HEAD request may be made to check the version number available at
  289. // UpgradeDownloadURLs. UpgradeDownloadClientVersionHeader is required when
  290. // UpgradeDownloadURLs is specified.
  291. UpgradeDownloadClientVersionHeader string
  292. // UpgradeDownloadFilename is the local target filename for an upgrade download.
  293. // This parameter is required when UpgradeDownloadURLs is specified.
  294. // Data is stored in co-located files (UpgradeDownloadFilename.part*) to allow
  295. // for resumable downloading.
  296. UpgradeDownloadFilename string
  297. // EmitBytesTransferred indicates whether to emit periodic notices showing
  298. // bytes sent and received.
  299. EmitBytesTransferred bool
  300. // UseIndistinguishableTLS enables use of an alternative TLS stack with a less
  301. // distinct fingerprint (ClientHello content) than the stock Go TLS.
  302. // UseIndistinguishableTLS only applies to untunneled TLS connections. This
  303. // parameter is only supported on platforms built with OpenSSL.
  304. // Requires TrustedCACertificatesFilename to be set.
  305. UseIndistinguishableTLS bool
  306. // UseTrustedCACertificates toggles use of the trusted CA certs, specified
  307. // in TrustedCACertificatesFilename, for tunneled TLS connections that expect
  308. // server certificates signed with public certificate authorities (currently,
  309. // only upgrade downloads). This option is used with stock Go TLS in cases where
  310. // Go may fail to obtain a list of root CAs from the operating system.
  311. // Requires TrustedCACertificatesFilename to be set.
  312. UseTrustedCACertificatesForStockTLS bool
  313. // TrustedCACertificatesFilename specifies a file containing trusted CA certs.
  314. // The file contents should be compatible with OpenSSL's SSL_CTX_load_verify_locations.
  315. // When specified, this enables use of indistinguishable TLS for HTTPS requests
  316. // that require typical (system CA) server authentication.
  317. TrustedCACertificatesFilename string
  318. // DisablePeriodicSshKeepAlive indicates whether to send an SSH keepalive every
  319. // 1-2 minutes, when the tunnel is idle. If the SSH keepalive times out, the tunnel
  320. // is considered to have failed.
  321. DisablePeriodicSshKeepAlive bool
  322. // DeviceRegion is the optional, reported region the host device is running in.
  323. // This input value should be a ISO 3166-1 alpha-2 country code. The device region
  324. // is reported to the server in the connected request and recorded for Psiphon
  325. // stats.
  326. // When provided, this value may be used, pre-connection, to select performance
  327. // or circumvention optimization strategies for the given region.
  328. DeviceRegion string
  329. // EmitDiagnosticNotices indicates whether to output notices containing detailed
  330. // information about the Psiphon session. As these notices may contain sensitive
  331. // network information, they should not be insecurely distributed or displayed
  332. // to users. Default is off.
  333. EmitDiagnosticNotices bool
  334. // TunnelConnectTimeoutSeconds specifies a single tunnel connection sequence timeout.
  335. // Zero value means that connection process will not time out.
  336. // If omitted, the default value is TUNNEL_CONNECT_TIMEOUT_SECONDS.
  337. TunnelConnectTimeoutSeconds *int
  338. // TunnelPortForwardDialTimeoutSeconds specifies a dial timeout per SSH port forward.
  339. // Zero value means a port forward dial will not time out.
  340. // If omitted, the default value is TUNNEL_PORT_FORWARD_DIAL_TIMEOUT_SECONDS.
  341. TunnelPortForwardDialTimeoutSeconds *int
  342. // TunnelSshKeepAliveProbeTimeoutSeconds specifies a timeout value for "probe"
  343. // SSH keep-alive that is sent upon port forward failure.
  344. // Zero value means keep-alive request will not time out.
  345. // If omitted, the default value is TUNNEL_SSH_KEEP_ALIVE_PROBE_TIMEOUT_SECONDS.
  346. TunnelSshKeepAliveProbeTimeoutSeconds *int
  347. // TunnelSshKeepAlivePeriodicTimeoutSeconds specifies a timeout value for regular
  348. // SSH keep-alives that are sent periodically.
  349. // Zero value means keep-alive request will not time out.
  350. // If omitted, the default value is TUNNEL_SSH_KEEP_ALIVE_PERIODIC_TIMEOUT_SECONDS.
  351. TunnelSshKeepAlivePeriodicTimeoutSeconds *int
  352. // FetchRemoteServerListTimeoutSeconds specifies a timeout value for remote server list
  353. // HTTP requests. Zero value means that request will not time out.
  354. // If omitted, the default value is FETCH_REMOTE_SERVER_LIST_TIMEOUT_SECONDS.
  355. FetchRemoteServerListTimeoutSeconds *int
  356. // PsiphonApiServerTimeoutSeconds specifies a timeout for periodic API HTTP
  357. // requests to Psiphon server such as stats, home pages, etc.
  358. // Zero value means that request will not time out.
  359. // If omitted, the default value is PSIPHON_API_SERVER_TIMEOUT_SECONDS.
  360. // Note that this value is overridden for final stats requests during shutdown
  361. // process in order to prevent hangs.
  362. PsiphonApiServerTimeoutSeconds *int
  363. // FetchRoutesTimeoutSeconds specifies a timeout value for split tunnel routes
  364. // HTTP requests. Zero value means that request will not time out.
  365. // If omitted, the default value is FETCH_ROUTES_TIMEOUT_SECONDS.
  366. FetchRoutesTimeoutSeconds *int
  367. // UpgradeDownloadTimeoutSeconds specifies a timeout value for upgrade download
  368. // HTTP requests. Zero value means that request will not time out.
  369. // If omitted, the default value is DOWNLOAD_UPGRADE_TIMEOUT_SECONDS.
  370. DownloadUpgradeTimeoutSeconds *int
  371. // HttpProxyOriginServerTimeoutSeconds specifies an HTTP response header timeout
  372. // value in various HTTP relays found in httpProxy.
  373. // Zero value means that request will not time out.
  374. // If omitted, the default value is HTTP_PROXY_ORIGIN_SERVER_TIMEOUT_SECONDS.
  375. HttpProxyOriginServerTimeoutSeconds *int
  376. // FetchRemoteServerListRetryPeriodSeconds specifies the delay before
  377. // resuming a remote server list download after a failure.
  378. // If omitted, the default value FETCH_REMOTE_SERVER_LIST_RETRY_PERIOD_SECONDS.
  379. FetchRemoteServerListRetryPeriodSeconds *int
  380. // DownloadUpgradestRetryPeriodSeconds specifies the delay before
  381. // resuming a client upgrade download after a failure.
  382. // If omitted, the default value DOWNLOAD_UPGRADE_RETRY_PERIOD_SECONDS.
  383. DownloadUpgradeRetryPeriodSeconds *int
  384. // EstablishTunnelPausePeriodSeconds specifies the delay between attempts
  385. // to establish tunnels. Briefly pausing allows for network conditions to improve
  386. // and for asynchronous operations such as fetch remote server list to complete.
  387. // If omitted, the default value is ESTABLISH_TUNNEL_PAUSE_PERIOD_SECONDS.
  388. EstablishTunnelPausePeriodSeconds *int
  389. // RateLimits specify throttling configuration for the tunnel.
  390. RateLimits common.RateLimits
  391. // EmitSLOKs indicates whether to emit notices for each seeded SLOK. As this
  392. // could reveal user browsing activity, it's intended for debugging and testing
  393. // only.
  394. EmitSLOKs bool
  395. }
  396. // DownloadURL specifies a URL for downloading resources along with parameters
  397. // for the download strategy.
  398. type DownloadURL struct {
  399. // URL is the location of the resource. This string is slightly obfuscated
  400. // with base64 encoding to mitigate trivial binary executable string scanning.
  401. URL string
  402. // SkipVerify indicates whether to verify HTTPS certificates. It some
  403. // circumvention scenarios, verification is not possible. This must
  404. // only be set to true when the resource its own verification mechanism.
  405. SkipVerify bool
  406. // OnlyAfterAttempts specifies how to schedule this URL when downloading
  407. // the same resource (same entity, same ETag) from multiple different
  408. // candidate locations. For a value of N, this URL is only a candidate
  409. // after N rounds of attempting the download from other URLs.
  410. OnlyAfterAttempts int
  411. }
  412. // LoadConfig parses and validates a JSON format Psiphon config JSON
  413. // string and returns a Config struct populated with config values.
  414. func LoadConfig(configJson []byte) (*Config, error) {
  415. var config Config
  416. err := json.Unmarshal(configJson, &config)
  417. if err != nil {
  418. return nil, common.ContextError(err)
  419. }
  420. // Do SetEmitDiagnosticNotices first, to ensure config file errors are emitted.
  421. if config.EmitDiagnosticNotices {
  422. SetEmitDiagnosticNotices(true)
  423. }
  424. // These fields are required; the rest are optional
  425. if config.PropagationChannelId == "" {
  426. return nil, common.ContextError(
  427. errors.New("propagation channel ID is missing from the configuration file"))
  428. }
  429. if config.SponsorId == "" {
  430. return nil, common.ContextError(
  431. errors.New("sponsor ID is missing from the configuration file"))
  432. }
  433. if config.DataStoreDirectory == "" {
  434. config.DataStoreDirectory, err = os.Getwd()
  435. if err != nil {
  436. return nil, common.ContextError(err)
  437. }
  438. }
  439. if config.ClientVersion == "" {
  440. config.ClientVersion = "0"
  441. }
  442. _, err = strconv.Atoi(config.ClientVersion)
  443. if err != nil {
  444. return nil, common.ContextError(
  445. fmt.Errorf("invalid client version: %s", err))
  446. }
  447. if config.TunnelProtocol != "" {
  448. if !common.Contains(protocol.SupportedTunnelProtocols, config.TunnelProtocol) {
  449. return nil, common.ContextError(
  450. errors.New("invalid tunnel protocol"))
  451. }
  452. }
  453. if config.EstablishTunnelTimeoutSeconds == nil {
  454. defaultEstablishTunnelTimeoutSeconds := ESTABLISH_TUNNEL_TIMEOUT_SECONDS
  455. config.EstablishTunnelTimeoutSeconds = &defaultEstablishTunnelTimeoutSeconds
  456. }
  457. if config.ConnectionWorkerPoolSize == 0 {
  458. config.ConnectionWorkerPoolSize = CONNECTION_WORKER_POOL_SIZE
  459. }
  460. if config.TunnelPoolSize == 0 {
  461. config.TunnelPoolSize = TUNNEL_POOL_SIZE
  462. }
  463. if config.NetworkConnectivityChecker != nil {
  464. return nil, common.ContextError(
  465. errors.New("NetworkConnectivityChecker interface must be set at runtime"))
  466. }
  467. if config.DeviceBinder != nil {
  468. return nil, common.ContextError(
  469. errors.New("DeviceBinder interface must be set at runtime"))
  470. }
  471. if config.DnsServerGetter != nil {
  472. return nil, common.ContextError(
  473. errors.New("DnsServerGetter interface must be set at runtime"))
  474. }
  475. if !common.Contains(
  476. []string{"", TRANSFORM_HOST_NAMES_ALWAYS, TRANSFORM_HOST_NAMES_NEVER},
  477. config.TransformHostNames) {
  478. return nil, common.ContextError(
  479. errors.New("invalid TransformHostNames"))
  480. }
  481. if !common.Contains(
  482. []string{"", protocol.PSIPHON_SSH_API_PROTOCOL, protocol.PSIPHON_WEB_API_PROTOCOL},
  483. config.TargetApiProtocol) {
  484. return nil, common.ContextError(
  485. errors.New("invalid TargetApiProtocol"))
  486. }
  487. if config.UpgradeDownloadUrl != "" && config.UpgradeDownloadURLs == nil {
  488. config.UpgradeDownloadURLs = promoteLegacyDownloadURL(config.UpgradeDownloadUrl)
  489. }
  490. if config.UpgradeDownloadURLs != nil {
  491. err := decodeAndValidateDownloadURLs("UpgradeDownloadURLs", config.UpgradeDownloadURLs)
  492. if err != nil {
  493. return nil, common.ContextError(err)
  494. }
  495. if config.UpgradeDownloadClientVersionHeader == "" {
  496. return nil, common.ContextError(errors.New("missing UpgradeDownloadClientVersionHeader"))
  497. }
  498. if config.UpgradeDownloadFilename == "" {
  499. return nil, common.ContextError(errors.New("missing UpgradeDownloadFilename"))
  500. }
  501. }
  502. if !config.DisableRemoteServerListFetcher {
  503. if config.RemoteServerListUrl != "" && config.RemoteServerListURLs == nil {
  504. config.RemoteServerListURLs = promoteLegacyDownloadURL(config.RemoteServerListUrl)
  505. }
  506. if config.RemoteServerListURLs != nil {
  507. err := decodeAndValidateDownloadURLs("RemoteServerListURLs", config.RemoteServerListURLs)
  508. if err != nil {
  509. return nil, common.ContextError(err)
  510. }
  511. if config.RemoteServerListSignaturePublicKey == "" {
  512. return nil, common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  513. }
  514. if config.RemoteServerListDownloadFilename == "" {
  515. return nil, common.ContextError(errors.New("missing RemoteServerListDownloadFilename"))
  516. }
  517. }
  518. if config.ObfuscatedServerListRootURL != "" && config.ObfuscatedServerListRootURLs == nil {
  519. config.ObfuscatedServerListRootURLs = promoteLegacyDownloadURL(config.ObfuscatedServerListRootURL)
  520. }
  521. if config.ObfuscatedServerListRootURLs != nil {
  522. err := decodeAndValidateDownloadURLs("ObfuscatedServerListRootURLs", config.ObfuscatedServerListRootURLs)
  523. if err != nil {
  524. return nil, common.ContextError(err)
  525. }
  526. if config.RemoteServerListSignaturePublicKey == "" {
  527. return nil, common.ContextError(errors.New("missing RemoteServerListSignaturePublicKey"))
  528. }
  529. if config.ObfuscatedServerListDownloadDirectory == "" {
  530. return nil, common.ContextError(errors.New("missing ObfuscatedServerListDownloadDirectory"))
  531. }
  532. }
  533. }
  534. if config.TunnelConnectTimeoutSeconds == nil {
  535. defaultTunnelConnectTimeoutSeconds := TUNNEL_CONNECT_TIMEOUT_SECONDS
  536. config.TunnelConnectTimeoutSeconds = &defaultTunnelConnectTimeoutSeconds
  537. }
  538. if config.TunnelPortForwardDialTimeoutSeconds == nil {
  539. TunnelPortForwardDialTimeoutSeconds := TUNNEL_PORT_FORWARD_DIAL_TIMEOUT_SECONDS
  540. config.TunnelPortForwardDialTimeoutSeconds = &TunnelPortForwardDialTimeoutSeconds
  541. }
  542. if config.TunnelSshKeepAliveProbeTimeoutSeconds == nil {
  543. defaultTunnelSshKeepAliveProbeTimeoutSeconds := TUNNEL_SSH_KEEP_ALIVE_PROBE_TIMEOUT_SECONDS
  544. config.TunnelSshKeepAliveProbeTimeoutSeconds = &defaultTunnelSshKeepAliveProbeTimeoutSeconds
  545. }
  546. if config.TunnelSshKeepAlivePeriodicTimeoutSeconds == nil {
  547. defaultTunnelSshKeepAlivePeriodicTimeoutSeconds := TUNNEL_SSH_KEEP_ALIVE_PERIODIC_TIMEOUT_SECONDS
  548. config.TunnelSshKeepAlivePeriodicTimeoutSeconds = &defaultTunnelSshKeepAlivePeriodicTimeoutSeconds
  549. }
  550. if config.FetchRemoteServerListTimeoutSeconds == nil {
  551. defaultFetchRemoteServerListTimeoutSeconds := FETCH_REMOTE_SERVER_LIST_TIMEOUT_SECONDS
  552. config.FetchRemoteServerListTimeoutSeconds = &defaultFetchRemoteServerListTimeoutSeconds
  553. }
  554. if config.PsiphonApiServerTimeoutSeconds == nil {
  555. defaultPsiphonApiServerTimeoutSeconds := PSIPHON_API_SERVER_TIMEOUT_SECONDS
  556. config.PsiphonApiServerTimeoutSeconds = &defaultPsiphonApiServerTimeoutSeconds
  557. }
  558. if config.FetchRoutesTimeoutSeconds == nil {
  559. defaultFetchRoutesTimeoutSeconds := FETCH_ROUTES_TIMEOUT_SECONDS
  560. config.FetchRoutesTimeoutSeconds = &defaultFetchRoutesTimeoutSeconds
  561. }
  562. if config.DownloadUpgradeTimeoutSeconds == nil {
  563. defaultDownloadUpgradeTimeoutSeconds := DOWNLOAD_UPGRADE_TIMEOUT_SECONDS
  564. config.DownloadUpgradeTimeoutSeconds = &defaultDownloadUpgradeTimeoutSeconds
  565. }
  566. if config.HttpProxyOriginServerTimeoutSeconds == nil {
  567. defaultHttpProxyOriginServerTimeoutSeconds := HTTP_PROXY_ORIGIN_SERVER_TIMEOUT_SECONDS
  568. config.HttpProxyOriginServerTimeoutSeconds = &defaultHttpProxyOriginServerTimeoutSeconds
  569. }
  570. if config.FetchRemoteServerListRetryPeriodSeconds == nil {
  571. defaultFetchRemoteServerListRetryPeriodSeconds := FETCH_REMOTE_SERVER_LIST_RETRY_PERIOD_SECONDS
  572. config.FetchRemoteServerListRetryPeriodSeconds = &defaultFetchRemoteServerListRetryPeriodSeconds
  573. }
  574. if config.DownloadUpgradeRetryPeriodSeconds == nil {
  575. defaultDownloadUpgradeRetryPeriodSeconds := DOWNLOAD_UPGRADE_RETRY_PERIOD_SECONDS
  576. config.DownloadUpgradeRetryPeriodSeconds = &defaultDownloadUpgradeRetryPeriodSeconds
  577. }
  578. if config.EstablishTunnelPausePeriodSeconds == nil {
  579. defaultEstablishTunnelPausePeriodSeconds := ESTABLISH_TUNNEL_PAUSE_PERIOD_SECONDS
  580. config.EstablishTunnelPausePeriodSeconds = &defaultEstablishTunnelPausePeriodSeconds
  581. }
  582. return &config, nil
  583. }
  584. func promoteLegacyDownloadURL(URL string) []*DownloadURL {
  585. downloadURLs := make([]*DownloadURL, 1)
  586. downloadURLs[0] = &DownloadURL{
  587. URL: base64.StdEncoding.EncodeToString([]byte(URL)),
  588. SkipVerify: false,
  589. OnlyAfterAttempts: 0,
  590. }
  591. return downloadURLs
  592. }
  593. func decodeAndValidateDownloadURLs(name string, downloadURLs []*DownloadURL) error {
  594. hasOnlyAfterZero := false
  595. for _, downloadURL := range downloadURLs {
  596. if downloadURL.OnlyAfterAttempts == 0 {
  597. hasOnlyAfterZero = true
  598. }
  599. decodedURL, err := base64.StdEncoding.DecodeString(downloadURL.URL)
  600. if err != nil {
  601. return fmt.Errorf("failed to decode URL in %s: %s", name, err)
  602. }
  603. downloadURL.URL = string(decodedURL)
  604. }
  605. var err error
  606. if !hasOnlyAfterZero {
  607. err = fmt.Errorf("must be at least one DownloadURL with OnlyAfterAttempts = 0 in %s", name)
  608. }
  609. return err
  610. }
  611. func selectDownloadURL(attempt int, downloadURLs []*DownloadURL) (string, string, bool) {
  612. // The first OnlyAfterAttempts = 0 URL is the canonical URL. This
  613. // is the value used as the key for SetUrlETag when multiple download
  614. // URLs can be used to fetch a single entity.
  615. canonicalURL := ""
  616. for _, downloadURL := range downloadURLs {
  617. if downloadURL.OnlyAfterAttempts == 0 {
  618. canonicalURL = downloadURL.URL
  619. break
  620. }
  621. }
  622. candidates := make([]int, 0)
  623. for index, URL := range downloadURLs {
  624. if attempt >= URL.OnlyAfterAttempts {
  625. candidates = append(candidates, index)
  626. }
  627. }
  628. if len(candidates) < 1 {
  629. // This case is not expected, as decodeAndValidateDownloadURLs
  630. // should reject configs that would have no candidates for
  631. // 0 attempts.
  632. return "", "", true
  633. }
  634. selection, err := common.MakeSecureRandomInt(len(candidates))
  635. if err != nil {
  636. selection = 0
  637. }
  638. downloadURL := downloadURLs[candidates[selection]]
  639. return downloadURL.URL, canonicalURL, downloadURL.SkipVerify
  640. }