config.go 24 KB

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