config.go 29 KB

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