config.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. "fmt"
  29. "net"
  30. "os"
  31. "strconv"
  32. "strings"
  33. "sync/atomic"
  34. "time"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  43. "golang.org/x/crypto/nacl/box"
  44. )
  45. const (
  46. SERVER_CONFIG_FILENAME = "psiphond.config"
  47. SERVER_TRAFFIC_RULES_CONFIG_FILENAME = "psiphond-traffic-rules.config"
  48. SERVER_OSL_CONFIG_FILENAME = "psiphond-osl.config"
  49. SERVER_TACTICS_CONFIG_FILENAME = "psiphond-tactics.config"
  50. SERVER_ENTRY_FILENAME = "server-entry.dat"
  51. DEFAULT_SERVER_IP_ADDRESS = "127.0.0.1"
  52. WEB_SERVER_SECRET_BYTE_LENGTH = 32
  53. DISCOVERY_VALUE_KEY_BYTE_LENGTH = 32
  54. SSH_USERNAME_SUFFIX_BYTE_LENGTH = 8
  55. SSH_PASSWORD_BYTE_LENGTH = 32
  56. SSH_RSA_HOST_KEY_BITS = 2048
  57. SSH_OBFUSCATED_KEY_BYTE_LENGTH = 32
  58. PERIODIC_GARBAGE_COLLECTION = 120 * time.Second
  59. STOP_ESTABLISH_TUNNELS_ESTABLISHED_CLIENT_THRESHOLD = 20
  60. DEFAULT_LOG_FILE_REOPEN_RETRIES = 25
  61. )
  62. // Config specifies the configuration and behavior of a Psiphon
  63. // server.
  64. type Config struct {
  65. // LogLevel specifies the log level. Valid values are:
  66. // panic, fatal, error, warn, info, debug
  67. LogLevel string
  68. // LogFilename specifies the path of the file to log
  69. // to. When blank, logs are written to stderr.
  70. LogFilename string
  71. // LogFileReopenRetries specifies how many retries, each with a 1ms delay,
  72. // will be attempted after reopening a rotated log file fails. Retries
  73. // mitigate any race conditions between writes/reopens and file operations
  74. // performed by external log managers, such as logrotate.
  75. //
  76. // When omitted, DEFAULT_LOG_FILE_REOPEN_RETRIES is used.
  77. LogFileReopenRetries *int
  78. // LogFileCreateMode specifies that the Psiphon server should create a new
  79. // log file when one is not found, such as after rotation with logrotate
  80. // configured with nocreate. The value is the os.FileMode value to use when
  81. // creating the file.
  82. //
  83. // When omitted, the Psiphon server does not create log files.
  84. LogFileCreateMode *int
  85. // SkipPanickingLogWriter disables panicking when
  86. // unable to write any logs.
  87. SkipPanickingLogWriter bool
  88. // DiscoveryValueHMACKey is the network-wide secret value
  89. // used to determine a unique discovery strategy.
  90. DiscoveryValueHMACKey string
  91. // GeoIPDatabaseFilenames are paths of GeoIP2/GeoLite2
  92. // MaxMind database files. When empty, no GeoIP lookups are
  93. // performed. Each file is queried, in order, for the
  94. // logged fields: country code, city, and ISP. Multiple
  95. // file support accommodates the MaxMind distribution where
  96. // ISP data in a separate file.
  97. GeoIPDatabaseFilenames []string
  98. // PsinetDatabaseFilename is the path of the file containing
  99. // psinet.Database data.
  100. PsinetDatabaseFilename string
  101. // HostID is the ID of the server host; this is used for API
  102. // event logging.
  103. HostID string
  104. // ServerIPAddress is the public IP address of the server.
  105. ServerIPAddress string
  106. // WebServerPort is the listening port of the web server.
  107. // When <= 0, no web server component is run.
  108. WebServerPort int
  109. // WebServerSecret is the unique secret value that the client
  110. // must supply to make requests to the web server.
  111. WebServerSecret string
  112. // WebServerCertificate is the certificate the client uses to
  113. // authenticate the web server.
  114. WebServerCertificate string
  115. // WebServerPrivateKey is the private key the web server uses to
  116. // authenticate itself to clients.
  117. WebServerPrivateKey string
  118. // WebServerPortForwardAddress specifies the expected network
  119. // address ("<host>:<port>") specified in a client's port forward
  120. // HostToConnect and PortToConnect when the client is making a
  121. // tunneled connection to the web server. This address is always
  122. // exempted from validation against SSH_DISALLOWED_PORT_FORWARD_HOSTS
  123. // and AllowTCPPorts.
  124. WebServerPortForwardAddress string
  125. // WebServerPortForwardRedirectAddress specifies an alternate
  126. // destination address to be substituted and dialed instead of
  127. // the original destination when the port forward destination is
  128. // WebServerPortForwardAddress.
  129. WebServerPortForwardRedirectAddress string
  130. // TunnelProtocolPorts specifies which tunnel protocols to run
  131. // and which ports to listen on for each protocol. Valid tunnel
  132. // protocols include:
  133. // "SSH", "OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  134. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  135. // "FRONTED-MEEK-QUIC-OSSH", "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH",
  136. // "MARIONETTE-OSSH", "TAPDANCE-OSSH", abd "CONJURE-OSSH".
  137. //
  138. // In the case of "MARIONETTE-OSSH" the port value is ignored and must be
  139. // set to 0. The port value specified in the Marionette format is used.
  140. TunnelProtocolPorts map[string]int
  141. // TunnelProtocolPassthroughAddresses specifies passthrough addresses to be
  142. // used for tunnel protocols configured in TunnelProtocolPorts. Passthrough
  143. // is a probing defense which relays all network traffic between a client and
  144. // the passthrough target when the client fails anti-probing tests.
  145. //
  146. // TunnelProtocolPassthroughAddresses is supported for:
  147. // "UNFRONTED-MEEK-HTTPS-OSSH", "UNFRONTED-MEEK-SESSION-TICKET-OSSH".
  148. TunnelProtocolPassthroughAddresses map[string]string
  149. // SSHPrivateKey is the SSH host key. The same key is used for
  150. // all protocols, run by this server instance, which use SSH.
  151. SSHPrivateKey string
  152. // SSHServerVersion is the server version presented in the
  153. // identification string. The same value is used for all
  154. // protocols, run by this server instance, which use SSH.
  155. SSHServerVersion string
  156. // SSHUserName is the SSH user name to be presented by the
  157. // the tunnel-core client. The same value is used for all
  158. // protocols, run by this server instance, which use SSH.
  159. SSHUserName string
  160. // SSHPassword is the SSH password to be presented by the
  161. // the tunnel-core client. The same value is used for all
  162. // protocols, run by this server instance, which use SSH.
  163. SSHPassword string
  164. // SSHBeginHandshakeTimeoutMilliseconds specifies the timeout
  165. // for clients queueing to begin an SSH handshake. The default
  166. // is SSH_BEGIN_HANDSHAKE_TIMEOUT.
  167. SSHBeginHandshakeTimeoutMilliseconds *int
  168. // SSHHandshakeTimeoutMilliseconds specifies the timeout
  169. // before which a client must complete its handshake. The default
  170. // is SSH_HANDSHAKE_TIMEOUT.
  171. SSHHandshakeTimeoutMilliseconds *int
  172. // ObfuscatedSSHKey is the secret key for use in the Obfuscated
  173. // SSH protocol. The same secret key is used for all protocols,
  174. // run by this server instance, which use Obfuscated SSH.
  175. ObfuscatedSSHKey string
  176. // MeekCookieEncryptionPrivateKey is the NaCl private key used
  177. // to decrypt meek cookie payload sent from clients. The same
  178. // key is used for all meek protocols run by this server instance.
  179. MeekCookieEncryptionPrivateKey string
  180. // MeekObfuscatedKey is the secret key used for obfuscating
  181. // meek cookies sent from clients. The same key is used for all
  182. // meek protocols run by this server instance.
  183. MeekObfuscatedKey string
  184. // MeekProhibitedHeaders is a list of HTTP headers to check for
  185. // in client requests. If one of these headers is found, the
  186. // request fails. This is used to defend against abuse.
  187. MeekProhibitedHeaders []string
  188. // MeekProxyForwardedForHeaders is a list of HTTP headers which
  189. // may be added by downstream HTTP proxies or CDNs in front
  190. // of clients. These headers supply the original client IP
  191. // address, which is geolocated for stats purposes. Headers
  192. // include, for example, X-Forwarded-For. The header's value
  193. // is assumed to be a comma delimted list of IP addresses where
  194. // the client IP is the first IP address in the list. Meek protocols
  195. // look for these headers and use the client IP address from
  196. // the header if any one is present and the value is a valid
  197. // IP address; otherwise the direct connection remote address is
  198. // used as the client IP.
  199. MeekProxyForwardedForHeaders []string
  200. // MeekTurnAroundTimeoutMilliseconds specifies the amount of time meek will
  201. // wait for downstream bytes before responding to a request. The default is
  202. // MEEK_DEFAULT_TURN_AROUND_TIMEOUT.
  203. MeekTurnAroundTimeoutMilliseconds *int
  204. // MeekExtendedTurnAroundTimeoutMilliseconds specifies the extended amount of
  205. // time meek will wait for downstream bytes, as long as bytes arrive every
  206. // MeekTurnAroundTimeoutMilliseconds, before responding to a request. The
  207. // default is MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT.
  208. MeekExtendedTurnAroundTimeoutMilliseconds *int
  209. // MeekMaxSessionStalenessMilliseconds specifies the TTL for meek sessions.
  210. // The default is MEEK_DEFAULT_MAX_SESSION_STALENESS.
  211. MeekMaxSessionStalenessMilliseconds *int
  212. // MeekHTTPClientIOTimeoutMilliseconds specifies meek HTTP server I/O
  213. // timeouts. The default is MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT.
  214. MeekHTTPClientIOTimeoutMilliseconds *int
  215. // MeekCachedResponseBufferSize is the size of a private,
  216. // fixed-size buffer allocated for every meek client. The buffer
  217. // is used to cache response payload, allowing the client to retry
  218. // fetching when a network connection is interrupted. This retry
  219. // makes the OSSH tunnel within meek resilient to interruptions
  220. // at the HTTP TCP layer.
  221. // Larger buffers increase resiliency to interruption, but consume
  222. // more memory as buffers as never freed. The maximum size of a
  223. // response payload is a function of client activity, network
  224. // throughput and throttling.
  225. // A default of 64K is used when MeekCachedResponseBufferSize is 0.
  226. MeekCachedResponseBufferSize int
  227. // MeekCachedResponsePoolBufferSize is the size of a fixed-size,
  228. // shared buffer used to temporarily extend a private buffer when
  229. // MeekCachedResponseBufferSize is insufficient. Shared buffers
  230. // allow some clients to successfully retry longer response payloads
  231. // without allocating large buffers for all clients.
  232. // A default of 64K is used when MeekCachedResponsePoolBufferSize
  233. // is 0.
  234. MeekCachedResponsePoolBufferSize int
  235. // MeekCachedResponsePoolBufferCount is the number of shared
  236. // buffers. Shared buffers are allocated on first use and remain
  237. // allocated, so shared buffer count * size is roughly the memory
  238. // overhead of this facility.
  239. // A default of 2048 is used when MeekCachedResponsePoolBufferCount
  240. // is 0.
  241. MeekCachedResponsePoolBufferCount int
  242. // UDPInterceptUdpgwServerAddress specifies the network address of
  243. // a udpgw server which clients may be port forwarding to. When
  244. // specified, these TCP port forwards are intercepted and handled
  245. // directly by this server, which parses the SSH channel using the
  246. // udpgw protocol. Handling includes udpgw transparent DNS: tunneled
  247. // UDP DNS packets are rerouted to the host's DNS server.
  248. //
  249. // The intercept is applied before the port forward destination is
  250. // validated against SSH_DISALLOWED_PORT_FORWARD_HOSTS and
  251. // AllowTCPPorts. So the intercept address may be any otherwise
  252. // prohibited destination.
  253. UDPInterceptUdpgwServerAddress string
  254. // DNSResolverIPAddress specifies the IP address of a DNS server
  255. // to be used when "/etc/resolv.conf" doesn't exist or fails to
  256. // parse. When blank, "/etc/resolv.conf" must contain a usable
  257. // "nameserver" entry.
  258. DNSResolverIPAddress string
  259. // LoadMonitorPeriodSeconds indicates how frequently to log server
  260. // load information (number of connected clients per tunnel protocol,
  261. // number of running goroutines, amount of memory allocated, etc.)
  262. // The default, 0, disables load logging.
  263. LoadMonitorPeriodSeconds int
  264. // ProcessProfileOutputDirectory is the path of a directory to which
  265. // process profiles will be written when signaled with SIGUSR2. The
  266. // files are overwritten on each invocation. When set to the default
  267. // value, blank, no profiles are written on SIGUSR2. Profiles include
  268. // the default profiles here: https://golang.org/pkg/runtime/pprof/#Profile.
  269. ProcessProfileOutputDirectory string
  270. // ProcessBlockProfileDurationSeconds specifies the sample duration for
  271. // "block" profiling. For the default, 0, no "block" profile is taken.
  272. ProcessBlockProfileDurationSeconds int
  273. // ProcessCPUProfileDurationSeconds specifies the sample duration for
  274. // CPU profiling. For the default, 0, no CPU profile is taken.
  275. ProcessCPUProfileDurationSeconds int
  276. // TrafficRulesFilename is the path of a file containing a JSON-encoded
  277. // TrafficRulesSet, the traffic rules to apply to Psiphon client tunnels.
  278. TrafficRulesFilename string
  279. // OSLConfigFilename is the path of a file containing a JSON-encoded
  280. // OSL Config, the OSL schemes to apply to Psiphon client tunnels.
  281. OSLConfigFilename string
  282. // RunPacketTunnel specifies whether to run a packet tunnel.
  283. RunPacketTunnel bool
  284. // PacketTunnelEgressInterface specifies tun.ServerConfig.EgressInterface.
  285. PacketTunnelEgressInterface string
  286. // PacketTunnelEnableDNSFlowTracking sets
  287. // tun.ServerConfig.EnableDNSFlowTracking.
  288. PacketTunnelEnableDNSFlowTracking bool
  289. // PacketTunnelDownstreamPacketQueueSize specifies
  290. // tun.ServerConfig.DownStreamPacketQueueSize.
  291. PacketTunnelDownstreamPacketQueueSize int
  292. // PacketTunnelSessionIdleExpirySeconds specifies
  293. // tun.ServerConfig.SessionIdleExpirySeconds.
  294. PacketTunnelSessionIdleExpirySeconds int
  295. // PacketTunnelSudoNetworkConfigCommands sets
  296. // tun.ServerConfig.SudoNetworkConfigCommands.
  297. PacketTunnelSudoNetworkConfigCommands bool
  298. // RunPacketManipulator specifies whether to run a packet manipulator.
  299. RunPacketManipulator bool
  300. // MaxConcurrentSSHHandshakes specifies a limit on the number of concurrent
  301. // SSH handshake negotiations. This is set to mitigate spikes in memory
  302. // allocations and CPU usage associated with SSH handshakes when many clients
  303. // attempt to connect concurrently. When a maximum limit is specified and
  304. // reached, additional clients that establish TCP or meek connections will
  305. // be disconnected after a short wait for the number of concurrent handshakes
  306. // to drop below the limit.
  307. // The default, 0 is no limit.
  308. MaxConcurrentSSHHandshakes int
  309. // PeriodicGarbageCollectionSeconds turns on periodic calls to
  310. // debug.FreeOSMemory, every specified number of seconds, to force garbage
  311. // collection and memory scavenging. Specify 0 to disable. The default is
  312. // PERIODIC_GARBAGE_COLLECTION.
  313. PeriodicGarbageCollectionSeconds *int
  314. // StopEstablishTunnelsEstablishedClientThreshold sets the established client
  315. // threshold for dumping profiles when SIGTSTP is signaled. When there are
  316. // less than or equal to the threshold number of established clients,
  317. // profiles are dumped to aid investigating unusual load limited states that
  318. // occur when few clients are connected and load should be relatively low. A
  319. // profile dump is attempted at most once per process lifetime, the first
  320. // time the threshold is met. Disabled when < 0.
  321. StopEstablishTunnelsEstablishedClientThreshold *int
  322. // AccessControlVerificationKeyRing is the access control authorization
  323. // verification key ring used to verify signed authorizations presented
  324. // by clients. Verified, active (unexpired) access control types will be
  325. // available for matching in the TrafficRulesFilter for the client via
  326. // AuthorizedAccessTypes. All other authorizations are ignored.
  327. AccessControlVerificationKeyRing accesscontrol.VerificationKeyRing
  328. // TacticsConfigFilename is the path of a file containing a JSON-encoded
  329. // tactics server configuration.
  330. TacticsConfigFilename string
  331. // MarionetteFormat specifies a Marionette format to use with the
  332. // MARIONETTE-OSSH tunnel protocol. The format specifies the network
  333. // protocol port to listen on.
  334. MarionetteFormat string
  335. // BlocklistFilename is the path of a file containing a CSV-encoded
  336. // blocklist configuration. See NewBlocklist for more file format
  337. // documentation.
  338. BlocklistFilename string
  339. // BlocklistActive indicates whether to actively prevent blocklist hits in
  340. // addition to logging events.
  341. BlocklistActive bool
  342. // AllowBogons disables port forward bogon checks. This should be used only
  343. // for testing.
  344. AllowBogons bool
  345. // OwnEncodedServerEntries is a list of the server's own encoded server
  346. // entries, idenfified by server entry tag. These values are used in the
  347. // handshake API to update clients that don't yet have a signed copy of these
  348. // server entries.
  349. //
  350. // For purposes of compartmentalization, each server receives only its own
  351. // server entries here; and, besides the discovery server entries, in
  352. // psinet.Database, necessary for the discovery feature, no other server
  353. // entries are stored on a Psiphon server.
  354. OwnEncodedServerEntries map[string]string
  355. sshBeginHandshakeTimeout time.Duration
  356. sshHandshakeTimeout time.Duration
  357. periodicGarbageCollection time.Duration
  358. stopEstablishTunnelsEstablishedClientThreshold int
  359. dumpProfilesOnStopEstablishTunnelsDone int32
  360. frontingProviderID string
  361. runningProtocols []string
  362. }
  363. // GetLogFileReopenConfig gets the reopen retries, and create/mode inputs for
  364. // rotate.NewRotatableFileWriter, which is used when writing to log files.
  365. //
  366. // By default, we expect the log files to be managed by logrotate, with
  367. // logrotate configured to re-create the next log file after rotation. As
  368. // described in the documentation for rotate.NewRotatableFileWriter, and as
  369. // observed in production, we occasionally need retries when attempting to
  370. // reopen the log file post-rotation; and we avoid conflicts, and spurious
  371. // re-rotations, by disabling file create in rotate.NewRotatableFileWriter. In
  372. // large scale production, incidents requiring retry are very rare, so the
  373. // retry delay is not expected to have a significant impact on performance.
  374. //
  375. // The defaults may be overriden in the Config.
  376. func (config *Config) GetLogFileReopenConfig() (int, bool, os.FileMode) {
  377. retries := DEFAULT_LOG_FILE_REOPEN_RETRIES
  378. if config.LogFileReopenRetries != nil {
  379. retries = *config.LogFileReopenRetries
  380. }
  381. create := false
  382. mode := os.FileMode(0)
  383. if config.LogFileCreateMode != nil {
  384. create = true
  385. mode = os.FileMode(*config.LogFileCreateMode)
  386. }
  387. return retries, create, mode
  388. }
  389. // RunWebServer indicates whether to run a web server component.
  390. func (config *Config) RunWebServer() bool {
  391. return config.WebServerPort > 0
  392. }
  393. // RunLoadMonitor indicates whether to monitor and log server load.
  394. func (config *Config) RunLoadMonitor() bool {
  395. return config.LoadMonitorPeriodSeconds > 0
  396. }
  397. // RunPeriodicGarbageCollection indicates whether to run periodic garbage collection.
  398. func (config *Config) RunPeriodicGarbageCollection() bool {
  399. return config.periodicGarbageCollection > 0
  400. }
  401. // DumpProfilesOnStopEstablishTunnels indicates whether dump profiles due to
  402. // an unexpectedly low number of established clients during high load.
  403. func (config *Config) DumpProfilesOnStopEstablishTunnels(establishedClientsCount int) bool {
  404. if config.stopEstablishTunnelsEstablishedClientThreshold < 0 {
  405. return false
  406. }
  407. if atomic.LoadInt32(&config.dumpProfilesOnStopEstablishTunnelsDone) != 0 {
  408. return false
  409. }
  410. dump := (establishedClientsCount <= config.stopEstablishTunnelsEstablishedClientThreshold)
  411. atomic.StoreInt32(&config.dumpProfilesOnStopEstablishTunnelsDone, 1)
  412. return dump
  413. }
  414. // GetOwnEncodedServerEntry returns one of the server's own server entries, as
  415. // identified by the server entry tag.
  416. func (config *Config) GetOwnEncodedServerEntry(serverEntryTag string) (string, bool) {
  417. serverEntry, ok := config.OwnEncodedServerEntries[serverEntryTag]
  418. return serverEntry, ok
  419. }
  420. // GetFrontingProviderID returns the fronting provider ID associated with the
  421. // server's fronted protocol(s).
  422. func (config *Config) GetFrontingProviderID() string {
  423. return config.frontingProviderID
  424. }
  425. // GetRunningProtocols returns the list of protcols this server is running.
  426. // The caller must not mutate the return value.
  427. func (config *Config) GetRunningProtocols() []string {
  428. return config.runningProtocols
  429. }
  430. // LoadConfig loads and validates a JSON encoded server config.
  431. func LoadConfig(configJSON []byte) (*Config, error) {
  432. var config Config
  433. err := json.Unmarshal(configJSON, &config)
  434. if err != nil {
  435. return nil, errors.Trace(err)
  436. }
  437. if config.ServerIPAddress == "" {
  438. return nil, errors.TraceNew("ServerIPAddress is required")
  439. }
  440. if config.WebServerPort > 0 && (config.WebServerSecret == "" || config.WebServerCertificate == "" ||
  441. config.WebServerPrivateKey == "") {
  442. return nil, errors.TraceNew(
  443. "Web server requires WebServerSecret, WebServerCertificate, WebServerPrivateKey")
  444. }
  445. if config.WebServerPortForwardAddress != "" {
  446. if err := validateNetworkAddress(config.WebServerPortForwardAddress, false); err != nil {
  447. return nil, errors.TraceNew("WebServerPortForwardAddress is invalid")
  448. }
  449. }
  450. if config.WebServerPortForwardRedirectAddress != "" {
  451. if config.WebServerPortForwardAddress == "" {
  452. return nil, errors.TraceNew(
  453. "WebServerPortForwardRedirectAddress requires WebServerPortForwardAddress")
  454. }
  455. if err := validateNetworkAddress(config.WebServerPortForwardRedirectAddress, false); err != nil {
  456. return nil, errors.TraceNew("WebServerPortForwardRedirectAddress is invalid")
  457. }
  458. }
  459. for tunnelProtocol, port := range config.TunnelProtocolPorts {
  460. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  461. return nil, errors.Tracef("Unsupported tunnel protocol: %s", tunnelProtocol)
  462. }
  463. if protocol.TunnelProtocolUsesSSH(tunnelProtocol) ||
  464. protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  465. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  466. config.SSHUserName == "" || config.SSHPassword == "" {
  467. return nil, errors.Tracef(
  468. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  469. tunnelProtocol)
  470. }
  471. }
  472. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  473. if config.ObfuscatedSSHKey == "" {
  474. return nil, errors.Tracef(
  475. "Tunnel protocol %s requires ObfuscatedSSHKey",
  476. tunnelProtocol)
  477. }
  478. }
  479. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  480. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  481. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  482. return nil, errors.Tracef(
  483. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  484. tunnelProtocol)
  485. }
  486. }
  487. if protocol.TunnelProtocolUsesMarionette(tunnelProtocol) {
  488. if port != 0 {
  489. return nil, errors.Tracef(
  490. "Tunnel protocol %s port is specified in format, not TunnelProtocolPorts",
  491. tunnelProtocol)
  492. }
  493. }
  494. }
  495. for tunnelProtocol, address := range config.TunnelProtocolPassthroughAddresses {
  496. if !protocol.TunnelProtocolSupportsPassthrough(tunnelProtocol) {
  497. return nil, errors.Tracef("Passthrough unsupported tunnel protocol: %s", tunnelProtocol)
  498. }
  499. if _, _, err := net.SplitHostPort(address); err != nil {
  500. if err != nil {
  501. return nil, errors.Tracef(
  502. "Tunnel protocol %s passthrough address %s invalid: %s",
  503. tunnelProtocol, address, err)
  504. }
  505. }
  506. }
  507. config.sshBeginHandshakeTimeout = SSH_BEGIN_HANDSHAKE_TIMEOUT
  508. if config.SSHBeginHandshakeTimeoutMilliseconds != nil {
  509. config.sshBeginHandshakeTimeout = time.Duration(*config.SSHBeginHandshakeTimeoutMilliseconds) * time.Millisecond
  510. }
  511. config.sshHandshakeTimeout = SSH_HANDSHAKE_TIMEOUT
  512. if config.SSHHandshakeTimeoutMilliseconds != nil {
  513. config.sshHandshakeTimeout = time.Duration(*config.SSHHandshakeTimeoutMilliseconds) * time.Millisecond
  514. }
  515. if config.ObfuscatedSSHKey != "" {
  516. seed, err := protocol.DeriveSSHServerVersionPRNGSeed(config.ObfuscatedSSHKey)
  517. if err != nil {
  518. return nil, errors.Tracef(
  519. "DeriveSSHServerVersionPRNGSeed failed: %s", err)
  520. }
  521. serverVersion := values.GetSSHServerVersion(seed)
  522. if serverVersion != "" {
  523. config.SSHServerVersion = serverVersion
  524. }
  525. }
  526. if config.UDPInterceptUdpgwServerAddress != "" {
  527. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress, true); err != nil {
  528. return nil, errors.Tracef("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  529. }
  530. }
  531. if config.DNSResolverIPAddress != "" {
  532. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  533. return nil, errors.Tracef("DNSResolverIPAddress is invalid")
  534. }
  535. }
  536. config.periodicGarbageCollection = PERIODIC_GARBAGE_COLLECTION
  537. if config.PeriodicGarbageCollectionSeconds != nil {
  538. config.periodicGarbageCollection = time.Duration(*config.PeriodicGarbageCollectionSeconds) * time.Second
  539. }
  540. config.stopEstablishTunnelsEstablishedClientThreshold = STOP_ESTABLISH_TUNNELS_ESTABLISHED_CLIENT_THRESHOLD
  541. if config.StopEstablishTunnelsEstablishedClientThreshold != nil {
  542. config.stopEstablishTunnelsEstablishedClientThreshold = *config.StopEstablishTunnelsEstablishedClientThreshold
  543. }
  544. err = accesscontrol.ValidateVerificationKeyRing(&config.AccessControlVerificationKeyRing)
  545. if err != nil {
  546. return nil, errors.Tracef(
  547. "AccessControlVerificationKeyRing is invalid: %s", err)
  548. }
  549. // Limitation: the following is a shortcut which extracts the server's
  550. // fronting provider ID from the server's OwnEncodedServerEntries. This logic
  551. // assumes a server has only one fronting provider. In principle, it's
  552. // possible for server with multiple server entries to run multiple fronted
  553. // protocols, each with a different fronting provider ID.
  554. //
  555. // TODO: add an explicit parameter mapping tunnel protocol ports to fronting
  556. // provider IDs.
  557. for _, encodedServerEntry := range config.OwnEncodedServerEntries {
  558. serverEntry, err := protocol.DecodeServerEntry(encodedServerEntry, "", "")
  559. if err != nil {
  560. return nil, errors.Tracef(
  561. "protocol.DecodeServerEntry failed: %s", err)
  562. }
  563. if config.frontingProviderID == "" {
  564. config.frontingProviderID = serverEntry.FrontingProviderID
  565. } else if config.frontingProviderID != serverEntry.FrontingProviderID {
  566. return nil, errors.Tracef("unsupported multiple FrontingProviderID values")
  567. }
  568. }
  569. config.runningProtocols = []string{}
  570. for tunnelProtocol := range config.TunnelProtocolPorts {
  571. config.runningProtocols = append(config.runningProtocols, tunnelProtocol)
  572. }
  573. return &config, nil
  574. }
  575. func validateNetworkAddress(address string, requireIPaddress bool) error {
  576. host, portStr, err := net.SplitHostPort(address)
  577. if err != nil {
  578. return err
  579. }
  580. if requireIPaddress && net.ParseIP(host) == nil {
  581. return errors.TraceNew("host must be an IP address")
  582. }
  583. port, err := strconv.Atoi(portStr)
  584. if err != nil {
  585. return err
  586. }
  587. if port < 0 || port > 65535 {
  588. return errors.TraceNew("invalid port")
  589. }
  590. return nil
  591. }
  592. // GenerateConfigParams specifies customizations to be applied to
  593. // a generated server config.
  594. type GenerateConfigParams struct {
  595. LogFilename string
  596. SkipPanickingLogWriter bool
  597. LogLevel string
  598. ServerIPAddress string
  599. WebServerPort int
  600. EnableSSHAPIRequests bool
  601. TunnelProtocolPorts map[string]int
  602. MarionetteFormat string
  603. TrafficRulesConfigFilename string
  604. OSLConfigFilename string
  605. TacticsConfigFilename string
  606. TacticsRequestPublicKey string
  607. TacticsRequestObfuscatedKey string
  608. }
  609. // GenerateConfig creates a new Psiphon server config. It returns JSON encoded
  610. // configs and a client-compatible "server entry" for the server. It generates
  611. // all necessary secrets and key material, which are emitted in the config
  612. // file and server entry as necessary.
  613. //
  614. // GenerateConfig uses sample values for many fields. The intention is for
  615. // generated configs to be used for testing or as examples for production
  616. // setup, not to generate production-ready configurations.
  617. //
  618. // When tactics key material is provided in GenerateConfigParams, tactics
  619. // capabilities are added for all meek protocols in TunnelProtocolPorts.
  620. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, []byte, []byte, error) {
  621. // Input validation
  622. if net.ParseIP(params.ServerIPAddress) == nil {
  623. return nil, nil, nil, nil, nil, errors.TraceNew("invalid IP address")
  624. }
  625. if len(params.TunnelProtocolPorts) == 0 {
  626. return nil, nil, nil, nil, nil, errors.TraceNew("no tunnel protocols")
  627. }
  628. usedPort := make(map[int]bool)
  629. if params.WebServerPort != 0 {
  630. usedPort[params.WebServerPort] = true
  631. }
  632. usingMeek := false
  633. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  634. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  635. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tunnel protocol")
  636. }
  637. if usedPort[port] {
  638. return nil, nil, nil, nil, nil, errors.TraceNew("duplicate listening port")
  639. }
  640. usedPort[port] = true
  641. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  642. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  643. usingMeek = true
  644. }
  645. }
  646. // One test mode populates the tactics config file; this will generate
  647. // keys. Another test mode passes in existing keys to be used in the
  648. // server entry. Both the filename and existing keys cannot be passed in.
  649. if (params.TacticsConfigFilename != "") &&
  650. (params.TacticsRequestPublicKey != "" || params.TacticsRequestObfuscatedKey != "") {
  651. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tactics parameters")
  652. }
  653. // Web server config
  654. var webServerSecret, webServerCertificate,
  655. webServerPrivateKey, webServerPortForwardAddress string
  656. if params.WebServerPort != 0 {
  657. webServerSecretBytes, err := common.MakeSecureRandomBytes(WEB_SERVER_SECRET_BYTE_LENGTH)
  658. if err != nil {
  659. return nil, nil, nil, nil, nil, errors.Trace(err)
  660. }
  661. webServerSecret = hex.EncodeToString(webServerSecretBytes)
  662. webServerCertificate, webServerPrivateKey, err = common.GenerateWebServerCertificate("")
  663. if err != nil {
  664. return nil, nil, nil, nil, nil, errors.Trace(err)
  665. }
  666. webServerPortForwardAddress = net.JoinHostPort(
  667. params.ServerIPAddress, strconv.Itoa(params.WebServerPort))
  668. }
  669. // SSH config
  670. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  671. if err != nil {
  672. return nil, nil, nil, nil, nil, errors.Trace(err)
  673. }
  674. sshPrivateKey := pem.EncodeToMemory(
  675. &pem.Block{
  676. Type: "RSA PRIVATE KEY",
  677. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  678. },
  679. )
  680. signer, err := ssh.NewSignerFromKey(rsaKey)
  681. if err != nil {
  682. return nil, nil, nil, nil, nil, errors.Trace(err)
  683. }
  684. sshPublicKey := signer.PublicKey()
  685. sshUserNameSuffixBytes, err := common.MakeSecureRandomBytes(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  686. if err != nil {
  687. return nil, nil, nil, nil, nil, errors.Trace(err)
  688. }
  689. sshUserNameSuffix := hex.EncodeToString(sshUserNameSuffixBytes)
  690. sshUserName := "psiphon_" + sshUserNameSuffix
  691. sshPasswordBytes, err := common.MakeSecureRandomBytes(SSH_PASSWORD_BYTE_LENGTH)
  692. if err != nil {
  693. return nil, nil, nil, nil, nil, errors.Trace(err)
  694. }
  695. sshPassword := hex.EncodeToString(sshPasswordBytes)
  696. sshServerVersion := "SSH-2.0-Psiphon"
  697. // Obfuscated SSH config
  698. obfuscatedSSHKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  699. if err != nil {
  700. return nil, nil, nil, nil, nil, errors.Trace(err)
  701. }
  702. obfuscatedSSHKey := hex.EncodeToString(obfuscatedSSHKeyBytes)
  703. // Meek config
  704. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  705. if usingMeek {
  706. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  707. box.GenerateKey(rand.Reader)
  708. if err != nil {
  709. return nil, nil, nil, nil, nil, errors.Trace(err)
  710. }
  711. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  712. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  713. meekObfuscatedKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  714. if err != nil {
  715. return nil, nil, nil, nil, nil, errors.Trace(err)
  716. }
  717. meekObfuscatedKey = hex.EncodeToString(meekObfuscatedKeyBytes)
  718. }
  719. // Other config
  720. discoveryValueHMACKeyBytes, err := common.MakeSecureRandomBytes(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  721. if err != nil {
  722. return nil, nil, nil, nil, nil, errors.Trace(err)
  723. }
  724. discoveryValueHMACKey := base64.StdEncoding.EncodeToString(discoveryValueHMACKeyBytes)
  725. // Assemble configs and server entry
  726. // Note: this config is intended for either testing or as an illustrative
  727. // example or template and is not intended for production deployment.
  728. logLevel := params.LogLevel
  729. if logLevel == "" {
  730. logLevel = "info"
  731. }
  732. // For testing, set the Psiphon server to create its log files; we do not
  733. // expect tests to necessarily run under log managers, such as logrotate.
  734. createMode := 0666
  735. config := &Config{
  736. LogLevel: logLevel,
  737. LogFilename: params.LogFilename,
  738. LogFileCreateMode: &createMode,
  739. SkipPanickingLogWriter: params.SkipPanickingLogWriter,
  740. GeoIPDatabaseFilenames: nil,
  741. HostID: "example-host-id",
  742. ServerIPAddress: params.ServerIPAddress,
  743. DiscoveryValueHMACKey: discoveryValueHMACKey,
  744. WebServerPort: params.WebServerPort,
  745. WebServerSecret: webServerSecret,
  746. WebServerCertificate: webServerCertificate,
  747. WebServerPrivateKey: webServerPrivateKey,
  748. WebServerPortForwardAddress: webServerPortForwardAddress,
  749. SSHPrivateKey: string(sshPrivateKey),
  750. SSHServerVersion: sshServerVersion,
  751. SSHUserName: sshUserName,
  752. SSHPassword: sshPassword,
  753. ObfuscatedSSHKey: obfuscatedSSHKey,
  754. TunnelProtocolPorts: params.TunnelProtocolPorts,
  755. DNSResolverIPAddress: "8.8.8.8",
  756. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  757. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  758. MeekObfuscatedKey: meekObfuscatedKey,
  759. MeekProhibitedHeaders: nil,
  760. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  761. LoadMonitorPeriodSeconds: 300,
  762. TrafficRulesFilename: params.TrafficRulesConfigFilename,
  763. OSLConfigFilename: params.OSLConfigFilename,
  764. TacticsConfigFilename: params.TacticsConfigFilename,
  765. MarionetteFormat: params.MarionetteFormat,
  766. }
  767. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  768. if err != nil {
  769. return nil, nil, nil, nil, nil, errors.Trace(err)
  770. }
  771. intPtr := func(i int) *int {
  772. return &i
  773. }
  774. trafficRulesSet := &TrafficRulesSet{
  775. DefaultRules: TrafficRules{
  776. RateLimits: RateLimits{
  777. ReadUnthrottledBytes: new(int64),
  778. ReadBytesPerSecond: new(int64),
  779. WriteUnthrottledBytes: new(int64),
  780. WriteBytesPerSecond: new(int64),
  781. },
  782. IdleTCPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  783. IdleUDPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  784. MaxTCPPortForwardCount: intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT),
  785. MaxUDPPortForwardCount: intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT),
  786. AllowTCPPorts: nil,
  787. AllowUDPPorts: nil,
  788. },
  789. }
  790. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  791. if err != nil {
  792. return nil, nil, nil, nil, nil, errors.Trace(err)
  793. }
  794. encodedOSLConfig, err := json.MarshalIndent(&osl.Config{}, "\n", " ")
  795. if err != nil {
  796. return nil, nil, nil, nil, nil, errors.Trace(err)
  797. }
  798. tacticsRequestPublicKey := params.TacticsRequestPublicKey
  799. tacticsRequestObfuscatedKey := params.TacticsRequestObfuscatedKey
  800. var tacticsRequestPrivateKey string
  801. var encodedTacticsConfig []byte
  802. if params.TacticsConfigFilename != "" {
  803. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err =
  804. tactics.GenerateKeys()
  805. if err != nil {
  806. return nil, nil, nil, nil, nil, errors.Trace(err)
  807. }
  808. decodedTacticsRequestPublicKey, err := base64.StdEncoding.DecodeString(tacticsRequestPublicKey)
  809. if err != nil {
  810. return nil, nil, nil, nil, nil, errors.Trace(err)
  811. }
  812. decodedTacticsRequestPrivateKey, err := base64.StdEncoding.DecodeString(tacticsRequestPrivateKey)
  813. if err != nil {
  814. return nil, nil, nil, nil, nil, errors.Trace(err)
  815. }
  816. decodedTacticsRequestObfuscatedKey, err := base64.StdEncoding.DecodeString(tacticsRequestObfuscatedKey)
  817. if err != nil {
  818. return nil, nil, nil, nil, nil, errors.Trace(err)
  819. }
  820. tacticsConfig := &tactics.Server{
  821. RequestPublicKey: decodedTacticsRequestPublicKey,
  822. RequestPrivateKey: decodedTacticsRequestPrivateKey,
  823. RequestObfuscatedKey: decodedTacticsRequestObfuscatedKey,
  824. DefaultTactics: tactics.Tactics{
  825. TTL: "1m",
  826. Probability: 1.0,
  827. },
  828. }
  829. encodedTacticsConfig, err = json.MarshalIndent(tacticsConfig, "\n", " ")
  830. if err != nil {
  831. return nil, nil, nil, nil, nil, errors.Trace(err)
  832. }
  833. }
  834. capabilities := []string{}
  835. if params.EnableSSHAPIRequests {
  836. capabilities = append(capabilities, protocol.CAPABILITY_SSH_API_REQUESTS)
  837. }
  838. if params.WebServerPort != 0 {
  839. capabilities = append(capabilities, protocol.CAPABILITY_UNTUNNELED_WEB_API_REQUESTS)
  840. }
  841. for tunnelProtocol := range params.TunnelProtocolPorts {
  842. capabilities = append(capabilities, protocol.GetCapability(tunnelProtocol))
  843. if params.TacticsRequestPublicKey != "" && params.TacticsRequestObfuscatedKey != "" &&
  844. protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  845. capabilities = append(capabilities, protocol.GetTacticsCapability(tunnelProtocol))
  846. }
  847. }
  848. sshPort := params.TunnelProtocolPorts["SSH"]
  849. obfuscatedSSHPort := params.TunnelProtocolPorts["OSSH"]
  850. obfuscatedSSHQUICPort := params.TunnelProtocolPorts["QUIC-OSSH"]
  851. // Meek port limitations
  852. // - fronted meek protocols are hard-wired in the client to be port 443 or 80.
  853. // - only one other meek port may be specified.
  854. meekPort := params.TunnelProtocolPorts["UNFRONTED-MEEK-OSSH"]
  855. if meekPort == 0 {
  856. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-HTTPS-OSSH"]
  857. }
  858. if meekPort == 0 {
  859. meekPort = params.TunnelProtocolPorts["UNFRONTED-MEEK-SESSION-TICKET-OSSH"]
  860. }
  861. // Note: fronting params are a stub; this server entry will exercise
  862. // client and server fronting code paths, but not actually traverse
  863. // a fronting hop.
  864. serverEntryWebServerPort := ""
  865. strippedWebServerCertificate := ""
  866. if params.WebServerPort != 0 {
  867. serverEntryWebServerPort = fmt.Sprintf("%d", params.WebServerPort)
  868. // Server entry format omits the BEGIN/END lines and newlines
  869. lines := strings.Split(webServerCertificate, "\n")
  870. strippedWebServerCertificate = strings.Join(lines[1:len(lines)-2], "")
  871. }
  872. serverEntry := &protocol.ServerEntry{
  873. IpAddress: params.ServerIPAddress,
  874. WebServerPort: serverEntryWebServerPort,
  875. WebServerSecret: webServerSecret,
  876. WebServerCertificate: strippedWebServerCertificate,
  877. SshPort: sshPort,
  878. SshUsername: sshUserName,
  879. SshPassword: sshPassword,
  880. SshHostKey: base64.RawStdEncoding.EncodeToString(sshPublicKey.Marshal()),
  881. SshObfuscatedPort: obfuscatedSSHPort,
  882. SshObfuscatedQUICPort: obfuscatedSSHQUICPort,
  883. SshObfuscatedKey: obfuscatedSSHKey,
  884. Capabilities: capabilities,
  885. Region: "US",
  886. MeekServerPort: meekPort,
  887. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  888. MeekObfuscatedKey: meekObfuscatedKey,
  889. MeekFrontingHosts: []string{params.ServerIPAddress},
  890. MeekFrontingAddresses: []string{params.ServerIPAddress},
  891. MeekFrontingDisableSNI: false,
  892. TacticsRequestPublicKey: tacticsRequestPublicKey,
  893. TacticsRequestObfuscatedKey: tacticsRequestObfuscatedKey,
  894. MarionetteFormat: params.MarionetteFormat,
  895. ConfigurationVersion: 1,
  896. }
  897. encodedServerEntry, err := protocol.EncodeServerEntry(serverEntry)
  898. if err != nil {
  899. return nil, nil, nil, nil, nil, errors.Trace(err)
  900. }
  901. return encodedConfig, encodedTrafficRulesSet, encodedOSLConfig, encodedTacticsConfig, []byte(encodedServerEntry), nil
  902. }