config.go 43 KB

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