config.go 36 KB

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