config.go 44 KB

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