config.go 33 KB

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