config.go 35 KB

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