config.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. /*
  2. * Copyright (c) 2016, 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 server
  20. import (
  21. "crypto/rand"
  22. "crypto/rsa"
  23. "crypto/x509"
  24. "encoding/base64"
  25. "encoding/hex"
  26. "encoding/json"
  27. "encoding/pem"
  28. "errors"
  29. "fmt"
  30. "net"
  31. "strconv"
  32. "strings"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/nacl/box"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  41. )
  42. const (
  43. SERVER_CONFIG_FILENAME = "psiphond.config"
  44. SERVER_TRAFFIC_RULES_CONFIG_FILENAME = "psiphond-traffic-rules.config"
  45. SERVER_OSL_CONFIG_FILENAME = "psiphond-osl.config"
  46. SERVER_TACTICS_CONFIG_FILENAME = "psiphond-tactics.config"
  47. SERVER_ENTRY_FILENAME = "server-entry.dat"
  48. DEFAULT_SERVER_IP_ADDRESS = "127.0.0.1"
  49. WEB_SERVER_SECRET_BYTE_LENGTH = 32
  50. DISCOVERY_VALUE_KEY_BYTE_LENGTH = 32
  51. SSH_USERNAME_SUFFIX_BYTE_LENGTH = 8
  52. SSH_PASSWORD_BYTE_LENGTH = 32
  53. SSH_RSA_HOST_KEY_BITS = 2048
  54. SSH_OBFUSCATED_KEY_BYTE_LENGTH = 32
  55. )
  56. // Config specifies the configuration and behavior of a Psiphon
  57. // server.
  58. type Config struct {
  59. // LogLevel specifies the log level. Valid values are:
  60. // panic, fatal, error, warn, info, debug
  61. LogLevel string
  62. // LogFilename specifies the path of the file to log
  63. // to. When blank, logs are written to stderr.
  64. LogFilename string
  65. // SkipPanickingLogWriter disables panicking when
  66. // unable to write any logs.
  67. SkipPanickingLogWriter bool
  68. // DiscoveryValueHMACKey is the network-wide secret value
  69. // used to determine a unique discovery strategy.
  70. DiscoveryValueHMACKey string
  71. // GeoIPDatabaseFilenames are paths of GeoIP2/GeoLite2
  72. // MaxMind database files. When empty, no GeoIP lookups are
  73. // performed. Each file is queried, in order, for the
  74. // logged fields: country code, city, and ISP. Multiple
  75. // file support accommodates the MaxMind distribution where
  76. // ISP data in a separate file.
  77. GeoIPDatabaseFilenames []string
  78. // PsinetDatabaseFilename is the path of the file containing
  79. // psinet.Database data.
  80. PsinetDatabaseFilename string
  81. // HostID is the ID of the server host; this is used for API
  82. // event logging.
  83. HostID string
  84. // ServerIPAddress is the public IP address of the server.
  85. ServerIPAddress string
  86. // WebServerPort is the listening port of the web server.
  87. // When <= 0, no web server component is run.
  88. WebServerPort int
  89. // WebServerSecret is the unique secret value that the client
  90. // must supply to make requests to the web server.
  91. WebServerSecret string
  92. // WebServerCertificate is the certificate the client uses to
  93. // authenticate the web server.
  94. WebServerCertificate string
  95. // WebServerPrivateKey is the private key the web server uses to
  96. // authenticate itself to clients.
  97. WebServerPrivateKey string
  98. // WebServerPortForwardAddress specifies the expected network
  99. // address ("<host>:<port>") specified in a client's port forward
  100. // HostToConnect and PortToConnect when the client is making a
  101. // tunneled connection to the web server. This address is always
  102. // exempted from validation against SSH_DISALLOWED_PORT_FORWARD_HOSTS
  103. // and AllowTCPPorts.
  104. WebServerPortForwardAddress string
  105. // WebServerPortForwardRedirectAddress specifies an alternate
  106. // destination address to be substituted and dialed instead of
  107. // the original destination when the port forward destination is
  108. // WebServerPortForwardAddress.
  109. WebServerPortForwardRedirectAddress string
  110. // TunnelProtocolPorts specifies which tunnel protocols to run
  111. // and which ports to listen on for each protocol. Valid tunnel
  112. // protocols include:
  113. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  114. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  115. // "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH", "MARIONETTE-OSSH", and
  116. // "TAPDANCE-OSSH".
  117. //
  118. // In the case of "MARIONETTE-OSSH" the port value is ignored and must be
  119. // set to 0. The port value specified in the Marionette format is used.
  120. TunnelProtocolPorts map[string]int
  121. // SSHPrivateKey is the SSH host key. The same key is used for
  122. // all protocols, run by this server instance, which use SSH.
  123. SSHPrivateKey string
  124. // SSHServerVersion is the server version presented in the
  125. // identification string. The same value is used for all
  126. // protocols, run by this server instance, which use SSH.
  127. SSHServerVersion string
  128. // SSHUserName is the SSH user name to be presented by the
  129. // the tunnel-core client. The same value is used for all
  130. // protocols, run by this server instance, which use SSH.
  131. SSHUserName string
  132. // SSHPassword is the SSH password to be presented by the
  133. // the tunnel-core client. The same value is used for all
  134. // protocols, run by this server instance, which use SSH.
  135. SSHPassword string
  136. // SSHBeginHandshakeTimeoutMilliseconds specifies the timeout
  137. // for clients queueing to begin an SSH handshake. The default
  138. // is SSH_BEGIN_HANDSHAKE_TIMEOUT.
  139. SSHBeginHandshakeTimeoutMilliseconds *int
  140. // SSHHandshakeTimeoutMilliseconds specifies the timeout
  141. // before which a client must complete its handshake. The default
  142. // is SSH_HANDSHAKE_TIMEOUT.
  143. SSHHandshakeTimeoutMilliseconds *int
  144. // ObfuscatedSSHKey is the secret key for use in the Obfuscated
  145. // SSH protocol. The same secret key is used for all protocols,
  146. // run by this server instance, which use Obfuscated SSH.
  147. ObfuscatedSSHKey string
  148. // MeekCookieEncryptionPrivateKey is the NaCl private key used
  149. // to decrypt meek cookie payload sent from clients. The same
  150. // key is used for all meek protocols run by this server instance.
  151. MeekCookieEncryptionPrivateKey string
  152. // MeekObfuscatedKey is the secret key used for obfuscating
  153. // meek cookies sent from clients. The same key is used for all
  154. // meek protocols run by this server instance.
  155. MeekObfuscatedKey string
  156. // MeekProhibitedHeaders is a list of HTTP headers to check for
  157. // in client requests. If one of these headers is found, the
  158. // request fails. This is used to defend against abuse.
  159. MeekProhibitedHeaders []string
  160. // MeekProxyForwardedForHeaders is a list of HTTP headers which
  161. // may be added by downstream HTTP proxies or CDNs in front
  162. // of clients. These headers supply the original client IP
  163. // address, which is geolocated for stats purposes. Headers
  164. // include, for example, X-Forwarded-For. The header's value
  165. // is assumed to be a comma delimted list of IP addresses where
  166. // the client IP is the first IP address in the list. Meek protocols
  167. // look for these headers and use the client IP address from
  168. // the header if any one is present and the value is a valid
  169. // IP address; otherwise the direct connection remote address is
  170. // used as the client IP.
  171. MeekProxyForwardedForHeaders []string
  172. // MeekCachedResponseBufferSize is the size of a private,
  173. // fixed-size buffer allocated for every meek client. The buffer
  174. // is used to cache response payload, allowing the client to retry
  175. // fetching when a network connection is interrupted. This retry
  176. // makes the OSSH tunnel within meek resilient to interruptions
  177. // at the HTTP TCP layer.
  178. // Larger buffers increase resiliency to interruption, but consume
  179. // more memory as buffers as never freed. The maximum size of a
  180. // response payload is a function of client activity, network
  181. // throughput and throttling.
  182. // A default of 64K is used when MeekCachedResponseBufferSize is 0.
  183. MeekCachedResponseBufferSize int
  184. // MeekCachedResponsePoolBufferSize is the size of a fixed-size,
  185. // shared buffer used to temporarily extend a private buffer when
  186. // MeekCachedResponseBufferSize is insufficient. Shared buffers
  187. // allow some clients to successfully retry longer response payloads
  188. // without allocating large buffers for all clients.
  189. // A default of 64K is used when MeekCachedResponsePoolBufferSize
  190. // is 0.
  191. MeekCachedResponsePoolBufferSize int
  192. // MeekCachedResponsePoolBufferCount is the number of shared
  193. // buffers. Shared buffers are allocated on first use and remain
  194. // allocated, so shared buffer count * size is roughly the memory
  195. // overhead of this facility.
  196. // A default of 2048 is used when MeekCachedResponsePoolBufferCount
  197. // is 0.
  198. MeekCachedResponsePoolBufferCount int
  199. // UDPInterceptUdpgwServerAddress specifies the network address of
  200. // a udpgw server which clients may be port forwarding to. When
  201. // specified, these TCP port forwards are intercepted and handled
  202. // directly by this server, which parses the SSH channel using the
  203. // udpgw protocol. Handling includes udpgw transparent DNS: tunneled
  204. // UDP DNS packets are rerouted to the host's DNS server.
  205. //
  206. // The intercept is applied before the port forward destination is
  207. // validated against SSH_DISALLOWED_PORT_FORWARD_HOSTS and
  208. // AllowTCPPorts. So the intercept address may be any otherwise
  209. // prohibited destination.
  210. UDPInterceptUdpgwServerAddress string
  211. // DNSResolverIPAddress specifies the IP address of a DNS server
  212. // to be used when "/etc/resolv.conf" doesn't exist or fails to
  213. // parse. When blank, "/etc/resolv.conf" must contain a usable
  214. // "nameserver" entry.
  215. DNSResolverIPAddress string
  216. // LoadMonitorPeriodSeconds indicates how frequently to log server
  217. // load information (number of connected clients per tunnel protocol,
  218. // number of running goroutines, amount of memory allocated, etc.)
  219. // The default, 0, disables load logging.
  220. LoadMonitorPeriodSeconds int
  221. // ProcessProfileOutputDirectory is the path of a directory to which
  222. // process profiles will be written when signaled with SIGUSR2. The
  223. // files are overwritten on each invocation. When set to the default
  224. // value, blank, no profiles are written on SIGUSR2. Profiles include
  225. // the default profiles here: https://golang.org/pkg/runtime/pprof/#Profile.
  226. ProcessProfileOutputDirectory string
  227. // ProcessBlockProfileDurationSeconds specifies the sample duration for
  228. // "block" profiling. For the default, 0, no "block" profile is taken.
  229. ProcessBlockProfileDurationSeconds int
  230. // ProcessCPUProfileDurationSeconds specifies the sample duration for
  231. // CPU profiling. For the default, 0, no CPU profile is taken.
  232. ProcessCPUProfileDurationSeconds int
  233. // TrafficRulesFilename is the path of a file containing a JSON-encoded
  234. // TrafficRulesSet, the traffic rules to apply to Psiphon client tunnels.
  235. TrafficRulesFilename string
  236. // OSLConfigFilename is the path of a file containing a JSON-encoded
  237. // OSL Config, the OSL schemes to apply to Psiphon client tunnels.
  238. OSLConfigFilename string
  239. // RunPacketTunnel specifies whether to run a packet tunnel.
  240. RunPacketTunnel bool
  241. // PacketTunnelEgressInterface specifies tun.ServerConfig.EgressInterface.
  242. PacketTunnelEgressInterface string
  243. // PacketTunnelDownstreamPacketQueueSize specifies
  244. // tun.ServerConfig.DownStreamPacketQueueSize.
  245. PacketTunnelDownstreamPacketQueueSize int
  246. // PacketTunnelSessionIdleExpirySeconds specifies
  247. // tun.ServerConfig.SessionIdleExpirySeconds.
  248. PacketTunnelSessionIdleExpirySeconds int
  249. // PacketTunnelSudoNetworkConfigCommands sets
  250. // tun.ServerConfig.SudoNetworkConfigCommands.
  251. PacketTunnelSudoNetworkConfigCommands bool
  252. // MaxConcurrentSSHHandshakes specifies a limit on the number of concurrent
  253. // SSH handshake negotiations. This is set to mitigate spikes in memory
  254. // allocations and CPU usage associated with SSH handshakes when many clients
  255. // attempt to connect concurrently. When a maximum limit is specified and
  256. // reached, additional clients that establish TCP or meek connections will
  257. // be disconnected after a short wait for the number of concurrent handshakes
  258. // to drop below the limit.
  259. // The default, 0 is no limit.
  260. MaxConcurrentSSHHandshakes int
  261. // PeriodicGarbageCollectionSeconds turns on periodic calls to runtime.GC,
  262. // every specified number of seconds, to force garbage collection.
  263. // The default, 0 is off.
  264. PeriodicGarbageCollectionSeconds int
  265. // AccessControlVerificationKeyRing is the access control authorization
  266. // verification key ring used to verify signed authorizations presented
  267. // by clients. Verified, active (unexpired) access control types will be
  268. // available for matching in the TrafficRulesFilter for the client via
  269. // AuthorizedAccessTypes. All other authorizations are ignored.
  270. AccessControlVerificationKeyRing accesscontrol.VerificationKeyRing
  271. // TacticsConfigFilename is the path of a file containing a JSON-encoded
  272. // tactics server configuration.
  273. TacticsConfigFilename string
  274. // MarionetteFormat specifies a Marionette format to use with the
  275. // MARIONETTE-OSSH tunnel protocol. The format specifies the network
  276. // protocol port to listen on.
  277. MarionetteFormat string
  278. // BlocklistFilename is the path of a file containing a CSV-encoded
  279. // blocklist configuration. See NewBlocklist for more file format
  280. // documentation.
  281. BlocklistFilename string
  282. // BlocklistActive indicates whether to actively prevent blocklist hits in
  283. // addition to logging events.
  284. BlocklistActive bool
  285. // OwnEncodedServerEntries is a list of the server's own encoded server
  286. // entries, idenfified by server entry tag. These values are used in the
  287. // handshake API to update clients that don't yet have a signed copy of these
  288. // server entries.
  289. //
  290. // For purposes of compartmentalization, each server receives only its own
  291. // server entries here; and, besides the discovery server entries, in
  292. // psinet.Database, necessary for the discovery feature, no other server
  293. // entries are stored on a Psiphon server.
  294. OwnEncodedServerEntries map[string]string
  295. sshBeginHandshakeTimeout time.Duration
  296. sshHandshakeTimeout time.Duration
  297. }
  298. // RunWebServer indicates whether to run a web server component.
  299. func (config *Config) RunWebServer() bool {
  300. return config.WebServerPort > 0
  301. }
  302. // RunLoadMonitor indicates whether to monitor and log server load.
  303. func (config *Config) RunLoadMonitor() bool {
  304. return config.LoadMonitorPeriodSeconds > 0
  305. }
  306. // RunPeriodicGarbageCollection indicates whether to run periodic garbage collection.
  307. func (config *Config) RunPeriodicGarbageCollection() bool {
  308. return config.PeriodicGarbageCollectionSeconds > 0
  309. }
  310. // GetOwnEncodedServerEntry returns one of the server's own server entries, as
  311. // identified by the server entry tag.
  312. func (config *Config) GetOwnEncodedServerEntry(serverEntryTag string) (string, bool) {
  313. serverEntry, ok := config.OwnEncodedServerEntries[serverEntryTag]
  314. return serverEntry, ok
  315. }
  316. // LoadConfig loads and validates a JSON encoded server config.
  317. func LoadConfig(configJSON []byte) (*Config, error) {
  318. var config Config
  319. err := json.Unmarshal(configJSON, &config)
  320. if err != nil {
  321. return nil, common.ContextError(err)
  322. }
  323. if config.ServerIPAddress == "" {
  324. return nil, errors.New("ServerIPAddress is required")
  325. }
  326. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  327. config.WebServerPrivateKey == "") {
  328. return nil, errors.New(
  329. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  330. }
  331. if config.WebServerPortForwardAddress != "" {
  332. if err := validateNetworkAddress(config.WebServerPortForwardAddress, false); err != nil {
  333. return nil, errors.New("WebServerPortForwardAddress is invalid")
  334. }
  335. }
  336. if config.WebServerPortForwardRedirectAddress != "" {
  337. if config.WebServerPortForwardAddress == "" {
  338. return nil, errors.New(
  339. "WebServerPortForwardRedirectAddress requires WebServerPortForwardAddress")
  340. }
  341. if err := validateNetworkAddress(config.WebServerPortForwardRedirectAddress, false); err != nil {
  342. return nil, errors.New("WebServerPortForwardRedirectAddress is invalid")
  343. }
  344. }
  345. for tunnelProtocol, port := range config.TunnelProtocolPorts {
  346. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  347. return nil, fmt.Errorf("Unsupported tunnel protocol: %s", tunnelProtocol)
  348. }
  349. if protocol.TunnelProtocolUsesSSH(tunnelProtocol) ||
  350. protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  351. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  352. config.SSHUserName == "" || config.SSHPassword == "" {
  353. return nil, fmt.Errorf(
  354. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  355. tunnelProtocol)
  356. }
  357. }
  358. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  359. if config.ObfuscatedSSHKey == "" {
  360. return nil, fmt.Errorf(
  361. "Tunnel protocol %s requires ObfuscatedSSHKey",
  362. tunnelProtocol)
  363. }
  364. }
  365. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  366. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  367. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  368. return nil, fmt.Errorf(
  369. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  370. tunnelProtocol)
  371. }
  372. }
  373. if protocol.TunnelProtocolUsesMarionette(tunnelProtocol) {
  374. if port != 0 {
  375. return nil, fmt.Errorf(
  376. "Tunnel protocol %s port is specified in format, not TunnelProtocolPorts",
  377. tunnelProtocol)
  378. }
  379. }
  380. }
  381. config.sshBeginHandshakeTimeout = SSH_BEGIN_HANDSHAKE_TIMEOUT
  382. if config.SSHBeginHandshakeTimeoutMilliseconds != nil {
  383. config.sshBeginHandshakeTimeout = time.Duration(*config.SSHBeginHandshakeTimeoutMilliseconds) * time.Millisecond
  384. }
  385. config.sshHandshakeTimeout = SSH_HANDSHAKE_TIMEOUT
  386. if config.SSHHandshakeTimeoutMilliseconds != nil {
  387. config.sshHandshakeTimeout = time.Duration(*config.SSHHandshakeTimeoutMilliseconds) * time.Millisecond
  388. }
  389. if config.ObfuscatedSSHKey != "" {
  390. seed, err := protocol.DeriveSSHServerVersionPRNGSeed(config.ObfuscatedSSHKey)
  391. if err != nil {
  392. return nil, fmt.Errorf(
  393. "DeriveSSHServerVersionPRNGSeed failed: %s", err)
  394. }
  395. serverVersion := pickSSHServerVersion(seed)
  396. if serverVersion != "" {
  397. config.SSHServerVersion = serverVersion
  398. }
  399. }
  400. if config.UDPInterceptUdpgwServerAddress != "" {
  401. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress, true); err != nil {
  402. return nil, fmt.Errorf("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  403. }
  404. }
  405. if config.DNSResolverIPAddress != "" {
  406. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  407. return nil, fmt.Errorf("DNSResolverIPAddress is invalid")
  408. }
  409. }
  410. err = accesscontrol.ValidateVerificationKeyRing(&config.AccessControlVerificationKeyRing)
  411. if err != nil {
  412. return nil, fmt.Errorf(
  413. "AccessControlVerificationKeyRing is invalid: %s", err)
  414. }
  415. return &config, nil
  416. }
  417. func validateNetworkAddress(address string, requireIPaddress bool) error {
  418. host, portStr, err := net.SplitHostPort(address)
  419. if err != nil {
  420. return err
  421. }
  422. if requireIPaddress && net.ParseIP(host) == nil {
  423. return errors.New("host must be an IP address")
  424. }
  425. port, err := strconv.Atoi(portStr)
  426. if err != nil {
  427. return err
  428. }
  429. if port < 0 || port > 65535 {
  430. return errors.New("invalid port")
  431. }
  432. return nil
  433. }
  434. // GenerateConfigParams specifies customizations to be applied to
  435. // a generated server config.
  436. type GenerateConfigParams struct {
  437. LogFilename string
  438. SkipPanickingLogWriter bool
  439. LogLevel string
  440. ServerIPAddress string
  441. WebServerPort int
  442. EnableSSHAPIRequests bool
  443. TunnelProtocolPorts map[string]int
  444. MarionetteFormat string
  445. TrafficRulesConfigFilename string
  446. OSLConfigFilename string
  447. TacticsConfigFilename string
  448. TacticsRequestPublicKey string
  449. TacticsRequestObfuscatedKey string
  450. }
  451. // GenerateConfig creates a new Psiphon server config. It returns JSON encoded
  452. // configs and a client-compatible "server entry" for the server. It generates
  453. // all necessary secrets and key material, which are emitted in the config
  454. // file and server entry as necessary.
  455. //
  456. // GenerateConfig uses sample values for many fields. The intention is for
  457. // generated configs to be used for testing or as examples for production
  458. // setup, not to generate production-ready configurations.
  459. //
  460. // When tactics key material is provided in GenerateConfigParams, tactics
  461. // capabilities are added for all meek protocols in TunnelProtocolPorts.
  462. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, []byte, []byte, error) {
  463. // Input validation
  464. if net.ParseIP(params.ServerIPAddress) == nil {
  465. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid IP address"))
  466. }
  467. if len(params.TunnelProtocolPorts) == 0 {
  468. return nil, nil, nil, nil, nil, common.ContextError(errors.New("no tunnel protocols"))
  469. }
  470. usedPort := make(map[int]bool)
  471. if params.WebServerPort != 0 {
  472. usedPort[params.WebServerPort] = true
  473. }
  474. usingMeek := false
  475. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  476. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  477. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid tunnel protocol"))
  478. }
  479. if usedPort[port] {
  480. return nil, nil, nil, nil, nil, common.ContextError(errors.New("duplicate listening port"))
  481. }
  482. usedPort[port] = true
  483. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  484. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  485. usingMeek = true
  486. }
  487. }
  488. // One test mode populates the tactics config file; this will generate
  489. // keys. Another test mode passes in existing keys to be used in the
  490. // server entry. Both the filename and existing keys cannot be passed in.
  491. if (params.TacticsConfigFilename != "") &&
  492. (params.TacticsRequestPublicKey != "" || params.TacticsRequestObfuscatedKey != "") {
  493. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid tactics parameters"))
  494. }
  495. // Web server config
  496. var webServerSecret, webServerCertificate,
  497. webServerPrivateKey, webServerPortForwardAddress string
  498. if params.WebServerPort != 0 {
  499. webServerSecretBytes, err := common.MakeSecureRandomBytes(WEB_SERVER_SECRET_BYTE_LENGTH)
  500. if err != nil {
  501. return nil, nil, nil, nil, nil, common.ContextError(err)
  502. }
  503. webServerSecret = hex.EncodeToString(webServerSecretBytes)
  504. webServerCertificate, webServerPrivateKey, err = common.GenerateWebServerCertificate("")
  505. if err != nil {
  506. return nil, nil, nil, nil, nil, common.ContextError(err)
  507. }
  508. webServerPortForwardAddress = net.JoinHostPort(
  509. params.ServerIPAddress, strconv.Itoa(params.WebServerPort))
  510. }
  511. // SSH config
  512. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  513. if err != nil {
  514. return nil, nil, nil, nil, nil, common.ContextError(err)
  515. }
  516. sshPrivateKey := pem.EncodeToMemory(
  517. &pem.Block{
  518. Type: "RSA PRIVATE KEY",
  519. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  520. },
  521. )
  522. signer, err := ssh.NewSignerFromKey(rsaKey)
  523. if err != nil {
  524. return nil, nil, nil, nil, nil, common.ContextError(err)
  525. }
  526. sshPublicKey := signer.PublicKey()
  527. sshUserNameSuffixBytes, err := common.MakeSecureRandomBytes(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  528. if err != nil {
  529. return nil, nil, nil, nil, nil, common.ContextError(err)
  530. }
  531. sshUserNameSuffix := hex.EncodeToString(sshUserNameSuffixBytes)
  532. sshUserName := "psiphon_" + sshUserNameSuffix
  533. sshPasswordBytes, err := common.MakeSecureRandomBytes(SSH_PASSWORD_BYTE_LENGTH)
  534. if err != nil {
  535. return nil, nil, nil, nil, nil, common.ContextError(err)
  536. }
  537. sshPassword := hex.EncodeToString(sshPasswordBytes)
  538. sshServerVersion := "SSH-2.0-Psiphon"
  539. // Obfuscated SSH config
  540. obfuscatedSSHKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  541. if err != nil {
  542. return nil, nil, nil, nil, nil, common.ContextError(err)
  543. }
  544. obfuscatedSSHKey := hex.EncodeToString(obfuscatedSSHKeyBytes)
  545. // Meek config
  546. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  547. if usingMeek {
  548. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  549. box.GenerateKey(rand.Reader)
  550. if err != nil {
  551. return nil, nil, nil, nil, nil, common.ContextError(err)
  552. }
  553. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  554. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  555. meekObfuscatedKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  556. if err != nil {
  557. return nil, nil, nil, nil, nil, common.ContextError(err)
  558. }
  559. meekObfuscatedKey = hex.EncodeToString(meekObfuscatedKeyBytes)
  560. }
  561. // Other config
  562. discoveryValueHMACKeyBytes, err := common.MakeSecureRandomBytes(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  563. if err != nil {
  564. return nil, nil, nil, nil, nil, common.ContextError(err)
  565. }
  566. discoveryValueHMACKey := base64.RawURLEncoding.EncodeToString(discoveryValueHMACKeyBytes)
  567. // Assemble configs and server entry
  568. // Note: this config is intended for either testing or as an illustrative
  569. // example or template and is not intended for production deployment.
  570. logLevel := params.LogLevel
  571. if logLevel == "" {
  572. logLevel = "info"
  573. }
  574. config := &Config{
  575. LogLevel: logLevel,
  576. LogFilename: params.LogFilename,
  577. SkipPanickingLogWriter: params.SkipPanickingLogWriter,
  578. GeoIPDatabaseFilenames: nil,
  579. HostID: "example-host-id",
  580. ServerIPAddress: params.ServerIPAddress,
  581. DiscoveryValueHMACKey: discoveryValueHMACKey,
  582. WebServerPort: params.WebServerPort,
  583. WebServerSecret: webServerSecret,
  584. WebServerCertificate: webServerCertificate,
  585. WebServerPrivateKey: webServerPrivateKey,
  586. WebServerPortForwardAddress: webServerPortForwardAddress,
  587. SSHPrivateKey: string(sshPrivateKey),
  588. SSHServerVersion: sshServerVersion,
  589. SSHUserName: sshUserName,
  590. SSHPassword: sshPassword,
  591. ObfuscatedSSHKey: obfuscatedSSHKey,
  592. TunnelProtocolPorts: params.TunnelProtocolPorts,
  593. DNSResolverIPAddress: "8.8.8.8",
  594. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  595. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  596. MeekObfuscatedKey: meekObfuscatedKey,
  597. MeekProhibitedHeaders: nil,
  598. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  599. LoadMonitorPeriodSeconds: 300,
  600. TrafficRulesFilename: params.TrafficRulesConfigFilename,
  601. OSLConfigFilename: params.OSLConfigFilename,
  602. TacticsConfigFilename: params.TacticsConfigFilename,
  603. MarionetteFormat: params.MarionetteFormat,
  604. }
  605. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  606. if err != nil {
  607. return nil, nil, nil, nil, nil, common.ContextError(err)
  608. }
  609. intPtr := func(i int) *int {
  610. return &i
  611. }
  612. trafficRulesSet := &TrafficRulesSet{
  613. DefaultRules: TrafficRules{
  614. RateLimits: RateLimits{
  615. ReadUnthrottledBytes: new(int64),
  616. ReadBytesPerSecond: new(int64),
  617. WriteUnthrottledBytes: new(int64),
  618. WriteBytesPerSecond: new(int64),
  619. },
  620. IdleTCPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  621. IdleUDPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  622. MaxTCPPortForwardCount: intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT),
  623. MaxUDPPortForwardCount: intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT),
  624. AllowTCPPorts: nil,
  625. AllowUDPPorts: nil,
  626. },
  627. }
  628. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  629. if err != nil {
  630. return nil, nil, nil, nil, nil, common.ContextError(err)
  631. }
  632. encodedOSLConfig, err := json.MarshalIndent(&osl.Config{}, "\n", " ")
  633. if err != nil {
  634. return nil, nil, nil, nil, nil, common.ContextError(err)
  635. }
  636. tacticsRequestPublicKey := params.TacticsRequestPublicKey
  637. tacticsRequestObfuscatedKey := params.TacticsRequestObfuscatedKey
  638. var tacticsRequestPrivateKey string
  639. var encodedTacticsConfig []byte
  640. if params.TacticsConfigFilename != "" {
  641. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err =
  642. tactics.GenerateKeys()
  643. if err != nil {
  644. return nil, nil, nil, nil, nil, common.ContextError(err)
  645. }
  646. decodedTacticsRequestPublicKey, err := base64.StdEncoding.DecodeString(tacticsRequestPublicKey)
  647. if err != nil {
  648. return nil, nil, nil, nil, nil, common.ContextError(err)
  649. }
  650. decodedTacticsRequestPrivateKey, err := base64.StdEncoding.DecodeString(tacticsRequestPrivateKey)
  651. if err != nil {
  652. return nil, nil, nil, nil, nil, common.ContextError(err)
  653. }
  654. decodedTacticsRequestObfuscatedKey, err := base64.StdEncoding.DecodeString(tacticsRequestObfuscatedKey)
  655. if err != nil {
  656. return nil, nil, nil, nil, nil, common.ContextError(err)
  657. }
  658. tacticsConfig := &tactics.Server{
  659. RequestPublicKey: decodedTacticsRequestPublicKey,
  660. RequestPrivateKey: decodedTacticsRequestPrivateKey,
  661. RequestObfuscatedKey: decodedTacticsRequestObfuscatedKey,
  662. DefaultTactics: tactics.Tactics{
  663. TTL: "1m",
  664. Probability: 1.0,
  665. },
  666. }
  667. encodedTacticsConfig, err = json.MarshalIndent(tacticsConfig, "\n", " ")
  668. if err != nil {
  669. return nil, nil, nil, nil, nil, common.ContextError(err)
  670. }
  671. }
  672. capabilities := []string{}
  673. if params.EnableSSHAPIRequests {
  674. capabilities = append(capabilities, protocol.CAPABILITY_SSH_API_REQUESTS)
  675. }
  676. if params.WebServerPort != 0 {
  677. capabilities = append(capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  678. }
  679. for tunnelProtocol := range params.TunnelProtocolPorts {
  680. capabilities = append(capabilities, protocol.GetCapability(tunnelProtocol))
  681. if params.TacticsRequestPublicKey != "" && params.TacticsRequestObfuscatedKey != "" &&
  682. protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  683. capabilities = append(capabilities, protocol.GetTacticsCapability(tunnelProtocol))
  684. }
  685. }
  686. sshPort := params.TunnelProtocolPorts["SSH"]
  687. obfuscatedSSHPort := params.TunnelProtocolPorts["OSSH"]
  688. obfuscatedSSHQUICPort := params.TunnelProtocolPorts["QUIC-OSSH"]
  689. // Meek port limitations
  690. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  691. // - only one other meek port may be specified.
  692. meekPort := params.TunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  693. if meekPort == 0 {
  694. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  695. }
  696. if meekPort == 0 {
  697. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-SESSION-TICKET-OSSH"]
  698. }
  699. // Note: fronting params are a stub; this server entry will exercise
  700. // client and server fronting code paths, but not actually traverse
  701. // a fronting hop.
  702. serverEntryWebServerPort := ""
  703. strippedWebServerCertificate := ""
  704. if params.WebServerPort != 0 {
  705. serverEntryWebServerPort = fmt.Sprintf("%d", params.WebServerPort)
  706. // Server entry format omits the BEGIN/END lines and newlines
  707. lines := strings.Split(webServerCertificate, "\n")
  708. strippedWebServerCertificate = strings.Join(lines[1:len(lines)-2], "")
  709. }
  710. serverEntry := &protocol.ServerEntry{
  711. IpAddress: params.ServerIPAddress,
  712. WebServerPort: serverEntryWebServerPort,
  713. WebServerSecret: webServerSecret,
  714. WebServerCertificate: strippedWebServerCertificate,
  715. SshPort: sshPort,
  716. SshUsername: sshUserName,
  717. SshPassword: sshPassword,
  718. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  719. SshObfuscatedPort: obfuscatedSSHPort,
  720. SshObfuscatedQUICPort: obfuscatedSSHQUICPort,
  721. SshObfuscatedKey: obfuscatedSSHKey,
  722. Capabilities: capabilities,
  723. Region: "US",
  724. MeekServerPort: meekPort,
  725. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  726. MeekObfuscatedKey: meekObfuscatedKey,
  727. MeekFrontingHosts: []string{params.ServerIPAddress},
  728. MeekFrontingAddresses: []string{params.ServerIPAddress},
  729. MeekFrontingDisableSNI: false,
  730. TacticsRequestPublicKey: tacticsRequestPublicKey,
  731. TacticsRequestObfuscatedKey: tacticsRequestObfuscatedKey,
  732. MarionetteFormat: params.MarionetteFormat,
  733. ConfigurationVersion: 1,
  734. }
  735. encodedServerEntry, err := protocol.EncodeServerEntry(serverEntry)
  736. if err != nil {
  737. return nil, nil, nil, nil, nil, common.ContextError(err)
  738. }
  739. return encodedConfig, encodedTrafficRulesSet, encodedOSLConfig, encodedTacticsConfig, []byte(encodedServerEntry), nil
  740. }