config.go 42 KB

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