config.go 26 KB

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