config.go 33 KB

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