config.go 44 KB

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