config.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "golang.org/x/crypto/nacl/box"
  35. "golang.org/x/crypto/ssh"
  36. )
  37. const (
  38. SERVER_CONFIG_FILENAME = "psiphond.config"
  39. SERVER_TRAFFIC_RULES_FILENAME = "psiphond-traffic-rules.config"
  40. SERVER_ENTRY_FILENAME = "server-entry.dat"
  41. DEFAULT_SERVER_IP_ADDRESS = "127.0.0.1"
  42. WEB_SERVER_SECRET_BYTE_LENGTH = 32
  43. DISCOVERY_VALUE_KEY_BYTE_LENGTH = 32
  44. SSH_USERNAME_SUFFIX_BYTE_LENGTH = 8
  45. SSH_PASSWORD_BYTE_LENGTH = 32
  46. SSH_RSA_HOST_KEY_BITS = 2048
  47. SSH_OBFUSCATED_KEY_BYTE_LENGTH = 32
  48. )
  49. // Config specifies the configuration and behavior of a Psiphon
  50. // server.
  51. type Config struct {
  52. // LogLevel specifies the log level. Valid values are:
  53. // panic, fatal, error, warn, info, debug
  54. LogLevel string
  55. // LogFilename specifies the path of the file to log
  56. // to. When blank, logs are written to stderr.
  57. LogFilename string
  58. // DiscoveryValueHMACKey is the network-wide secret value
  59. // used to determine a unique discovery strategy.
  60. DiscoveryValueHMACKey string
  61. // GeoIPDatabaseFilenames ares paths of GeoIP2/GeoLite2
  62. // MaxMind database files. When empty, no GeoIP lookups are
  63. // performed. Each file is queried, in order, for the
  64. // logged fields: country code, city, and ISP. Multiple
  65. // file support accomodates the MaxMind distribution where
  66. // ISP data in a separate file.
  67. GeoIPDatabaseFilenames []string
  68. // PsinetDatabaseFilename is the path of the Psiphon automation
  69. // jsonpickle format Psiphon API data file.
  70. PsinetDatabaseFilename string
  71. // HostID is the ID of the server host; this is used for API
  72. // event logging.
  73. HostID string
  74. // ServerIPAddress is the public IP address of the server.
  75. ServerIPAddress string
  76. // WebServerPort is the listening port of the web server.
  77. // When <= 0, no web server component is run.
  78. WebServerPort int
  79. // WebServerSecret is the unique secret value that the client
  80. // must supply to make requests to the web server.
  81. WebServerSecret string
  82. // WebServerCertificate is the certificate the client uses to
  83. // authenticate the web server.
  84. WebServerCertificate string
  85. // WebServerPrivateKey is the private key the web server uses to
  86. // authenticate itself to clients.
  87. WebServerPrivateKey string
  88. // TunnelProtocolPorts specifies which tunnel protocols to run
  89. // and which ports to listen on for each protocol. Valid tunnel
  90. // protocols include: "SSH", "OSSH", "UNFRONTED-MEEK-OSSH",
  91. // "UNFRONTED-MEEK-HTTPS-OSSH", "FRONTED-MEEK-OSSH",
  92. // "FRONTED-MEEK-HTTP-OSSH".
  93. TunnelProtocolPorts map[string]int
  94. // SSHPrivateKey is the SSH host key. The same key is used for
  95. // all protocols, run by this server instance, which use SSH.
  96. SSHPrivateKey string
  97. // SSHServerVersion is the server version presented in the
  98. // identification string. The same value is used for all
  99. // protocols, run by this server instance, which use SSH.
  100. SSHServerVersion string
  101. // SSHUserName is the SSH user name to be presented by the
  102. // the tunnel-core client. The same value is used for all
  103. // protocols, run by this server instance, which use SSH.
  104. SSHUserName string
  105. // SSHPassword is the SSH password to be presented by the
  106. // the tunnel-core client. The same value is used for all
  107. // protocols, run by this server instance, which use SSH.
  108. SSHPassword string
  109. // ObfuscatedSSHKey is the secret key for use in the Obfuscated
  110. // SSH protocol. The same secret key is used for all protocols,
  111. // run by this server instance, which use Obfuscated SSH.
  112. ObfuscatedSSHKey string
  113. // MeekCookieEncryptionPrivateKey is the NaCl private key used
  114. // to decrypt meek cookie payload sent from clients. The same
  115. // key is used for all meek protocols run by this server instance.
  116. MeekCookieEncryptionPrivateKey string
  117. // MeekObfuscatedKey is the secret key used for obfuscating
  118. // meek cookies sent from clients. The same key is used for all
  119. // meek protocols run by this server instance.
  120. MeekObfuscatedKey string
  121. // MeekCertificateCommonName is the value used for the hostname
  122. // in the self-signed certificate generated and used for meek
  123. // HTTPS modes. The same value is used for all HTTPS meek
  124. // protocols.
  125. MeekCertificateCommonName string
  126. // MeekProhibitedHeaders is a list of HTTP headers to check for
  127. // in client requests. If one of these headers is found, the
  128. // request fails. This is used to defend against abuse.
  129. MeekProhibitedHeaders []string
  130. // MeekProxyForwardedForHeaders is a list of HTTP headers which
  131. // may be added by downstream HTTP proxies or CDNs in front
  132. // of clients. These headers supply the original client IP
  133. // address, which is geolocated for stats purposes. Headers
  134. // include, for example, X-Forwarded-For. The header's value
  135. // is assumed to be a comma delimted list of IP addresses where
  136. // the client IP is the first IP address in the list. Meek protocols
  137. // look for these headers and use the client IP address from
  138. // the header if any one is present and the value is a valid
  139. // IP address; otherwise the direct connection remote address is
  140. // used as the client IP.
  141. MeekProxyForwardedForHeaders []string
  142. // UDPInterceptUdpgwServerAddress specifies the network address of
  143. // a udpgw server which clients may be port forwarding to. When
  144. // specified, these TCP port forwards are intercepted and handled
  145. // directly by this server, which parses the SSH channel using the
  146. // udpgw protocol. Handling includes udpgw transparent DNS: tunneled
  147. // UDP DNS packets are rerouted to the host's DNS server.
  148. UDPInterceptUdpgwServerAddress string
  149. // DNSResolverIPAddress specifies the IP address of a DNS server
  150. // to be used when "/etc/resolv.conf" doesn't exist or fails to
  151. // parse. When blank, "/etc/resolv.conf" must contain a usable
  152. // "nameserver" entry.
  153. DNSResolverIPAddress string
  154. // LoadMonitorPeriodSeconds indicates how frequently to log server
  155. // load information (number of connected clients per tunnel protocol,
  156. // number of running goroutines, amount of memory allocated, etc.)
  157. // The default, 0, disables load logging.
  158. LoadMonitorPeriodSeconds int
  159. // TrafficRulesFilename is the path of a file containing a
  160. // JSON-encoded TrafficRulesSet, the traffic rules to apply to
  161. // Psiphon client tunnels.
  162. TrafficRulesFilename string
  163. }
  164. // RunWebServer indicates whether to run a web server component.
  165. func (config *Config) RunWebServer() bool {
  166. return config.WebServerPort > 0
  167. }
  168. // RunLoadMonitor indicates whether to monitor and log server load.
  169. func (config *Config) RunLoadMonitor() bool {
  170. return config.LoadMonitorPeriodSeconds > 0
  171. }
  172. // LoadConfig loads and validates a JSON encoded server config.
  173. func LoadConfig(configJSON []byte) (*Config, error) {
  174. var config Config
  175. err := json.Unmarshal(configJSON, &config)
  176. if err != nil {
  177. return nil, common.ContextError(err)
  178. }
  179. if config.ServerIPAddress == "" {
  180. return nil, errors.New("ServerIPAddress is missing from config file")
  181. }
  182. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  183. config.WebServerPrivateKey == "") {
  184. return nil, errors.New(
  185. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  186. }
  187. for tunnelProtocol, _ := range config.TunnelProtocolPorts {
  188. if common.TunnelProtocolUsesSSH(tunnelProtocol) ||
  189. common.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  190. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  191. config.SSHUserName == "" || config.SSHPassword == "" {
  192. return nil, fmt.Errorf(
  193. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  194. tunnelProtocol)
  195. }
  196. }
  197. if common.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  198. if config.ObfuscatedSSHKey == "" {
  199. return nil, fmt.Errorf(
  200. "Tunnel protocol %s requires ObfuscatedSSHKey",
  201. tunnelProtocol)
  202. }
  203. }
  204. if common.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  205. common.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  206. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  207. return nil, fmt.Errorf(
  208. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  209. tunnelProtocol)
  210. }
  211. }
  212. if common.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  213. if config.MeekCertificateCommonName == "" {
  214. return nil, fmt.Errorf(
  215. "Tunnel protocol %s requires MeekCertificateCommonName",
  216. tunnelProtocol)
  217. }
  218. }
  219. }
  220. validateNetworkAddress := func(address string) error {
  221. host, port, err := net.SplitHostPort(address)
  222. if err == nil && net.ParseIP(host) == nil {
  223. err = errors.New("Host must be an IP address")
  224. }
  225. if err == nil {
  226. _, err = strconv.Atoi(port)
  227. }
  228. return err
  229. }
  230. if config.UDPInterceptUdpgwServerAddress != "" {
  231. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress); err != nil {
  232. return nil, fmt.Errorf("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  233. }
  234. }
  235. if config.DNSResolverIPAddress != "" {
  236. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  237. return nil, fmt.Errorf("DNSResolverIPAddress is invalid")
  238. }
  239. }
  240. return &config, nil
  241. }
  242. // GenerateConfigParams specifies customizations to be applied to
  243. // a generated server config.
  244. type GenerateConfigParams struct {
  245. LogFilename string
  246. ServerIPAddress string
  247. WebServerPort int
  248. EnableSSHAPIRequests bool
  249. TunnelProtocolPorts map[string]int
  250. TrafficRulesFilename string
  251. }
  252. // GenerateConfig creates a new Psiphon server config. It returns JSON
  253. // encoded configs and a client-compatible "server entry" for the server. It
  254. // generates all necessary secrets and key material, which are emitted in
  255. // the config file and server entry as necessary.
  256. // GenerateConfig uses sample values for many fields. The intention is for
  257. // generated configs to be used for testing or as a template for production
  258. // setup, not to generate production-ready configurations.
  259. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, error) {
  260. // Input validation
  261. if net.ParseIP(params.ServerIPAddress) == nil {
  262. return nil, nil, nil, common.ContextError(errors.New("invalid IP address"))
  263. }
  264. if len(params.TunnelProtocolPorts) == 0 {
  265. return nil, nil, nil, common.ContextError(errors.New("no tunnel protocols"))
  266. }
  267. usedPort := make(map[int]bool)
  268. if params.WebServerPort != 0 {
  269. usedPort[params.WebServerPort] = true
  270. }
  271. usingMeek := false
  272. for protocol, port := range params.TunnelProtocolPorts {
  273. if !common.Contains(common.SupportedTunnelProtocols, protocol) {
  274. return nil, nil, nil, common.ContextError(errors.New("invalid tunnel protocol"))
  275. }
  276. if usedPort[port] {
  277. return nil, nil, nil, common.ContextError(errors.New("duplicate listening port"))
  278. }
  279. usedPort[port] = true
  280. if common.TunnelProtocolUsesMeekHTTP(protocol) ||
  281. common.TunnelProtocolUsesMeekHTTPS(protocol) {
  282. usingMeek = true
  283. }
  284. }
  285. // Web server config
  286. var webServerSecret, webServerCertificate, webServerPrivateKey string
  287. if params.WebServerPort != 0 {
  288. var err error
  289. webServerSecret, err = common.MakeRandomStringHex(WEB_SERVER_SECRET_BYTE_LENGTH)
  290. if err != nil {
  291. return nil, nil, nil, common.ContextError(err)
  292. }
  293. webServerCertificate, webServerPrivateKey, err = GenerateWebServerCertificate("")
  294. if err != nil {
  295. return nil, nil, nil, common.ContextError(err)
  296. }
  297. }
  298. // SSH config
  299. // TODO: use other key types: anti-fingerprint by varying params
  300. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  301. if err != nil {
  302. return nil, nil, nil, common.ContextError(err)
  303. }
  304. sshPrivateKey := pem.EncodeToMemory(
  305. &pem.Block{
  306. Type: "RSA PRIVATE KEY",
  307. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  308. },
  309. )
  310. signer, err := ssh.NewSignerFromKey(rsaKey)
  311. if err != nil {
  312. return nil, nil, nil, common.ContextError(err)
  313. }
  314. sshPublicKey := signer.PublicKey()
  315. sshUserNameSuffix, err := common.MakeRandomStringHex(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  316. if err != nil {
  317. return nil, nil, nil, common.ContextError(err)
  318. }
  319. sshUserName := "psiphon_" + sshUserNameSuffix
  320. sshPassword, err := common.MakeRandomStringHex(SSH_PASSWORD_BYTE_LENGTH)
  321. if err != nil {
  322. return nil, nil, nil, common.ContextError(err)
  323. }
  324. // TODO: vary version string for anti-fingerprint
  325. sshServerVersion := "SSH-2.0-Psiphon"
  326. // Obfuscated SSH config
  327. obfuscatedSSHKey, err := common.MakeRandomStringHex(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  328. if err != nil {
  329. return nil, nil, nil, common.ContextError(err)
  330. }
  331. // Meek config
  332. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  333. if usingMeek {
  334. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  335. box.GenerateKey(rand.Reader)
  336. if err != nil {
  337. return nil, nil, nil, common.ContextError(err)
  338. }
  339. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  340. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  341. meekObfuscatedKey, err = common.MakeRandomStringHex(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  342. if err != nil {
  343. return nil, nil, nil, common.ContextError(err)
  344. }
  345. }
  346. // Other config
  347. discoveryValueHMACKey, err := common.MakeRandomStringBase64(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  348. if err != nil {
  349. return nil, nil, nil, common.ContextError(err)
  350. }
  351. // Assemble configs and server entry
  352. // Note: this config is intended for either testing or as an illustrative
  353. // example or template and is not intended for production deployment.
  354. config := &Config{
  355. LogLevel: "info",
  356. LogFilename: params.LogFilename,
  357. GeoIPDatabaseFilenames: nil,
  358. HostID: "example-host-id",
  359. ServerIPAddress: params.ServerIPAddress,
  360. DiscoveryValueHMACKey: discoveryValueHMACKey,
  361. WebServerPort: params.WebServerPort,
  362. WebServerSecret: webServerSecret,
  363. WebServerCertificate: webServerCertificate,
  364. WebServerPrivateKey: webServerPrivateKey,
  365. SSHPrivateKey: string(sshPrivateKey),
  366. SSHServerVersion: sshServerVersion,
  367. SSHUserName: sshUserName,
  368. SSHPassword: sshPassword,
  369. ObfuscatedSSHKey: obfuscatedSSHKey,
  370. TunnelProtocolPorts: params.TunnelProtocolPorts,
  371. DNSResolverIPAddress: "8.8.8.8",
  372. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  373. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  374. MeekObfuscatedKey: meekObfuscatedKey,
  375. MeekCertificateCommonName: "www.example.org",
  376. MeekProhibitedHeaders: nil,
  377. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  378. LoadMonitorPeriodSeconds: 300,
  379. TrafficRulesFilename: params.TrafficRulesFilename,
  380. }
  381. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  382. if err != nil {
  383. return nil, nil, nil, common.ContextError(err)
  384. }
  385. trafficRulesSet := &TrafficRulesSet{
  386. DefaultRules: TrafficRules{
  387. DefaultLimits: common.RateLimits{
  388. DownstreamUnlimitedBytes: 0,
  389. DownstreamBytesPerSecond: 0,
  390. UpstreamUnlimitedBytes: 0,
  391. UpstreamBytesPerSecond: 0,
  392. },
  393. IdleTCPPortForwardTimeoutMilliseconds: 30000,
  394. IdleUDPPortForwardTimeoutMilliseconds: 30000,
  395. MaxTCPPortForwardCount: 1024,
  396. MaxUDPPortForwardCount: 32,
  397. AllowTCPPorts: nil,
  398. AllowUDPPorts: nil,
  399. DenyTCPPorts: nil,
  400. DenyUDPPorts: nil,
  401. },
  402. }
  403. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  404. if err != nil {
  405. return nil, nil, nil, common.ContextError(err)
  406. }
  407. capabilities := []string{}
  408. if params.EnableSSHAPIRequests {
  409. capabilities = append(capabilities, common.CAPABILITY_SSH_API_REQUESTS)
  410. }
  411. if params.WebServerPort != 0 {
  412. capabilities = append(capabilities, common.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  413. }
  414. for protocol, _ := range params.TunnelProtocolPorts {
  415. capabilities = append(capabilities, psiphon.GetCapability(protocol))
  416. }
  417. sshPort := params.TunnelProtocolPorts["SSH"]
  418. obfuscatedSSHPort := params.TunnelProtocolPorts["OSSH"]
  419. // Meek port limitations
  420. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  421. // - only one other meek port may be specified.
  422. meekPort := params.TunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  423. if meekPort == 0 {
  424. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  425. }
  426. // Note: fronting params are a stub; this server entry will exercise
  427. // client and server fronting code paths, but not actually traverse
  428. // a fronting hop.
  429. serverEntryWebServerPort := ""
  430. strippedWebServerCertificate := ""
  431. if params.WebServerPort != 0 {
  432. serverEntryWebServerPort = fmt.Sprintf("%d", params.WebServerPort)
  433. // Server entry format omits the BEGIN/END lines and newlines
  434. lines := strings.Split(webServerCertificate, "\n")
  435. strippedWebServerCertificate = strings.Join(lines[1:len(lines)-2], "")
  436. }
  437. serverEntry := &psiphon.ServerEntry{
  438. IpAddress: params.ServerIPAddress,
  439. WebServerPort: serverEntryWebServerPort,
  440. WebServerSecret: webServerSecret,
  441. WebServerCertificate: strippedWebServerCertificate,
  442. SshPort: sshPort,
  443. SshUsername: sshUserName,
  444. SshPassword: sshPassword,
  445. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  446. SshObfuscatedPort: obfuscatedSSHPort,
  447. SshObfuscatedKey: obfuscatedSSHKey,
  448. Capabilities: capabilities,
  449. Region: "US",
  450. MeekServerPort: meekPort,
  451. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  452. MeekObfuscatedKey: meekObfuscatedKey,
  453. MeekFrontingHosts: []string{params.ServerIPAddress},
  454. MeekFrontingAddresses: []string{params.ServerIPAddress},
  455. MeekFrontingDisableSNI: false,
  456. }
  457. encodedServerEntry, err := psiphon.EncodeServerEntry(serverEntry)
  458. if err != nil {
  459. return nil, nil, nil, common.ContextError(err)
  460. }
  461. return encodedConfig, encodedTrafficRulesSet, []byte(encodedServerEntry), nil
  462. }