config.go 45 KB

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