config.go 34 KB

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