config.go 35 KB

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