config.go 19 KB

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