config.go 31 KB

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