config.go 30 KB

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