config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. "time"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon"
  34. "golang.org/x/crypto/nacl/box"
  35. "golang.org/x/crypto/ssh"
  36. )
  37. const (
  38. SERVER_CONFIG_FILENAME = "psiphon-server.config"
  39. SERVER_ENTRY_FILENAME = "serverEntry.dat"
  40. DEFAULT_SERVER_IP_ADDRESS = "127.0.0.1"
  41. WEB_SERVER_SECRET_BYTE_LENGTH = 32
  42. DISCOVERY_VALUE_KEY_BYTE_LENGTH = 32
  43. WEB_SERVER_READ_TIMEOUT = 10 * time.Second
  44. WEB_SERVER_WRITE_TIMEOUT = 10 * time.Second
  45. SSH_USERNAME_SUFFIX_BYTE_LENGTH = 8
  46. SSH_PASSWORD_BYTE_LENGTH = 32
  47. SSH_RSA_HOST_KEY_BITS = 2048
  48. SSH_HANDSHAKE_TIMEOUT = 30 * time.Second
  49. SSH_CONNECTION_READ_DEADLINE = 5 * time.Minute
  50. SSH_TCP_PORT_FORWARD_DIAL_TIMEOUT = 30 * time.Second
  51. SSH_TCP_PORT_FORWARD_COPY_BUFFER_SIZE = 8192
  52. SSH_OBFUSCATED_KEY_BYTE_LENGTH = 32
  53. REDIS_POOL_MAX_IDLE = 50
  54. REDIS_POOL_MAX_ACTIVE = 1000
  55. REDIS_POOL_IDLE_TIMEOUT = 5 * time.Minute
  56. )
  57. // TODO: break config into sections (sub-structs)
  58. // Config specifies the configuration and behavior of a Psiphon
  59. // server.
  60. type Config struct {
  61. // LogLevel specifies the log level. Valid values are:
  62. // panic, fatal, error, warn, info, debug
  63. LogLevel string
  64. // SyslogFacility specifies the syslog facility to log to.
  65. // When set, the local syslog service is used for message
  66. // logging.
  67. // Valid values include: "user", "local0", "local1", etc.
  68. SyslogFacility string
  69. // SyslogTag specifies an optional tag for syslog log
  70. // messages. The default tag is "psiphon-server". The
  71. // fail2ban logs, if enabled, also use this tag.
  72. SyslogTag string
  73. // Fail2BanFormat is a string format specifier for the
  74. // log message format to use for fail2ban integration for
  75. // blocking abusive clients by source IP address.
  76. // When set, logs with this format are made to the AUTH
  77. // facility with INFO severity in the local syslog server
  78. // if clients fail to authenticate.
  79. // The client's IP address is included with the log message.
  80. // An example format specifier, which should be compatible
  81. // with default SSH fail2ban configuration, is
  82. // "Authentication failure for psiphon-client from %s".
  83. Fail2BanFormat string
  84. // DiscoveryValueHMACKey is the network-wide secret value
  85. // used to determine a unique discovery strategy.
  86. DiscoveryValueHMACKey string
  87. // GeoIPDatabaseFilename is the path of the GeoIP2/GeoLite2
  88. // MaxMind database file. when blank, no GeoIP lookups are
  89. // performed.
  90. GeoIPDatabaseFilename string
  91. // RedisServerAddress is the TCP address of a redis server. When
  92. // set, redis is used to store per-session GeoIP information.
  93. RedisServerAddress string
  94. // PsinetDatabaseFilename is the path of the Psiphon automation
  95. // jsonpickle format Psiphon API data file.
  96. PsinetDatabaseFilename string
  97. // HostID is the ID of the server host; this is used for API
  98. // event logging.
  99. HostID string
  100. // ServerIPAddress is the public IP address of the server.
  101. ServerIPAddress string
  102. // WebServerPort is the listening port of the web server.
  103. // When <= 0, no web server component is run.
  104. WebServerPort int
  105. // WebServerSecret is the unique secret value that the client
  106. // must supply to make requests to the web server.
  107. WebServerSecret string
  108. // WebServerCertificate is the certificate the client uses to
  109. // authenticate the web server.
  110. WebServerCertificate string
  111. // WebServerPrivateKey is the private key the web server uses to
  112. // authenticate itself to clients.
  113. WebServerPrivateKey string
  114. // TunnelProtocolPorts specifies which tunnel protocols to run
  115. // and which ports to listen on for each protocol. Valid tunnel
  116. // protocols include: "SSH", "OSSH", "UNFRONTED-MEEK-OSSH",
  117. // "UNFRONTED-MEEK-HTTPS-OSSH", "FRONTED-MEEK-OSSH",
  118. // "FRONTED-MEEK-HTTP-OSSH".
  119. TunnelProtocolPorts map[string]int
  120. // SSHPrivateKey is the SSH host key. The same key is used for
  121. // all protocols, run by this server instance, which use SSH.
  122. SSHPrivateKey string
  123. // SSHServerVersion is the server version presented in the
  124. // identification string. The same value is used for all
  125. // protocols, run by this server instance, which use SSH.
  126. SSHServerVersion string
  127. // SSHUserName is the SSH user name to be presented by the
  128. // the tunnel-core client. The same value is used for all
  129. // protocols, run by this server instance, which use SSH.
  130. SSHUserName string
  131. // SSHPassword is the SSH password to be presented by the
  132. // the tunnel-core client. The same value is used for all
  133. // protocols, run by this server instance, which use SSH.
  134. SSHPassword string
  135. // ObfuscatedSSHKey is the secret key for use in the Obfuscated
  136. // SSH protocol. The same secret key is used for all protocols,
  137. // run by this server instance, which use Obfuscated SSH.
  138. ObfuscatedSSHKey string
  139. // MeekCookieEncryptionPrivateKey is the NaCl private key used
  140. // to decrypt meek cookie payload sent from clients. The same
  141. // key is used for all meek protocols run by this server instance.
  142. MeekCookieEncryptionPrivateKey string
  143. // MeekObfuscatedKey is the secret key used for obfuscating
  144. // meek cookies sent from clients. The same key is used for all
  145. // meek protocols run by this server instance.
  146. MeekObfuscatedKey string
  147. // MeekCertificateCommonName is the value used for the hostname
  148. // in the self-signed certificate generated and used for meek
  149. // HTTPS modes. The same value is used for all HTTPS meek
  150. // protocols.
  151. MeekCertificateCommonName string
  152. // MeekProhibitedHeaders is a list of HTTP headers to check for
  153. // in client requests. If one of these headers is found, the
  154. // request fails. This is used to defend against abuse.
  155. MeekProhibitedHeaders []string
  156. // MeekProxyForwardedForHeaders is a list of HTTP headers which
  157. // may be added by downstream HTTP proxies or CDNs in front
  158. // of clients. These headers supply the original client IP
  159. // address, which is geolocated for stats purposes. Headers
  160. // include, for example, X-Forwarded-For. The header's value
  161. // is assumed to be a comma delimted list of IP addresses where
  162. // the client IP is the first IP address in the list. Meek protocols
  163. // look for these headers and use the client IP address from
  164. // the header if any one is present and the value is a valid
  165. // IP address; otherwise the direct connection remote address is
  166. // used as the client IP.
  167. MeekProxyForwardedForHeaders []string
  168. // UDPInterceptUdpgwServerAddress specifies the network address of
  169. // a udpgw server which clients may be port forwarding to. When
  170. // specified, these TCP port forwards are intercepted and handled
  171. // directly by this server, which parses the SSH channel using the
  172. // udpgw protocol.
  173. UDPInterceptUdpgwServerAddress string
  174. // DNSServerAddress specifies the network address of a DNS server
  175. // to which DNS UDP packets will be forwarded to. When set, any
  176. // tunneled DNS UDP packets will be re-routed to this destination.
  177. UDPForwardDNSServerAddress string
  178. // DefaultTrafficRules specifies the traffic rules to be used when
  179. // no regional-specific rules are set.
  180. DefaultTrafficRules TrafficRules
  181. // RegionalTrafficRules specifies the traffic rules for particular
  182. // client regions (countries) as determined by GeoIP lookup of the
  183. // client IP address. The key for each regional traffic rule entry
  184. // is one or more space delimited ISO 3166-1 alpha-2 country codes.
  185. RegionalTrafficRules map[string]TrafficRules
  186. // LoadMonitorPeriodSeconds indicates how frequently to log server
  187. // load information (number of connected clients per tunnel protocol,
  188. // number of running goroutines, amount of memory allocated, etc.)
  189. // The default, 0, disables load logging.
  190. LoadMonitorPeriodSeconds int
  191. }
  192. // RateLimits specify the rate limits for tunneled data transfer
  193. // between an individual client and the server.
  194. type RateLimits struct {
  195. // DownstreamUnlimitedBytes specifies the number of downstream
  196. // bytes to transfer, approximately, before starting rate
  197. // limiting.
  198. DownstreamUnlimitedBytes int64
  199. // DownstreamBytesPerSecond specifies a rate limit for downstream
  200. // data transfer. The default, 0, is no limit.
  201. DownstreamBytesPerSecond int
  202. // UpstreamUnlimitedBytes specifies the number of upstream
  203. // bytes to transfer, approximately, before starting rate
  204. // limiting.
  205. UpstreamUnlimitedBytes int64
  206. // UpstreamBytesPerSecond specifies a rate limit for upstream
  207. // data transfer. The default, 0, is no limit.
  208. UpstreamBytesPerSecond int
  209. }
  210. // TrafficRules specify the limits placed on client traffic.
  211. type TrafficRules struct {
  212. // DefaultRateLimitsare the rate limits to be applied when
  213. // no protocol-specific rates are set.
  214. DefaultRateLimits RateLimits
  215. // ProtocolRateLimits specifies the rate limits for particular
  216. // tunnel protocols. The key for each rate limit entry is one
  217. // or more space delimited Psiphon tunnel protocol names. Valid
  218. // tunnel protocols includes the same list as for
  219. // TunnelProtocolPorts.
  220. ProtocolRateLimits map[string]RateLimits
  221. // IdleTCPPortForwardTimeoutMilliseconds is the timeout period
  222. // after which idle (no bytes flowing in either direction)
  223. // client TCP port forwards are preemptively closed.
  224. // The default, 0, is no idle timeout.
  225. IdleTCPPortForwardTimeoutMilliseconds int
  226. // IdleUDPPortForwardTimeoutMilliseconds is the timeout period
  227. // after which idle (no bytes flowing in either direction)
  228. // client UDP port forwards are preemptively closed.
  229. // The default, 0, is no idle timeout.
  230. IdleUDPPortForwardTimeoutMilliseconds int
  231. // MaxTCPPortForwardCount is the maximum number of TCP port
  232. // forwards each client may have open concurrently.
  233. // The default, 0, is no maximum.
  234. MaxTCPPortForwardCount int
  235. // MaxUDPPortForwardCount is the maximum number of UDP port
  236. // forwards each client may have open concurrently.
  237. // The default, 0, is no maximum.
  238. MaxUDPPortForwardCount int
  239. // AllowTCPPorts specifies a whitelist of TCP ports that
  240. // are permitted for port forwarding. When set, only ports
  241. // in the list are accessible to clients.
  242. AllowTCPPorts []int
  243. // AllowUDPPorts specifies a whitelist of UDP ports that
  244. // are permitted for port forwarding. When set, only ports
  245. // in the list are accessible to clients.
  246. AllowUDPPorts []int
  247. // DenyTCPPorts specifies a blacklist of TCP ports that
  248. // are not permitted for port forwarding. When set, the
  249. // ports in the list are inaccessible to clients.
  250. DenyTCPPorts []int
  251. // DenyUDPPorts specifies a blacklist of UDP ports that
  252. // are not permitted for port forwarding. When set, the
  253. // ports in the list are inaccessible to clients.
  254. DenyUDPPorts []int
  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. // UseRedis indicates whether to store per-session GeoIP information in
  265. // redis. This is for integration with the legacy psi_web component.
  266. func (config *Config) UseRedis() bool {
  267. return config.RedisServerAddress != ""
  268. }
  269. // UseFail2Ban indicates whether to log client IP addresses, in authentication
  270. // failure cases, to the local syslog service AUTH facility for use by fail2ban.
  271. func (config *Config) UseFail2Ban() bool {
  272. return config.Fail2BanFormat != ""
  273. }
  274. // GetTrafficRules looks up the traffic rules for the specified country. If there
  275. // are no RegionalTrafficRules for the country, DefaultTrafficRules are used.
  276. func (config *Config) GetTrafficRules(clientCountryCode string) TrafficRules {
  277. // TODO: faster lookup?
  278. for countryCodes, trafficRules := range config.RegionalTrafficRules {
  279. for _, countryCode := range strings.Split(countryCodes, " ") {
  280. if countryCode == clientCountryCode {
  281. return trafficRules
  282. }
  283. }
  284. }
  285. return config.DefaultTrafficRules
  286. }
  287. // GetRateLimits looks up the rate limits for the specified tunnel protocol.
  288. // If there are no ProtocolRateLimits for the protocol, DefaultRateLimits are used.
  289. func (rules *TrafficRules) GetRateLimits(clientTunnelProtocol string) RateLimits {
  290. // TODO: faster lookup?
  291. for tunnelProtocols, rateLimits := range rules.ProtocolRateLimits {
  292. for _, tunnelProtocol := range strings.Split(tunnelProtocols, " ") {
  293. if tunnelProtocol == clientTunnelProtocol {
  294. return rateLimits
  295. }
  296. }
  297. }
  298. return rules.DefaultRateLimits
  299. }
  300. // LoadConfig loads and validates a JSON encoded server config. If more than one
  301. // JSON config is specified, then all are loaded and values are merged together,
  302. // in order. Multiple configs allows for use cases like storing static, server-specific
  303. // values in a base config while also deploying network-wide throttling settings
  304. // in a secondary file that can be paved over on all server hosts.
  305. func LoadConfig(configJSONs [][]byte) (*Config, error) {
  306. // Note: default values are set in GenerateConfig
  307. var config Config
  308. for _, configJSON := range configJSONs {
  309. err := json.Unmarshal(configJSON, &config)
  310. if err != nil {
  311. return nil, psiphon.ContextError(err)
  312. }
  313. }
  314. if config.Fail2BanFormat != "" && strings.Count(config.Fail2BanFormat, "%s") != 1 {
  315. return nil, errors.New("Fail2BanFormat must have one '%%s' placeholder")
  316. }
  317. if config.ServerIPAddress == "" {
  318. return nil, errors.New("ServerIPAddress is missing from config file")
  319. }
  320. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  321. config.WebServerPrivateKey == "") {
  322. return nil, errors.New(
  323. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  324. }
  325. for tunnelProtocol, _ := range config.TunnelProtocolPorts {
  326. if psiphon.TunnelProtocolUsesSSH(tunnelProtocol) ||
  327. psiphon.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  328. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  329. config.SSHUserName == "" || config.SSHPassword == "" {
  330. return nil, fmt.Errorf(
  331. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  332. tunnelProtocol)
  333. }
  334. }
  335. if psiphon.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  336. if config.ObfuscatedSSHKey == "" {
  337. return nil, fmt.Errorf(
  338. "Tunnel protocol %s requires ObfuscatedSSHKey",
  339. tunnelProtocol)
  340. }
  341. }
  342. if psiphon.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  343. psiphon.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  344. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  345. return nil, fmt.Errorf(
  346. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  347. tunnelProtocol)
  348. }
  349. }
  350. if psiphon.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  351. if config.MeekCertificateCommonName == "" {
  352. return nil, fmt.Errorf(
  353. "Tunnel protocol %s requires MeekCertificateCommonName",
  354. tunnelProtocol)
  355. }
  356. }
  357. }
  358. validateNetworkAddress := func(address string) error {
  359. host, port, err := net.SplitHostPort(address)
  360. if err == nil && net.ParseIP(host) == nil {
  361. err = errors.New("Host must be an IP address")
  362. }
  363. if err == nil {
  364. _, err = strconv.Atoi(port)
  365. }
  366. return err
  367. }
  368. if config.UDPForwardDNSServerAddress != "" {
  369. if err := validateNetworkAddress(config.UDPForwardDNSServerAddress); err != nil {
  370. return nil, fmt.Errorf("UDPForwardDNSServerAddress is invalid: %s", err)
  371. }
  372. }
  373. if config.UDPInterceptUdpgwServerAddress != "" {
  374. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress); err != nil {
  375. return nil, fmt.Errorf("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  376. }
  377. }
  378. return &config, nil
  379. }
  380. // GenerateConfig creates a new Psiphon server config. It returns a JSON
  381. // encoded config and a client-compatible "server entry" for the server. It
  382. // generates all necessary secrets and key material, which are emitted in
  383. // the config file and server entry as necessary.
  384. // GenerateConfig uses sample values for many fields. The intention is for
  385. // a generated config to be used for testing or as a template for production
  386. // setup, not to generate production-ready configurations.
  387. func GenerateConfig(
  388. serverIPaddress string,
  389. webServerPort int,
  390. tunnelProtocolPorts map[string]int) ([]byte, []byte, error) {
  391. // Input validation
  392. if net.ParseIP(serverIPaddress) == nil {
  393. return nil, nil, psiphon.ContextError(errors.New("invalid IP address"))
  394. }
  395. if len(tunnelProtocolPorts) == 0 {
  396. return nil, nil, psiphon.ContextError(errors.New("no tunnel protocols"))
  397. }
  398. usedPort := make(map[int]bool)
  399. if webServerPort != 0 {
  400. usedPort[webServerPort] = true
  401. }
  402. for protocol, port := range tunnelProtocolPorts {
  403. if !psiphon.Contains(psiphon.SupportedTunnelProtocols, protocol) {
  404. return nil, nil, psiphon.ContextError(errors.New("invalid tunnel protocol"))
  405. }
  406. if usedPort[port] {
  407. return nil, nil, psiphon.ContextError(errors.New("duplicate listening port"))
  408. }
  409. usedPort[port] = true
  410. }
  411. // Web server config
  412. webServerSecret, err := psiphon.MakeRandomStringHex(WEB_SERVER_SECRET_BYTE_LENGTH)
  413. if err != nil {
  414. return nil, nil, psiphon.ContextError(err)
  415. }
  416. webServerCertificate, webServerPrivateKey, err := GenerateWebServerCertificate("")
  417. if err != nil {
  418. return nil, nil, psiphon.ContextError(err)
  419. }
  420. discoveryValueHMACKey, err := psiphon.MakeRandomStringBase64(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  421. if err != nil {
  422. return nil, nil, psiphon.ContextError(err)
  423. }
  424. // SSH config
  425. // TODO: use other key types: anti-fingerprint by varying params
  426. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  427. if err != nil {
  428. return nil, nil, psiphon.ContextError(err)
  429. }
  430. sshPrivateKey := pem.EncodeToMemory(
  431. &pem.Block{
  432. Type: "RSA PRIVATE KEY",
  433. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  434. },
  435. )
  436. signer, err := ssh.NewSignerFromKey(rsaKey)
  437. if err != nil {
  438. return nil, nil, psiphon.ContextError(err)
  439. }
  440. sshPublicKey := signer.PublicKey()
  441. sshUserNameSuffix, err := psiphon.MakeRandomStringHex(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  442. if err != nil {
  443. return nil, nil, psiphon.ContextError(err)
  444. }
  445. sshUserName := "psiphon_" + sshUserNameSuffix
  446. sshPassword, err := psiphon.MakeRandomStringHex(SSH_PASSWORD_BYTE_LENGTH)
  447. if err != nil {
  448. return nil, nil, psiphon.ContextError(err)
  449. }
  450. // TODO: vary version string for anti-fingerprint
  451. sshServerVersion := "SSH-2.0-Psiphon"
  452. // Obfuscated SSH config
  453. obfuscatedSSHKey, err := psiphon.MakeRandomStringHex(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  454. if err != nil {
  455. return nil, nil, psiphon.ContextError(err)
  456. }
  457. // Meek config
  458. meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, err :=
  459. box.GenerateKey(rand.Reader)
  460. if err != nil {
  461. return nil, nil, psiphon.ContextError(err)
  462. }
  463. meekObfuscatedKey, err := psiphon.MakeRandomStringHex(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  464. if err != nil {
  465. return nil, nil, psiphon.ContextError(err)
  466. }
  467. // Assemble config and server entry
  468. // Note: this config is intended for either testing or as an illustrative
  469. // example or template and is not intended for production deployment.
  470. config := &Config{
  471. LogLevel: "info",
  472. SyslogFacility: "user",
  473. SyslogTag: "psiphon-server",
  474. Fail2BanFormat: "Authentication failure for psiphon-client from %s",
  475. GeoIPDatabaseFilename: "",
  476. HostID: "example-host-id",
  477. ServerIPAddress: serverIPaddress,
  478. DiscoveryValueHMACKey: discoveryValueHMACKey,
  479. WebServerPort: webServerPort,
  480. WebServerSecret: webServerSecret,
  481. WebServerCertificate: webServerCertificate,
  482. WebServerPrivateKey: webServerPrivateKey,
  483. SSHPrivateKey: string(sshPrivateKey),
  484. SSHServerVersion: sshServerVersion,
  485. SSHUserName: sshUserName,
  486. SSHPassword: sshPassword,
  487. ObfuscatedSSHKey: obfuscatedSSHKey,
  488. TunnelProtocolPorts: tunnelProtocolPorts,
  489. RedisServerAddress: "",
  490. UDPForwardDNSServerAddress: "8.8.8.8:53",
  491. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  492. MeekCookieEncryptionPrivateKey: base64.StdEncoding.EncodeToString(meekCookieEncryptionPrivateKey[:]),
  493. MeekObfuscatedKey: meekObfuscatedKey,
  494. MeekCertificateCommonName: "www.example.org",
  495. MeekProhibitedHeaders: nil,
  496. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  497. DefaultTrafficRules: TrafficRules{
  498. DefaultRateLimits: RateLimits{
  499. DownstreamUnlimitedBytes: 0,
  500. DownstreamBytesPerSecond: 0,
  501. UpstreamUnlimitedBytes: 0,
  502. UpstreamBytesPerSecond: 0,
  503. },
  504. IdleTCPPortForwardTimeoutMilliseconds: 30000,
  505. IdleUDPPortForwardTimeoutMilliseconds: 30000,
  506. MaxTCPPortForwardCount: 1024,
  507. MaxUDPPortForwardCount: 32,
  508. AllowTCPPorts: nil,
  509. AllowUDPPorts: nil,
  510. DenyTCPPorts: nil,
  511. DenyUDPPorts: nil,
  512. },
  513. LoadMonitorPeriodSeconds: 300,
  514. }
  515. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  516. if err != nil {
  517. return nil, nil, psiphon.ContextError(err)
  518. }
  519. // Server entry format omits the BEGIN/END lines and newlines
  520. lines := strings.Split(webServerCertificate, "\n")
  521. strippedWebServerCertificate := strings.Join(lines[1:len(lines)-2], "")
  522. capabilities := []string{psiphon.CAPABILITY_SSH_API_REQUESTS}
  523. if webServerPort != 0 {
  524. capabilities = append(capabilities, psiphon.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  525. }
  526. for protocol, _ := range tunnelProtocolPorts {
  527. capabilities = append(capabilities, psiphon.GetCapability(protocol))
  528. }
  529. sshPort := tunnelProtocolPorts["SSH"]
  530. obfuscatedSSHPort := tunnelProtocolPorts["OSSH"]
  531. // Meek port limitations
  532. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  533. // - only one other meek port may be specified.
  534. meekPort := tunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  535. if meekPort == 0 {
  536. meekPort = tunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  537. }
  538. // Note: fronting params are a stub; this server entry will exercise
  539. // client and server fronting code paths, but not actually traverse
  540. // a fronting hop.
  541. serverEntry := &psiphon.ServerEntry{
  542. IpAddress: serverIPaddress,
  543. WebServerPort: fmt.Sprintf("%d", webServerPort),
  544. WebServerSecret: webServerSecret,
  545. WebServerCertificate: strippedWebServerCertificate,
  546. SshPort: sshPort,
  547. SshUsername: sshUserName,
  548. SshPassword: sshPassword,
  549. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  550. SshObfuscatedPort: obfuscatedSSHPort,
  551. SshObfuscatedKey: obfuscatedSSHKey,
  552. Capabilities: capabilities,
  553. Region: "US",
  554. MeekServerPort: meekPort,
  555. MeekCookieEncryptionPublicKey: base64.StdEncoding.EncodeToString(meekCookieEncryptionPublicKey[:]),
  556. MeekObfuscatedKey: meekObfuscatedKey,
  557. MeekFrontingHosts: []string{serverIPaddress},
  558. MeekFrontingAddresses: []string{serverIPaddress},
  559. MeekFrontingDisableSNI: false,
  560. }
  561. encodedServerEntry, err := psiphon.EncodeServerEntry(serverEntry)
  562. if err != nil {
  563. return nil, nil, psiphon.ContextError(err)
  564. }
  565. return encodedConfig, []byte(encodedServerEntry), nil
  566. }