config.go 26 KB

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