config.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. // MaxConcurrentSSHHandshakes specifies a limit on the number of concurrent
  265. // SSH handshake negotiations. This is set to mitigate spikes in memory
  266. // allocations and CPU usage associated with SSH handshakes when many clients
  267. // attempt to connect concurrently. When a maximum limit is specified and
  268. // reached, additional clients that establish TCP or meek connections will
  269. // be disconnected after a short wait for the number of concurrent handshakes
  270. // to drop below the limit.
  271. // The default, 0 is no limit.
  272. MaxConcurrentSSHHandshakes int
  273. // PeriodicGarbageCollectionSeconds turns on periodic calls to
  274. // debug.FreeOSMemory, every specified number of seconds, to force garbage
  275. // collection and memory scavenging. Specify 0 to disable. The default is
  276. // PERIODIC_GARBAGE_COLLECTION.
  277. PeriodicGarbageCollectionSeconds *int
  278. // StopEstablishTunnelsEstablishedClientThreshold sets the established client
  279. // threshold for dumping profiles when SIGTSTP is signaled. When there are
  280. // less than or equal to the threshold number of established clients,
  281. // profiles are dumped to aid investigating unusual load limited states that
  282. // occur when few clients are connected and load should be relatively low. A
  283. // profile dump is attempted at most once per process lifetime, the first
  284. // time the threshold is met. Disabled when < 0.
  285. StopEstablishTunnelsEstablishedClientThreshold *int
  286. // AccessControlVerificationKeyRing is the access control authorization
  287. // verification key ring used to verify signed authorizations presented
  288. // by clients. Verified, active (unexpired) access control types will be
  289. // available for matching in the TrafficRulesFilter for the client via
  290. // AuthorizedAccessTypes. All other authorizations are ignored.
  291. AccessControlVerificationKeyRing accesscontrol.VerificationKeyRing
  292. // TacticsConfigFilename is the path of a file containing a JSON-encoded
  293. // tactics server configuration.
  294. TacticsConfigFilename string
  295. // MarionetteFormat specifies a Marionette format to use with the
  296. // MARIONETTE-OSSH tunnel protocol. The format specifies the network
  297. // protocol port to listen on.
  298. MarionetteFormat string
  299. // BlocklistFilename is the path of a file containing a CSV-encoded
  300. // blocklist configuration. See NewBlocklist for more file format
  301. // documentation.
  302. BlocklistFilename string
  303. // BlocklistActive indicates whether to actively prevent blocklist hits in
  304. // addition to logging events.
  305. BlocklistActive bool
  306. // AllowBogons disables port forward bogon checks. This should be used only
  307. // for testing.
  308. AllowBogons bool
  309. // OwnEncodedServerEntries is a list of the server's own encoded server
  310. // entries, idenfified by server entry tag. These values are used in the
  311. // handshake API to update clients that don't yet have a signed copy of these
  312. // server entries.
  313. //
  314. // For purposes of compartmentalization, each server receives only its own
  315. // server entries here; and, besides the discovery server entries, in
  316. // psinet.Database, necessary for the discovery feature, no other server
  317. // entries are stored on a Psiphon server.
  318. OwnEncodedServerEntries map[string]string
  319. sshBeginHandshakeTimeout time.Duration
  320. sshHandshakeTimeout time.Duration
  321. periodicGarbageCollection time.Duration
  322. stopEstablishTunnelsEstablishedClientThreshold int
  323. dumpProfilesOnStopEstablishTunnelsDone int32
  324. }
  325. // RunWebServer indicates whether to run a web server component.
  326. func (config *Config) RunWebServer() bool {
  327. return config.WebServerPort > 0
  328. }
  329. // RunLoadMonitor indicates whether to monitor and log server load.
  330. func (config *Config) RunLoadMonitor() bool {
  331. return config.LoadMonitorPeriodSeconds > 0
  332. }
  333. // RunPeriodicGarbageCollection indicates whether to run periodic garbage collection.
  334. func (config *Config) RunPeriodicGarbageCollection() bool {
  335. return config.periodicGarbageCollection > 0
  336. }
  337. // DumpProfilesOnStopEstablishTunnels indicates whether dump profiles due to
  338. // an unexpectedly low number of established clients during high load.
  339. func (config *Config) DumpProfilesOnStopEstablishTunnels(establishedClientsCount int) bool {
  340. if config.stopEstablishTunnelsEstablishedClientThreshold < 0 {
  341. return false
  342. }
  343. if atomic.LoadInt32(&config.dumpProfilesOnStopEstablishTunnelsDone) != 0 {
  344. return false
  345. }
  346. dump := (establishedClientsCount <= config.stopEstablishTunnelsEstablishedClientThreshold)
  347. atomic.StoreInt32(&config.dumpProfilesOnStopEstablishTunnelsDone, 1)
  348. return dump
  349. }
  350. // GetOwnEncodedServerEntry returns one of the server's own server entries, as
  351. // identified by the server entry tag.
  352. func (config *Config) GetOwnEncodedServerEntry(serverEntryTag string) (string, bool) {
  353. serverEntry, ok := config.OwnEncodedServerEntries[serverEntryTag]
  354. return serverEntry, ok
  355. }
  356. // LoadConfig loads and validates a JSON encoded server config.
  357. func LoadConfig(configJSON []byte) (*Config, error) {
  358. var config Config
  359. err := json.Unmarshal(configJSON, &config)
  360. if err != nil {
  361. return nil, errors.Trace(err)
  362. }
  363. if config.ServerIPAddress == "" {
  364. return nil, errors.TraceNew("ServerIPAddress is required")
  365. }
  366. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  367. config.WebServerPrivateKey == "") {
  368. return nil, errors.TraceNew(
  369. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  370. }
  371. if config.WebServerPortForwardAddress != "" {
  372. if err := validateNetworkAddress(config.WebServerPortForwardAddress, false); err != nil {
  373. return nil, errors.TraceNew("WebServerPortForwardAddress is invalid")
  374. }
  375. }
  376. if config.WebServerPortForwardRedirectAddress != "" {
  377. if config.WebServerPortForwardAddress == "" {
  378. return nil, errors.TraceNew(
  379. "WebServerPortForwardRedirectAddress requires WebServerPortForwardAddress")
  380. }
  381. if err := validateNetworkAddress(config.WebServerPortForwardRedirectAddress, false); err != nil {
  382. return nil, errors.TraceNew("WebServerPortForwardRedirectAddress is invalid")
  383. }
  384. }
  385. for tunnelProtocol, port := range config.TunnelProtocolPorts {
  386. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  387. return nil, errors.Tracef("Unsupported tunnel protocol: %s", tunnelProtocol)
  388. }
  389. if protocol.TunnelProtocolUsesSSH(tunnelProtocol) ||
  390. protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  391. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  392. config.SSHUserName == "" || config.SSHPassword == "" {
  393. return nil, errors.Tracef(
  394. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  395. tunnelProtocol)
  396. }
  397. }
  398. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  399. if config.ObfuscatedSSHKey == "" {
  400. return nil, errors.Tracef(
  401. "Tunnel protocol %s requires ObfuscatedSSHKey",
  402. tunnelProtocol)
  403. }
  404. }
  405. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  406. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  407. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  408. return nil, errors.Tracef(
  409. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  410. tunnelProtocol)
  411. }
  412. }
  413. if protocol.TunnelProtocolUsesMarionette(tunnelProtocol) {
  414. if port != 0 {
  415. return nil, errors.Tracef(
  416. "Tunnel protocol %s port is specified in format, not TunnelProtocolPorts",
  417. tunnelProtocol)
  418. }
  419. }
  420. }
  421. for tunnelProtocol, address := range config.TunnelProtocolPassthroughAddresses {
  422. if !protocol.TunnelProtocolSupportsPassthrough(tunnelProtocol) {
  423. return nil, errors.Tracef("Passthrough unsupported tunnel protocol: %s", tunnelProtocol)
  424. }
  425. if _, _, err := net.SplitHostPort(address); err != nil {
  426. if err != nil {
  427. return nil, errors.Tracef(
  428. "Tunnel protocol %s passthrough address %s invalid: %s",
  429. tunnelProtocol, address, err)
  430. }
  431. }
  432. }
  433. config.sshBeginHandshakeTimeout = SSH_BEGIN_HANDSHAKE_TIMEOUT
  434. if config.SSHBeginHandshakeTimeoutMilliseconds != nil {
  435. config.sshBeginHandshakeTimeout = time.Duration(*config.SSHBeginHandshakeTimeoutMilliseconds) * time.Millisecond
  436. }
  437. config.sshHandshakeTimeout = SSH_HANDSHAKE_TIMEOUT
  438. if config.SSHHandshakeTimeoutMilliseconds != nil {
  439. config.sshHandshakeTimeout = time.Duration(*config.SSHHandshakeTimeoutMilliseconds) * time.Millisecond
  440. }
  441. if config.ObfuscatedSSHKey != "" {
  442. seed, err := protocol.DeriveSSHServerVersionPRNGSeed(config.ObfuscatedSSHKey)
  443. if err != nil {
  444. return nil, errors.Tracef(
  445. "DeriveSSHServerVersionPRNGSeed failed: %s", err)
  446. }
  447. serverVersion := values.GetSSHServerVersion(seed)
  448. if serverVersion != "" {
  449. config.SSHServerVersion = serverVersion
  450. }
  451. }
  452. if config.UDPInterceptUdpgwServerAddress != "" {
  453. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress, true); err != nil {
  454. return nil, errors.Tracef("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  455. }
  456. }
  457. if config.DNSResolverIPAddress != "" {
  458. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  459. return nil, errors.Tracef("DNSResolverIPAddress is invalid")
  460. }
  461. }
  462. config.periodicGarbageCollection = PERIODIC_GARBAGE_COLLECTION
  463. if config.PeriodicGarbageCollectionSeconds != nil {
  464. config.periodicGarbageCollection = time.Duration(*config.PeriodicGarbageCollectionSeconds) * time.Second
  465. }
  466. config.stopEstablishTunnelsEstablishedClientThreshold = STOP_ESTABLISH_TUNNELS_ESTABLISHED_CLIENT_THRESHOLD
  467. if config.StopEstablishTunnelsEstablishedClientThreshold != nil {
  468. config.stopEstablishTunnelsEstablishedClientThreshold = *config.StopEstablishTunnelsEstablishedClientThreshold
  469. }
  470. err = accesscontrol.ValidateVerificationKeyRing(&config.AccessControlVerificationKeyRing)
  471. if err != nil {
  472. return nil, errors.Tracef(
  473. "AccessControlVerificationKeyRing is invalid: %s", err)
  474. }
  475. return &config, nil
  476. }
  477. func validateNetworkAddress(address string, requireIPaddress bool) error {
  478. host, portStr, err := net.SplitHostPort(address)
  479. if err != nil {
  480. return err
  481. }
  482. if requireIPaddress && net.ParseIP(host) == nil {
  483. return errors.TraceNew("host must be an IP address")
  484. }
  485. port, err := strconv.Atoi(portStr)
  486. if err != nil {
  487. return err
  488. }
  489. if port < 0 || port > 65535 {
  490. return errors.TraceNew("invalid port")
  491. }
  492. return nil
  493. }
  494. // GenerateConfigParams specifies customizations to be applied to
  495. // a generated server config.
  496. type GenerateConfigParams struct {
  497. LogFilename string
  498. SkipPanickingLogWriter bool
  499. LogLevel string
  500. ServerIPAddress string
  501. WebServerPort int
  502. EnableSSHAPIRequests bool
  503. TunnelProtocolPorts map[string]int
  504. MarionetteFormat string
  505. TrafficRulesConfigFilename string
  506. OSLConfigFilename string
  507. TacticsConfigFilename string
  508. TacticsRequestPublicKey string
  509. TacticsRequestObfuscatedKey string
  510. }
  511. // GenerateConfig creates a new Psiphon server config. It returns JSON encoded
  512. // configs and a client-compatible "server entry" for the server. It generates
  513. // all necessary secrets and key material, which are emitted in the config
  514. // file and server entry as necessary.
  515. //
  516. // GenerateConfig uses sample values for many fields. The intention is for
  517. // generated configs to be used for testing or as examples for production
  518. // setup, not to generate production-ready configurations.
  519. //
  520. // When tactics key material is provided in GenerateConfigParams, tactics
  521. // capabilities are added for all meek protocols in TunnelProtocolPorts.
  522. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, []byte, []byte, error) {
  523. // Input validation
  524. if net.ParseIP(params.ServerIPAddress) == nil {
  525. return nil, nil, nil, nil, nil, errors.TraceNew("invalid IP address")
  526. }
  527. if len(params.TunnelProtocolPorts) == 0 {
  528. return nil, nil, nil, nil, nil, errors.TraceNew("no tunnel protocols")
  529. }
  530. usedPort := make(map[int]bool)
  531. if params.WebServerPort != 0 {
  532. usedPort[params.WebServerPort] = true
  533. }
  534. usingMeek := false
  535. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  536. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  537. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tunnel protocol")
  538. }
  539. if usedPort[port] {
  540. return nil, nil, nil, nil, nil, errors.TraceNew("duplicate listening port")
  541. }
  542. usedPort[port] = true
  543. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  544. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  545. usingMeek = true
  546. }
  547. }
  548. // One test mode populates the tactics config file; this will generate
  549. // keys. Another test mode passes in existing keys to be used in the
  550. // server entry. Both the filename and existing keys cannot be passed in.
  551. if (params.TacticsConfigFilename != "") &&
  552. (params.TacticsRequestPublicKey != "" || params.TacticsRequestObfuscatedKey != "") {
  553. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tactics parameters")
  554. }
  555. // Web server config
  556. var webServerSecret, webServerCertificate,
  557. webServerPrivateKey, webServerPortForwardAddress string
  558. if params.WebServerPort != 0 {
  559. webServerSecretBytes, err := common.MakeSecureRandomBytes(WEB_SERVER_SECRET_BYTE_LENGTH)
  560. if err != nil {
  561. return nil, nil, nil, nil, nil, errors.Trace(err)
  562. }
  563. webServerSecret = hex.EncodeToString(webServerSecretBytes)
  564. webServerCertificate, webServerPrivateKey, err = common.GenerateWebServerCertificate("")
  565. if err != nil {
  566. return nil, nil, nil, nil, nil, errors.Trace(err)
  567. }
  568. webServerPortForwardAddress = net.JoinHostPort(
  569. params.ServerIPAddress, strconv.Itoa(params.WebServerPort))
  570. }
  571. // SSH config
  572. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  573. if err != nil {
  574. return nil, nil, nil, nil, nil, errors.Trace(err)
  575. }
  576. sshPrivateKey := pem.EncodeToMemory(
  577. &pem.Block{
  578. Type: "RSA PRIVATE KEY",
  579. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  580. },
  581. )
  582. signer, err := ssh.NewSignerFromKey(rsaKey)
  583. if err != nil {
  584. return nil, nil, nil, nil, nil, errors.Trace(err)
  585. }
  586. sshPublicKey := signer.PublicKey()
  587. sshUserNameSuffixBytes, err := common.MakeSecureRandomBytes(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  588. if err != nil {
  589. return nil, nil, nil, nil, nil, errors.Trace(err)
  590. }
  591. sshUserNameSuffix := hex.EncodeToString(sshUserNameSuffixBytes)
  592. sshUserName := "psiphon_" + sshUserNameSuffix
  593. sshPasswordBytes, err := common.MakeSecureRandomBytes(SSH_PASSWORD_BYTE_LENGTH)
  594. if err != nil {
  595. return nil, nil, nil, nil, nil, errors.Trace(err)
  596. }
  597. sshPassword := hex.EncodeToString(sshPasswordBytes)
  598. sshServerVersion := "SSH-2.0-Psiphon"
  599. // Obfuscated SSH config
  600. obfuscatedSSHKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  601. if err != nil {
  602. return nil, nil, nil, nil, nil, errors.Trace(err)
  603. }
  604. obfuscatedSSHKey := hex.EncodeToString(obfuscatedSSHKeyBytes)
  605. // Meek config
  606. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  607. if usingMeek {
  608. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  609. box.GenerateKey(rand.Reader)
  610. if err != nil {
  611. return nil, nil, nil, nil, nil, errors.Trace(err)
  612. }
  613. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  614. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  615. meekObfuscatedKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  616. if err != nil {
  617. return nil, nil, nil, nil, nil, errors.Trace(err)
  618. }
  619. meekObfuscatedKey = hex.EncodeToString(meekObfuscatedKeyBytes)
  620. }
  621. // Other config
  622. discoveryValueHMACKeyBytes, err := common.MakeSecureRandomBytes(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  623. if err != nil {
  624. return nil, nil, nil, nil, nil, errors.Trace(err)
  625. }
  626. discoveryValueHMACKey := base64.StdEncoding.EncodeToString(discoveryValueHMACKeyBytes)
  627. // Assemble configs and server entry
  628. // Note: this config is intended for either testing or as an illustrative
  629. // example or template and is not intended for production deployment.
  630. logLevel := params.LogLevel
  631. if logLevel == "" {
  632. logLevel = "info"
  633. }
  634. config := &Config{
  635. LogLevel: logLevel,
  636. LogFilename: params.LogFilename,
  637. SkipPanickingLogWriter: params.SkipPanickingLogWriter,
  638. GeoIPDatabaseFilenames: nil,
  639. HostID: "example-host-id",
  640. ServerIPAddress: params.ServerIPAddress,
  641. DiscoveryValueHMACKey: discoveryValueHMACKey,
  642. WebServerPort: params.WebServerPort,
  643. WebServerSecret: webServerSecret,
  644. WebServerCertificate: webServerCertificate,
  645. WebServerPrivateKey: webServerPrivateKey,
  646. WebServerPortForwardAddress: webServerPortForwardAddress,
  647. SSHPrivateKey: string(sshPrivateKey),
  648. SSHServerVersion: sshServerVersion,
  649. SSHUserName: sshUserName,
  650. SSHPassword: sshPassword,
  651. ObfuscatedSSHKey: obfuscatedSSHKey,
  652. TunnelProtocolPorts: params.TunnelProtocolPorts,
  653. DNSResolverIPAddress: "8.8.8.8",
  654. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  655. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  656. MeekObfuscatedKey: meekObfuscatedKey,
  657. MeekProhibitedHeaders: nil,
  658. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  659. LoadMonitorPeriodSeconds: 300,
  660. TrafficRulesFilename: params.TrafficRulesConfigFilename,
  661. OSLConfigFilename: params.OSLConfigFilename,
  662. TacticsConfigFilename: params.TacticsConfigFilename,
  663. MarionetteFormat: params.MarionetteFormat,
  664. }
  665. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  666. if err != nil {
  667. return nil, nil, nil, nil, nil, errors.Trace(err)
  668. }
  669. intPtr := func(i int) *int {
  670. return &i
  671. }
  672. trafficRulesSet := &TrafficRulesSet{
  673. DefaultRules: TrafficRules{
  674. RateLimits: RateLimits{
  675. ReadUnthrottledBytes: new(int64),
  676. ReadBytesPerSecond: new(int64),
  677. WriteUnthrottledBytes: new(int64),
  678. WriteBytesPerSecond: new(int64),
  679. },
  680. IdleTCPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  681. IdleUDPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  682. MaxTCPPortForwardCount: intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT),
  683. MaxUDPPortForwardCount: intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT),
  684. AllowTCPPorts: nil,
  685. AllowUDPPorts: nil,
  686. },
  687. }
  688. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  689. if err != nil {
  690. return nil, nil, nil, nil, nil, errors.Trace(err)
  691. }
  692. encodedOSLConfig, err := json.MarshalIndent(&osl.Config{}, "\n", " ")
  693. if err != nil {
  694. return nil, nil, nil, nil, nil, errors.Trace(err)
  695. }
  696. tacticsRequestPublicKey := params.TacticsRequestPublicKey
  697. tacticsRequestObfuscatedKey := params.TacticsRequestObfuscatedKey
  698. var tacticsRequestPrivateKey string
  699. var encodedTacticsConfig []byte
  700. if params.TacticsConfigFilename != "" {
  701. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err =
  702. tactics.GenerateKeys()
  703. if err != nil {
  704. return nil, nil, nil, nil, nil, errors.Trace(err)
  705. }
  706. decodedTacticsRequestPublicKey, err := base64.StdEncoding.DecodeString(tacticsRequestPublicKey)
  707. if err != nil {
  708. return nil, nil, nil, nil, nil, errors.Trace(err)
  709. }
  710. decodedTacticsRequestPrivateKey, err := base64.StdEncoding.DecodeString(tacticsRequestPrivateKey)
  711. if err != nil {
  712. return nil, nil, nil, nil, nil, errors.Trace(err)
  713. }
  714. decodedTacticsRequestObfuscatedKey, err := base64.StdEncoding.DecodeString(tacticsRequestObfuscatedKey)
  715. if err != nil {
  716. return nil, nil, nil, nil, nil, errors.Trace(err)
  717. }
  718. tacticsConfig := &tactics.Server{
  719. RequestPublicKey: decodedTacticsRequestPublicKey,
  720. RequestPrivateKey: decodedTacticsRequestPrivateKey,
  721. RequestObfuscatedKey: decodedTacticsRequestObfuscatedKey,
  722. DefaultTactics: tactics.Tactics{
  723. TTL: "1m",
  724. Probability: 1.0,
  725. },
  726. }
  727. encodedTacticsConfig, err = json.MarshalIndent(tacticsConfig, "\n", " ")
  728. if err != nil {
  729. return nil, nil, nil, nil, nil, errors.Trace(err)
  730. }
  731. }
  732. capabilities := []string{}
  733. if params.EnableSSHAPIRequests {
  734. capabilities = append(capabilities, protocol.CAPABILITY_SSH_API_REQUESTS)
  735. }
  736. if params.WebServerPort != 0 {
  737. capabilities = append(capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  738. }
  739. for tunnelProtocol := range params.TunnelProtocolPorts {
  740. capabilities = append(capabilities, protocol.GetCapability(tunnelProtocol))
  741. if params.TacticsRequestPublicKey != "" && params.TacticsRequestObfuscatedKey != "" &&
  742. protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  743. capabilities = append(capabilities, protocol.GetTacticsCapability(tunnelProtocol))
  744. }
  745. }
  746. sshPort := params.TunnelProtocolPorts["SSH"]
  747. obfuscatedSSHPort := params.TunnelProtocolPorts["OSSH"]
  748. obfuscatedSSHQUICPort := params.TunnelProtocolPorts["QUIC-OSSH"]
  749. // Meek port limitations
  750. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  751. // - only one other meek port may be specified.
  752. meekPort := params.TunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  753. if meekPort == 0 {
  754. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  755. }
  756. if meekPort == 0 {
  757. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-SESSION-TICKET-OSSH"]
  758. }
  759. // Note: fronting params are a stub; this server entry will exercise
  760. // client and server fronting code paths, but not actually traverse
  761. // a fronting hop.
  762. serverEntryWebServerPort := ""
  763. strippedWebServerCertificate := ""
  764. if params.WebServerPort != 0 {
  765. serverEntryWebServerPort = fmt.Sprintf("%d", params.WebServerPort)
  766. // Server entry format omits the BEGIN/END lines and newlines
  767. lines := strings.Split(webServerCertificate, "\n")
  768. strippedWebServerCertificate = strings.Join(lines[1:len(lines)-2], "")
  769. }
  770. serverEntry := &protocol.ServerEntry{
  771. IpAddress: params.ServerIPAddress,
  772. WebServerPort: serverEntryWebServerPort,
  773. WebServerSecret: webServerSecret,
  774. WebServerCertificate: strippedWebServerCertificate,
  775. SshPort: sshPort,
  776. SshUsername: sshUserName,
  777. SshPassword: sshPassword,
  778. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  779. SshObfuscatedPort: obfuscatedSSHPort,
  780. SshObfuscatedQUICPort: obfuscatedSSHQUICPort,
  781. SshObfuscatedKey: obfuscatedSSHKey,
  782. Capabilities: capabilities,
  783. Region: "US",
  784. MeekServerPort: meekPort,
  785. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  786. MeekObfuscatedKey: meekObfuscatedKey,
  787. MeekFrontingHosts: []string{params.ServerIPAddress},
  788. MeekFrontingAddresses: []string{params.ServerIPAddress},
  789. MeekFrontingDisableSNI: false,
  790. TacticsRequestPublicKey: tacticsRequestPublicKey,
  791. TacticsRequestObfuscatedKey: tacticsRequestObfuscatedKey,
  792. MarionetteFormat: params.MarionetteFormat,
  793. ConfigurationVersion: 1,
  794. }
  795. encodedServerEntry, err := protocol.EncodeServerEntry(serverEntry)
  796. if err != nil {
  797. return nil, nil, nil, nil, nil, errors.Trace(err)
  798. }
  799. return encodedConfig, encodedTrafficRulesSet, encodedOSLConfig, encodedTacticsConfig, []byte(encodedServerEntry), nil
  800. }