config.go 22 KB

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