config.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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 Psiphon automation
  79. // jsonpickle format Psiphon API data file.
  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. sshBeginHandshakeTimeout time.Duration
  286. sshHandshakeTimeout time.Duration
  287. }
  288. // RunWebServer indicates whether to run a web server component.
  289. func (config *Config) RunWebServer() bool {
  290. return config.WebServerPort > 0
  291. }
  292. // RunLoadMonitor indicates whether to monitor and log server load.
  293. func (config *Config) RunLoadMonitor() bool {
  294. return config.LoadMonitorPeriodSeconds > 0
  295. }
  296. // RunPeriodicGarbageCollection indicates whether to run periodic garbage collection.
  297. func (config *Config) RunPeriodicGarbageCollection() bool {
  298. return config.PeriodicGarbageCollectionSeconds > 0
  299. }
  300. // LoadConfig loads and validates a JSON encoded server config.
  301. func LoadConfig(configJSON []byte) (*Config, error) {
  302. var config Config
  303. err := json.Unmarshal(configJSON, &config)
  304. if err != nil {
  305. return nil, common.ContextError(err)
  306. }
  307. if config.ServerIPAddress == "" {
  308. return nil, errors.New("ServerIPAddress is required")
  309. }
  310. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  311. config.WebServerPrivateKey == "") {
  312. return nil, errors.New(
  313. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  314. }
  315. if config.WebServerPortForwardAddress != "" {
  316. if err := validateNetworkAddress(config.WebServerPortForwardAddress, false); err != nil {
  317. return nil, errors.New("WebServerPortForwardAddress is invalid")
  318. }
  319. }
  320. if config.WebServerPortForwardRedirectAddress != "" {
  321. if config.WebServerPortForwardAddress == "" {
  322. return nil, errors.New(
  323. "WebServerPortForwardRedirectAddress requires WebServerPortForwardAddress")
  324. }
  325. if err := validateNetworkAddress(config.WebServerPortForwardRedirectAddress, false); err != nil {
  326. return nil, errors.New("WebServerPortForwardRedirectAddress is invalid")
  327. }
  328. }
  329. for tunnelProtocol, port := range config.TunnelProtocolPorts {
  330. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  331. return nil, fmt.Errorf("Unsupported tunnel protocol: %s", tunnelProtocol)
  332. }
  333. if protocol.TunnelProtocolUsesSSH(tunnelProtocol) ||
  334. protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  335. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  336. config.SSHUserName == "" || config.SSHPassword == "" {
  337. return nil, fmt.Errorf(
  338. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  339. tunnelProtocol)
  340. }
  341. }
  342. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  343. if config.ObfuscatedSSHKey == "" {
  344. return nil, fmt.Errorf(
  345. "Tunnel protocol %s requires ObfuscatedSSHKey",
  346. tunnelProtocol)
  347. }
  348. }
  349. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  350. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  351. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  352. return nil, fmt.Errorf(
  353. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  354. tunnelProtocol)
  355. }
  356. }
  357. if protocol.TunnelProtocolUsesMarionette(tunnelProtocol) {
  358. if port != 0 {
  359. return nil, fmt.Errorf(
  360. "Tunnel protocol %s port is specified in format, not TunnelProtocolPorts",
  361. tunnelProtocol)
  362. }
  363. }
  364. }
  365. config.sshBeginHandshakeTimeout = SSH_BEGIN_HANDSHAKE_TIMEOUT
  366. if config.SSHBeginHandshakeTimeoutMilliseconds != nil {
  367. config.sshBeginHandshakeTimeout = time.Duration(*config.SSHBeginHandshakeTimeoutMilliseconds) * time.Millisecond
  368. }
  369. config.sshHandshakeTimeout = SSH_HANDSHAKE_TIMEOUT
  370. if config.SSHHandshakeTimeoutMilliseconds != nil {
  371. config.sshHandshakeTimeout = time.Duration(*config.SSHHandshakeTimeoutMilliseconds) * time.Millisecond
  372. }
  373. if config.ObfuscatedSSHKey != "" {
  374. seed, err := protocol.DeriveSSHServerVersionPRNGSeed(config.ObfuscatedSSHKey)
  375. if err != nil {
  376. return nil, fmt.Errorf(
  377. "DeriveSSHServerVersionPRNGSeed failed: %s", err)
  378. }
  379. serverVersion := pickSSHServerVersion(seed)
  380. if serverVersion != "" {
  381. config.SSHServerVersion = serverVersion
  382. }
  383. }
  384. if config.UDPInterceptUdpgwServerAddress != "" {
  385. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress, true); err != nil {
  386. return nil, fmt.Errorf("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  387. }
  388. }
  389. if config.DNSResolverIPAddress != "" {
  390. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  391. return nil, fmt.Errorf("DNSResolverIPAddress is invalid")
  392. }
  393. }
  394. err = accesscontrol.ValidateVerificationKeyRing(&config.AccessControlVerificationKeyRing)
  395. if err != nil {
  396. return nil, fmt.Errorf(
  397. "AccessControlVerificationKeyRing is invalid: %s", err)
  398. }
  399. return &config, nil
  400. }
  401. func validateNetworkAddress(address string, requireIPaddress bool) error {
  402. host, portStr, err := net.SplitHostPort(address)
  403. if err != nil {
  404. return err
  405. }
  406. if requireIPaddress && net.ParseIP(host) == nil {
  407. return errors.New("host must be an IP address")
  408. }
  409. port, err := strconv.Atoi(portStr)
  410. if err != nil {
  411. return err
  412. }
  413. if port < 0 || port > 65535 {
  414. return errors.New("invalid port")
  415. }
  416. return nil
  417. }
  418. // GenerateConfigParams specifies customizations to be applied to
  419. // a generated server config.
  420. type GenerateConfigParams struct {
  421. LogFilename string
  422. SkipPanickingLogWriter bool
  423. LogLevel string
  424. ServerIPAddress string
  425. WebServerPort int
  426. EnableSSHAPIRequests bool
  427. TunnelProtocolPorts map[string]int
  428. MarionetteFormat string
  429. TrafficRulesConfigFilename string
  430. OSLConfigFilename string
  431. TacticsConfigFilename string
  432. TacticsRequestPublicKey string
  433. TacticsRequestObfuscatedKey string
  434. }
  435. // GenerateConfig creates a new Psiphon server config. It returns JSON encoded
  436. // configs and a client-compatible "server entry" for the server. It generates
  437. // all necessary secrets and key material, which are emitted in the config
  438. // file and server entry as necessary.
  439. //
  440. // GenerateConfig uses sample values for many fields. The intention is for
  441. // generated configs to be used for testing or as examples for production
  442. // setup, not to generate production-ready configurations.
  443. //
  444. // When tactics key material is provided in GenerateConfigParams, tactics
  445. // capabilities are added for all meek protocols in TunnelProtocolPorts.
  446. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, []byte, []byte, error) {
  447. // Input validation
  448. if net.ParseIP(params.ServerIPAddress) == nil {
  449. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid IP address"))
  450. }
  451. if len(params.TunnelProtocolPorts) == 0 {
  452. return nil, nil, nil, nil, nil, common.ContextError(errors.New("no tunnel protocols"))
  453. }
  454. usedPort := make(map[int]bool)
  455. if params.WebServerPort != 0 {
  456. usedPort[params.WebServerPort] = true
  457. }
  458. usingMeek := false
  459. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  460. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  461. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid tunnel protocol"))
  462. }
  463. if usedPort[port] {
  464. return nil, nil, nil, nil, nil, common.ContextError(errors.New("duplicate listening port"))
  465. }
  466. usedPort[port] = true
  467. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  468. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  469. usingMeek = true
  470. }
  471. }
  472. // One test mode populates the tactics config file; this will generate
  473. // keys. Another test mode passes in existing keys to be used in the
  474. // server entry. Both the filename and existing keys cannot be passed in.
  475. if (params.TacticsConfigFilename != "") &&
  476. (params.TacticsRequestPublicKey != "" || params.TacticsRequestObfuscatedKey != "") {
  477. return nil, nil, nil, nil, nil, common.ContextError(errors.New("invalid tactics parameters"))
  478. }
  479. // Web server config
  480. var webServerSecret, webServerCertificate,
  481. webServerPrivateKey, webServerPortForwardAddress string
  482. if params.WebServerPort != 0 {
  483. webServerSecretBytes, err := common.MakeSecureRandomBytes(WEB_SERVER_SECRET_BYTE_LENGTH)
  484. if err != nil {
  485. return nil, nil, nil, nil, nil, common.ContextError(err)
  486. }
  487. webServerSecret = hex.EncodeToString(webServerSecretBytes)
  488. webServerCertificate, webServerPrivateKey, err = common.GenerateWebServerCertificate("")
  489. if err != nil {
  490. return nil, nil, nil, nil, nil, common.ContextError(err)
  491. }
  492. webServerPortForwardAddress = net.JoinHostPort(
  493. params.ServerIPAddress, strconv.Itoa(params.WebServerPort))
  494. }
  495. // SSH config
  496. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  497. if err != nil {
  498. return nil, nil, nil, nil, nil, common.ContextError(err)
  499. }
  500. sshPrivateKey := pem.EncodeToMemory(
  501. &pem.Block{
  502. Type: "RSA PRIVATE KEY",
  503. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  504. },
  505. )
  506. signer, err := ssh.NewSignerFromKey(rsaKey)
  507. if err != nil {
  508. return nil, nil, nil, nil, nil, common.ContextError(err)
  509. }
  510. sshPublicKey := signer.PublicKey()
  511. sshUserNameSuffixBytes, err := common.MakeSecureRandomBytes(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  512. if err != nil {
  513. return nil, nil, nil, nil, nil, common.ContextError(err)
  514. }
  515. sshUserNameSuffix := hex.EncodeToString(sshUserNameSuffixBytes)
  516. sshUserName := "psiphon_" + sshUserNameSuffix
  517. sshPasswordBytes, err := common.MakeSecureRandomBytes(SSH_PASSWORD_BYTE_LENGTH)
  518. if err != nil {
  519. return nil, nil, nil, nil, nil, common.ContextError(err)
  520. }
  521. sshPassword := hex.EncodeToString(sshPasswordBytes)
  522. sshServerVersion := "SSH-2.0-Psiphon"
  523. // Obfuscated SSH config
  524. obfuscatedSSHKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  525. if err != nil {
  526. return nil, nil, nil, nil, nil, common.ContextError(err)
  527. }
  528. obfuscatedSSHKey := hex.EncodeToString(obfuscatedSSHKeyBytes)
  529. // Meek config
  530. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  531. if usingMeek {
  532. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  533. box.GenerateKey(rand.Reader)
  534. if err != nil {
  535. return nil, nil, nil, nil, nil, common.ContextError(err)
  536. }
  537. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  538. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  539. meekObfuscatedKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  540. if err != nil {
  541. return nil, nil, nil, nil, nil, common.ContextError(err)
  542. }
  543. meekObfuscatedKey = hex.EncodeToString(meekObfuscatedKeyBytes)
  544. }
  545. // Other config
  546. discoveryValueHMACKeyBytes, err := common.MakeSecureRandomBytes(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  547. if err != nil {
  548. return nil, nil, nil, nil, nil, common.ContextError(err)
  549. }
  550. discoveryValueHMACKey := base64.RawURLEncoding.EncodeToString(discoveryValueHMACKeyBytes)
  551. // Assemble configs and server entry
  552. // Note: this config is intended for either testing or as an illustrative
  553. // example or template and is not intended for production deployment.
  554. logLevel := params.LogLevel
  555. if logLevel == "" {
  556. logLevel = "info"
  557. }
  558. config := &Config{
  559. LogLevel: logLevel,
  560. LogFilename: params.LogFilename,
  561. SkipPanickingLogWriter: params.SkipPanickingLogWriter,
  562. GeoIPDatabaseFilenames: nil,
  563. HostID: "example-host-id",
  564. ServerIPAddress: params.ServerIPAddress,
  565. DiscoveryValueHMACKey: discoveryValueHMACKey,
  566. WebServerPort: params.WebServerPort,
  567. WebServerSecret: webServerSecret,
  568. WebServerCertificate: webServerCertificate,
  569. WebServerPrivateKey: webServerPrivateKey,
  570. WebServerPortForwardAddress: webServerPortForwardAddress,
  571. SSHPrivateKey: string(sshPrivateKey),
  572. SSHServerVersion: sshServerVersion,
  573. SSHUserName: sshUserName,
  574. SSHPassword: sshPassword,
  575. ObfuscatedSSHKey: obfuscatedSSHKey,
  576. TunnelProtocolPorts: params.TunnelProtocolPorts,
  577. DNSResolverIPAddress: "8.8.8.8",
  578. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  579. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  580. MeekObfuscatedKey: meekObfuscatedKey,
  581. MeekProhibitedHeaders: nil,
  582. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  583. LoadMonitorPeriodSeconds: 300,
  584. TrafficRulesFilename: params.TrafficRulesConfigFilename,
  585. OSLConfigFilename: params.OSLConfigFilename,
  586. TacticsConfigFilename: params.TacticsConfigFilename,
  587. MarionetteFormat: params.MarionetteFormat,
  588. }
  589. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  590. if err != nil {
  591. return nil, nil, nil, nil, nil, common.ContextError(err)
  592. }
  593. intPtr := func(i int) *int {
  594. return &i
  595. }
  596. trafficRulesSet := &TrafficRulesSet{
  597. DefaultRules: TrafficRules{
  598. RateLimits: RateLimits{
  599. ReadUnthrottledBytes: new(int64),
  600. ReadBytesPerSecond: new(int64),
  601. WriteUnthrottledBytes: new(int64),
  602. WriteBytesPerSecond: new(int64),
  603. },
  604. IdleTCPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  605. IdleUDPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  606. MaxTCPPortForwardCount: intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT),
  607. MaxUDPPortForwardCount: intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT),
  608. AllowTCPPorts: nil,
  609. AllowUDPPorts: nil,
  610. },
  611. }
  612. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  613. if err != nil {
  614. return nil, nil, nil, nil, nil, common.ContextError(err)
  615. }
  616. encodedOSLConfig, err := json.MarshalIndent(&osl.Config{}, "\n", " ")
  617. if err != nil {
  618. return nil, nil, nil, nil, nil, common.ContextError(err)
  619. }
  620. tacticsRequestPublicKey := params.TacticsRequestPublicKey
  621. tacticsRequestObfuscatedKey := params.TacticsRequestObfuscatedKey
  622. var tacticsRequestPrivateKey string
  623. var encodedTacticsConfig []byte
  624. if params.TacticsConfigFilename != "" {
  625. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err =
  626. tactics.GenerateKeys()
  627. if err != nil {
  628. return nil, nil, nil, nil, nil, common.ContextError(err)
  629. }
  630. decodedTacticsRequestPublicKey, err := base64.StdEncoding.DecodeString(tacticsRequestPublicKey)
  631. if err != nil {
  632. return nil, nil, nil, nil, nil, common.ContextError(err)
  633. }
  634. decodedTacticsRequestPrivateKey, err := base64.StdEncoding.DecodeString(tacticsRequestPrivateKey)
  635. if err != nil {
  636. return nil, nil, nil, nil, nil, common.ContextError(err)
  637. }
  638. decodedTacticsRequestObfuscatedKey, err := base64.StdEncoding.DecodeString(tacticsRequestObfuscatedKey)
  639. if err != nil {
  640. return nil, nil, nil, nil, nil, common.ContextError(err)
  641. }
  642. tacticsConfig := &tactics.Server{
  643. RequestPublicKey: decodedTacticsRequestPublicKey,
  644. RequestPrivateKey: decodedTacticsRequestPrivateKey,
  645. RequestObfuscatedKey: decodedTacticsRequestObfuscatedKey,
  646. DefaultTactics: tactics.Tactics{
  647. TTL: "1m",
  648. Probability: 1.0,
  649. },
  650. }
  651. encodedTacticsConfig, err = json.MarshalIndent(tacticsConfig, "\n", " ")
  652. if err != nil {
  653. return nil, nil, nil, nil, nil, common.ContextError(err)
  654. }
  655. }
  656. capabilities := []string{}
  657. if params.EnableSSHAPIRequests {
  658. capabilities = append(capabilities, protocol.CAPABILITY_SSH_API_REQUESTS)
  659. }
  660. if params.WebServerPort != 0 {
  661. capabilities = append(capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  662. }
  663. for tunnelProtocol := range params.TunnelProtocolPorts {
  664. capabilities = append(capabilities, protocol.GetCapability(tunnelProtocol))
  665. if params.TacticsRequestPublicKey != "" && params.TacticsRequestObfuscatedKey != "" &&
  666. protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  667. capabilities = append(capabilities, protocol.GetTacticsCapability(tunnelProtocol))
  668. }
  669. }
  670. sshPort := params.TunnelProtocolPorts["SSH"]
  671. obfuscatedSSHPort := params.TunnelProtocolPorts["OSSH"]
  672. obfuscatedSSHQUICPort := params.TunnelProtocolPorts["QUIC-OSSH"]
  673. // Meek port limitations
  674. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  675. // - only one other meek port may be specified.
  676. meekPort := params.TunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  677. if meekPort == 0 {
  678. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  679. }
  680. if meekPort == 0 {
  681. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-SESSION-TICKET-OSSH"]
  682. }
  683. // Note: fronting params are a stub; this server entry will exercise
  684. // client and server fronting code paths, but not actually traverse
  685. // a fronting hop.
  686. serverEntryWebServerPort := ""
  687. strippedWebServerCertificate := ""
  688. if params.WebServerPort != 0 {
  689. serverEntryWebServerPort = fmt.Sprintf("%d", params.WebServerPort)
  690. // Server entry format omits the BEGIN/END lines and newlines
  691. lines := strings.Split(webServerCertificate, "\n")
  692. strippedWebServerCertificate = strings.Join(lines[1:len(lines)-2], "")
  693. }
  694. serverEntry := &protocol.ServerEntry{
  695. IpAddress: params.ServerIPAddress,
  696. WebServerPort: serverEntryWebServerPort,
  697. WebServerSecret: webServerSecret,
  698. WebServerCertificate: strippedWebServerCertificate,
  699. SshPort: sshPort,
  700. SshUsername: sshUserName,
  701. SshPassword: sshPassword,
  702. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  703. SshObfuscatedPort: obfuscatedSSHPort,
  704. SshObfuscatedQUICPort: obfuscatedSSHQUICPort,
  705. SshObfuscatedKey: obfuscatedSSHKey,
  706. Capabilities: capabilities,
  707. Region: "US",
  708. MeekServerPort: meekPort,
  709. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  710. MeekObfuscatedKey: meekObfuscatedKey,
  711. MeekFrontingHosts: []string{params.ServerIPAddress},
  712. MeekFrontingAddresses: []string{params.ServerIPAddress},
  713. MeekFrontingDisableSNI: false,
  714. TacticsRequestPublicKey: tacticsRequestPublicKey,
  715. TacticsRequestObfuscatedKey: tacticsRequestObfuscatedKey,
  716. MarionetteFormat: params.MarionetteFormat,
  717. ConfigurationVersion: 1,
  718. }
  719. encodedServerEntry, err := protocol.EncodeServerEntry(serverEntry)
  720. if err != nil {
  721. return nil, nil, nil, nil, nil, common.ContextError(err)
  722. }
  723. return encodedConfig, encodedTrafficRulesSet, encodedOSLConfig, encodedTacticsConfig, []byte(encodedServerEntry), nil
  724. }