config.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365
  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. "net"
  29. "os"
  30. "strconv"
  31. "strings"
  32. "sync/atomic"
  33. "time"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/accesscontrol"
  36. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/crypto/ssh"
  37. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  38. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/inproxy"
  39. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/osl"
  40. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/prng"
  41. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  42. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
  43. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/values"
  44. "golang.org/x/crypto/nacl/box"
  45. )
  46. const (
  47. SERVER_CONFIG_FILENAME = "psiphond.config"
  48. SERVER_TRAFFIC_RULES_CONFIG_FILENAME = "psiphond-traffic-rules.config"
  49. SERVER_OSL_CONFIG_FILENAME = "psiphond-osl.config"
  50. SERVER_TACTICS_CONFIG_FILENAME = "psiphond-tactics.config"
  51. SERVER_ENTRY_FILENAME = "server-entry.dat"
  52. DEFAULT_SERVER_IP_ADDRESS = "127.0.0.1"
  53. WEB_SERVER_SECRET_BYTE_LENGTH = 32
  54. DISCOVERY_VALUE_KEY_BYTE_LENGTH = 32
  55. SSH_USERNAME_SUFFIX_BYTE_LENGTH = 8
  56. SSH_PASSWORD_BYTE_LENGTH = 32
  57. SSH_RSA_HOST_KEY_BITS = 2048
  58. SSH_OBFUSCATED_KEY_BYTE_LENGTH = 32
  59. SHADOWSOCKS_KEY_BYTE_LENGTH = 32
  60. PEAK_UPSTREAM_FAILURE_RATE_MINIMUM_SAMPLE_SIZE = 10
  61. PERIODIC_GARBAGE_COLLECTION = 120 * time.Second
  62. STOP_ESTABLISH_TUNNELS_ESTABLISHED_CLIENT_THRESHOLD = 20
  63. DEFAULT_LOG_FILE_REOPEN_RETRIES = 25
  64. )
  65. // Config specifies the configuration and behavior of a Psiphon
  66. // server.
  67. type Config struct {
  68. // LogLevel specifies the log level. Valid values are:
  69. // panic, fatal, error, warn, info, debug
  70. //
  71. // Some debug logs can contain user traffic destination address information.
  72. LogLevel string
  73. // LogFilename specifies the path of the file to log
  74. // to. When blank, logs are written to stderr.
  75. LogFilename string
  76. // LogFileReopenRetries specifies how many retries, each with a 1ms delay,
  77. // will be attempted after reopening a rotated log file fails. Retries
  78. // mitigate any race conditions between writes/reopens and file operations
  79. // performed by external log managers, such as logrotate.
  80. //
  81. // When omitted, DEFAULT_LOG_FILE_REOPEN_RETRIES is used.
  82. LogFileReopenRetries *int
  83. // LogFileCreateMode specifies that the Psiphon server should create a new
  84. // log file when one is not found, such as after rotation with logrotate
  85. // configured with nocreate. The value is the os.FileMode value to use when
  86. // creating the file.
  87. //
  88. // When omitted, the Psiphon server does not create log files.
  89. LogFileCreateMode *int
  90. // When LogDNSServerLoadMetrics is true, server_load logs will include a
  91. // break down of DNS request counts, failure rates, etc. per DNS server.
  92. // Otherwise, only the overall DNS metrics are logged.
  93. LogDNSServerLoadMetrics bool
  94. // SkipPanickingLogWriter disables panicking when
  95. // unable to write any logs.
  96. SkipPanickingLogWriter bool
  97. // DiscoveryValueHMACKey is the network-wide secret value
  98. // used to determine a unique discovery strategy.
  99. DiscoveryValueHMACKey string
  100. // GeoIPDatabaseFilenames are paths of GeoIP2/GeoLite2
  101. // MaxMind database files. When empty, no GeoIP lookups are
  102. // performed. Each file is queried, in order, for the
  103. // logged fields: country code, city, and ISP. Multiple
  104. // file support accommodates the MaxMind distribution where
  105. // ISP data in a separate file.
  106. GeoIPDatabaseFilenames []string
  107. // PsinetDatabaseFilename is the path of the file containing
  108. // psinet.Database data.
  109. PsinetDatabaseFilename string
  110. // HostID identifies the server host; this value is included with all logs.
  111. HostID string
  112. // HostProvider identifies the server host provider; this value is
  113. // included with all logs and logged only when not blank.
  114. HostProvider string
  115. // ServerIPAddress is the public IP address of the server.
  116. ServerIPAddress string
  117. // TunnelProtocolPorts specifies which tunnel protocols to run
  118. // and which ports to listen on for each protocol. Valid tunnel
  119. // protocols include:
  120. // "SSH", "OSSH", "TLS-OSSH", "UNFRONTED-MEEK-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  121. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "FRONTED-MEEK-OSSH",
  122. // "FRONTED-MEEK-QUIC-OSSH", "FRONTED-MEEK-HTTP-OSSH", "QUIC-OSSH",
  123. // "TAPDANCE-OSSH", "CONJURE-OSSH", and "SHADOWSOCKS-OSSH".
  124. TunnelProtocolPorts map[string]int
  125. // TunnelProtocolPassthroughAddresses specifies passthrough addresses to be
  126. // used for tunnel protocols configured in TunnelProtocolPorts. Passthrough
  127. // is a probing defense which relays all network traffic between a client and
  128. // the passthrough target when the client fails anti-probing tests.
  129. //
  130. // TunnelProtocolPassthroughAddresses is supported for:
  131. // "TLS-OSSH", "UNFRONTED-MEEK-HTTPS-OSSH",
  132. // "UNFRONTED-MEEK-SESSION-TICKET-OSSH", "UNFRONTED-MEEK-OSSH".
  133. TunnelProtocolPassthroughAddresses map[string]string
  134. // LegacyPassthrough indicates whether to expect legacy passthrough messages
  135. // from clients attempting to connect. This should be set for existing/legacy
  136. // passthrough servers only.
  137. LegacyPassthrough bool
  138. // EnableGQUIC indicates whether to enable legacy gQUIC QUIC-OSSH
  139. // versions, for backwards compatibility with all versions used by older
  140. // clients. Enabling gQUIC degrades the anti-probing stance of QUIC-OSSH,
  141. // as the legacy gQUIC stack will respond to probing packets.
  142. EnableGQUIC bool
  143. // SSHPrivateKey is the SSH host key. The same key is used for
  144. // all protocols, run by this server instance, which use SSH.
  145. SSHPrivateKey string
  146. // SSHServerVersion is the server version presented in the
  147. // identification string. The same value is used for all
  148. // protocols, run by this server instance, which use SSH.
  149. SSHServerVersion string
  150. // SSHUserName is the SSH user name to be presented by the
  151. // the tunnel-core client. The same value is used for all
  152. // protocols, run by this server instance, which use SSH.
  153. SSHUserName string
  154. // SSHPassword is the SSH password to be presented by the
  155. // the tunnel-core client. The same value is used for all
  156. // protocols, run by this server instance, which use SSH.
  157. SSHPassword string
  158. // SSHBeginHandshakeTimeoutMilliseconds specifies the timeout
  159. // for clients queueing to begin an SSH handshake. The default
  160. // is SSH_BEGIN_HANDSHAKE_TIMEOUT.
  161. SSHBeginHandshakeTimeoutMilliseconds *int
  162. // SSHHandshakeTimeoutMilliseconds specifies the timeout
  163. // before which a client must complete its handshake. The default
  164. // is SSH_HANDSHAKE_TIMEOUT.
  165. SSHHandshakeTimeoutMilliseconds *int
  166. // ObfuscatedSSHKey is the secret key for use in the Obfuscated
  167. // SSH protocol. The same secret key is used for all protocols,
  168. // run by this server instance, which use Obfuscated SSH.
  169. ObfuscatedSSHKey string
  170. // ShadowsocksKey is the secret key for use in the Shadowsocks
  171. // protocol.
  172. ShadowsocksKey string
  173. // MeekCookieEncryptionPrivateKey is the NaCl private key used
  174. // to decrypt meek cookie payload sent from clients. The same
  175. // key is used for all meek protocols run by this server instance.
  176. MeekCookieEncryptionPrivateKey string
  177. // MeekObfuscatedKey is the secret key used for obfuscating
  178. // meek cookies sent from clients. The same key is used for all
  179. // meek protocols run by this server instance.
  180. //
  181. // NOTE: this key is also used by the TLS-OSSH protocol, which allows
  182. // clients with legacy unfronted meek-https server entries, that have the
  183. // passthrough capability, to connect with TLS-OSSH to the servers
  184. // corresponding to those server entries, which now support TLS-OSSH by
  185. // demultiplexing meek-https and TLS-OSSH over the meek-https port.
  186. MeekObfuscatedKey string
  187. // MeekProhibitedHeaders is a list of HTTP headers to check for
  188. // in client requests. If one of these headers is found, the
  189. // request fails. This is used to defend against abuse.
  190. MeekProhibitedHeaders []string
  191. // MeekRequiredHeaders is a list of HTTP header names and values that must
  192. // appear in requests. This is used to defend against abuse.
  193. MeekRequiredHeaders map[string]string
  194. // MeekServerCertificate specifies an optional certificate to use for meek
  195. // servers, in place of the default, randomly generate certificate. When
  196. // specified, the corresponding private key must be supplied in
  197. // MeekServerPrivateKey. Any specified certificate is used for all meek
  198. // listeners.
  199. MeekServerCertificate string
  200. // MeekServerPrivateKey is the private key corresponding to the optional
  201. // MeekServerCertificate parameter.
  202. MeekServerPrivateKey string
  203. // MeekProxyForwardedForHeaders is a list of HTTP headers which
  204. // may be added by downstream HTTP proxies or CDNs in front
  205. // of clients. These headers supply the original client IP
  206. // address, which is geolocated for stats purposes. Headers
  207. // include, for example, X-Forwarded-For. The header's value
  208. // is assumed to be a comma delimted list of IP addresses where
  209. // the client IP is the first IP address in the list. Meek protocols
  210. // look for these headers and use the client IP address from
  211. // the header if any one is present and the value is a valid
  212. // IP address; otherwise the direct connection remote address is
  213. // used as the client IP.
  214. MeekProxyForwardedForHeaders []string
  215. // MeekTurnAroundTimeoutMilliseconds specifies the amount of time meek will
  216. // wait for downstream bytes before responding to a request. The default is
  217. // MEEK_DEFAULT_TURN_AROUND_TIMEOUT.
  218. MeekTurnAroundTimeoutMilliseconds *int
  219. // MeekExtendedTurnAroundTimeoutMilliseconds specifies the extended amount of
  220. // time meek will wait for downstream bytes, as long as bytes arrive every
  221. // MeekTurnAroundTimeoutMilliseconds, before responding to a request. The
  222. // default is MEEK_DEFAULT_EXTENDED_TURN_AROUND_TIMEOUT.
  223. MeekExtendedTurnAroundTimeoutMilliseconds *int
  224. // MeekSkipExtendedTurnAroundThresholdBytes specifies when to skip the
  225. // extended turn around. When the number of bytes received in the client
  226. // request meets the threshold, optimize for upstream flows with quicker
  227. // round trip turn arounds.
  228. MeekSkipExtendedTurnAroundThresholdBytes *int
  229. // MeekMaxSessionStalenessMilliseconds specifies the TTL for meek sessions.
  230. // The default is MEEK_DEFAULT_MAX_SESSION_STALENESS.
  231. MeekMaxSessionStalenessMilliseconds *int
  232. // MeekHTTPClientIOTimeoutMilliseconds specifies meek HTTP server I/O
  233. // timeouts. The default is MEEK_DEFAULT_HTTP_CLIENT_IO_TIMEOUT.
  234. MeekHTTPClientIOTimeoutMilliseconds *int
  235. // MeekFrontedHTTPClientIOTimeoutMilliseconds specifies meek HTTP server
  236. // I/O timeouts for fronted protocols. The default is
  237. // MEEK_DEFAULT_FRONTED_HTTP_CLIENT_IO_TIMEOUT.
  238. MeekFrontedHTTPClientIOTimeoutMilliseconds *int
  239. // MeekCachedResponseBufferSize is the size of a private,
  240. // fixed-size buffer allocated for every meek client. The buffer
  241. // is used to cache response payload, allowing the client to retry
  242. // fetching when a network connection is interrupted. This retry
  243. // makes the OSSH tunnel within meek resilient to interruptions
  244. // at the HTTP TCP layer.
  245. // Larger buffers increase resiliency to interruption, but consume
  246. // more memory as buffers as never freed. The maximum size of a
  247. // response payload is a function of client activity, network
  248. // throughput and throttling.
  249. // A default of 64K is used when MeekCachedResponseBufferSize is 0.
  250. MeekCachedResponseBufferSize int
  251. // MeekCachedResponsePoolBufferSize is the size of a fixed-size,
  252. // shared buffer used to temporarily extend a private buffer when
  253. // MeekCachedResponseBufferSize is insufficient. Shared buffers
  254. // allow some clients to successfully retry longer response payloads
  255. // without allocating large buffers for all clients.
  256. // A default of 64K is used when MeekCachedResponsePoolBufferSize
  257. // is 0.
  258. MeekCachedResponsePoolBufferSize int
  259. // MeekCachedResponsePoolBufferCount is the number of shared
  260. // buffers. Shared buffers are allocated on first use and remain
  261. // allocated, so shared buffer count * size is roughly the memory
  262. // overhead of this facility.
  263. // A default of 2048 is used when MeekCachedResponsePoolBufferCount
  264. // is 0.
  265. MeekCachedResponsePoolBufferCount int
  266. // MeekCachedResponsePoolBufferClientLimit is the maximum number of of
  267. // shared buffers a single client may consume at once. A default of 32 is
  268. // used when MeekCachedResponsePoolBufferClientLimit is 0.
  269. MeekCachedResponsePoolBufferClientLimit 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. // packetman.Config.SudoNetworkConfigCommands, and
  332. // SudoNetworkConfigCommands for configureIptablesAcceptRateLimitChain.
  333. PacketTunnelSudoNetworkConfigCommands bool
  334. // RunPacketManipulator specifies whether to run a packet manipulator.
  335. RunPacketManipulator bool
  336. // MaxConcurrentSSHHandshakes specifies a limit on the number of concurrent
  337. // SSH handshake negotiations. This is set to mitigate spikes in memory
  338. // allocations and CPU usage associated with SSH handshakes when many clients
  339. // attempt to connect concurrently. When a maximum limit is specified and
  340. // reached, additional clients that establish TCP or meek connections will
  341. // be disconnected after a short wait for the number of concurrent handshakes
  342. // to drop below the limit.
  343. // The default, 0 is no limit.
  344. MaxConcurrentSSHHandshakes int
  345. // PeriodicGarbageCollectionSeconds turns on periodic calls to
  346. // debug.FreeOSMemory, every specified number of seconds, to force garbage
  347. // collection and memory scavenging. Specify 0 to disable. The default is
  348. // PERIODIC_GARBAGE_COLLECTION.
  349. PeriodicGarbageCollectionSeconds *int
  350. // StopEstablishTunnelsEstablishedClientThreshold sets the established client
  351. // threshold for dumping profiles when SIGTSTP is signaled. When there are
  352. // less than or equal to the threshold number of established clients,
  353. // profiles are dumped to aid investigating unusual load limited states that
  354. // occur when few clients are connected and load should be relatively low. A
  355. // profile dump is attempted at most once per process lifetime, the first
  356. // time the threshold is met. Disabled when < 0.
  357. StopEstablishTunnelsEstablishedClientThreshold *int
  358. // AccessControlVerificationKeyRing is the access control authorization
  359. // verification key ring used to verify signed authorizations presented
  360. // by clients. Verified, active (unexpired) access control types will be
  361. // available for matching in the TrafficRulesFilter for the client via
  362. // AuthorizedAccessTypes. All other authorizations are ignored.
  363. AccessControlVerificationKeyRing accesscontrol.VerificationKeyRing
  364. // TacticsConfigFilename is the path of a file containing a JSON-encoded
  365. // tactics server configuration.
  366. TacticsConfigFilename string
  367. // BlocklistFilename is the path of a file containing a CSV-encoded
  368. // blocklist configuration. See NewBlocklist for more file format
  369. // documentation.
  370. BlocklistFilename string
  371. // BlocklistActive indicates whether to actively prevent blocklist hits in
  372. // addition to logging events.
  373. BlocklistActive bool
  374. // AllowBogons disables port forward bogon checks. This should be used only
  375. // for testing.
  376. AllowBogons bool
  377. // EnableSteeringIPs enables meek server steering IP support.
  378. EnableSteeringIPs bool
  379. // OwnEncodedServerEntries is a list of the server's own encoded server
  380. // entries, idenfified by server entry tag. These values are used in the
  381. // handshake API to update clients that don't yet have a signed copy of these
  382. // server entries.
  383. //
  384. // For purposes of compartmentalization, each server receives only its own
  385. // server entries here; and, besides the discovery server entries, in
  386. // psinet.Database, necessary for the discovery feature, no other server
  387. // entries are stored on a Psiphon server.
  388. OwnEncodedServerEntries map[string]string
  389. // MeekServerRunInproxyBroker indicates whether to run an in-proxy broker
  390. // endpoint and service under the meek server.
  391. MeekServerRunInproxyBroker bool
  392. // MeekServerInproxyBrokerOnly indicates whether to run only an in-proxy
  393. // broker under the meek server, and not run any meek tunnel protocol. To
  394. // run the meek listener, a meek server protocol and port must still be
  395. // specified in TunnelProtocolPorts, but no other tunnel protocol
  396. // parameters are required.
  397. MeekServerInproxyBrokerOnly bool
  398. // InproxyBrokerSessionPrivateKey specifies the broker's in-proxy session
  399. // private key and derived public key used by in-proxy clients and
  400. // proxies. This value is required when running an in-proxy broker.
  401. InproxyBrokerSessionPrivateKey string
  402. // InproxyBrokerObfuscationRootSecret specifies the broker's in-proxy
  403. // session root obfuscation secret used by in-proxy clients and proxies.
  404. // This value is required when running an in-proxy broker.
  405. InproxyBrokerObfuscationRootSecret string
  406. // InproxyBrokerServerEntrySignaturePublicKey specifies the public key
  407. // used to verify Psiphon server entry signature. This value is required
  408. // when running an in-proxy broker.
  409. InproxyBrokerServerEntrySignaturePublicKey string
  410. // InproxyBrokerAllowCommonASNMatching overrides the default broker
  411. // matching behavior which doesn't match non-personal in-proxy clients
  412. // and proxies from the same ASN. This parameter is for testing only.
  413. InproxyBrokerAllowCommonASNMatching bool
  414. // InproxyBrokerAllowBogonWebRTCConnections overrides the default broker
  415. // SDP validation behavior, which doesn't allow private network WebRTC
  416. // candidates. This parameter is for testing only.
  417. InproxyBrokerAllowBogonWebRTCConnections bool
  418. // InproxyServerSessionPrivateKey specifies the server's in-proxy session
  419. // private key and derived public key used by brokers. This value is
  420. // required when running in-proxy tunnel protocols.
  421. InproxyServerSessionPrivateKey string
  422. // InproxyServerObfuscationRootSecret specifies the server's in-proxy
  423. // session root obfuscation secret used by brokers. This value is
  424. // required when running in-proxy tunnel protocols.
  425. InproxyServerObfuscationRootSecret string
  426. // IptablesAcceptRateLimitChainName, when set, enables programmatic
  427. // configuration of iptables rules to allow and apply rate limits to
  428. // tunnel protocol network ports. The configuration is applied to the
  429. // specified chain.
  430. //
  431. // For details, see configureIptablesAcceptRateLimitChain.
  432. IptablesAcceptRateLimitChainName string
  433. // IptablesAcceptRateLimitTunnelProtocolRateLimits specifies custom
  434. // iptables rate limits by tunnel protocol name. See
  435. // configureIptablesAcceptRateLimitChain details about the rate limit
  436. // values.
  437. IptablesAcceptRateLimitTunnelProtocolRateLimits map[string][2]int
  438. sshBeginHandshakeTimeout time.Duration
  439. sshHandshakeTimeout time.Duration
  440. peakUpstreamFailureRateMinimumSampleSize int
  441. periodicGarbageCollection time.Duration
  442. stopEstablishTunnelsEstablishedClientThreshold int
  443. dumpProfilesOnStopEstablishTunnelsDoneOnce int32
  444. providerID string
  445. frontingProviderID string
  446. region string
  447. runningProtocols []string
  448. runningOnlyInproxyBroker bool
  449. }
  450. // GetLogFileReopenConfig gets the reopen retries, and create/mode inputs for
  451. // rotate.NewRotatableFileWriter, which is used when writing to log files.
  452. //
  453. // By default, we expect the log files to be managed by logrotate, with
  454. // logrotate configured to re-create the next log file after rotation. As
  455. // described in the documentation for rotate.NewRotatableFileWriter, and as
  456. // observed in production, we occasionally need retries when attempting to
  457. // reopen the log file post-rotation; and we avoid conflicts, and spurious
  458. // re-rotations, by disabling file create in rotate.NewRotatableFileWriter. In
  459. // large scale production, incidents requiring retry are very rare, so the
  460. // retry delay is not expected to have a significant impact on performance.
  461. //
  462. // The defaults may be overriden in the Config.
  463. func (config *Config) GetLogFileReopenConfig() (int, bool, os.FileMode) {
  464. retries := DEFAULT_LOG_FILE_REOPEN_RETRIES
  465. if config.LogFileReopenRetries != nil {
  466. retries = *config.LogFileReopenRetries
  467. }
  468. create := false
  469. mode := os.FileMode(0)
  470. if config.LogFileCreateMode != nil {
  471. create = true
  472. mode = os.FileMode(*config.LogFileCreateMode)
  473. }
  474. return retries, create, mode
  475. }
  476. // RunLoadMonitor indicates whether to monitor and log server load.
  477. func (config *Config) RunLoadMonitor() bool {
  478. return config.LoadMonitorPeriodSeconds > 0
  479. }
  480. // RunPeriodicGarbageCollection indicates whether to run periodic garbage collection.
  481. func (config *Config) RunPeriodicGarbageCollection() bool {
  482. return config.periodicGarbageCollection > 0
  483. }
  484. // DumpProfilesOnStopEstablishTunnels indicates whether dump profiles due to
  485. // an unexpectedly low number of established clients during high load.
  486. func (config *Config) DumpProfilesOnStopEstablishTunnels(establishedClientsCount int) bool {
  487. if config.stopEstablishTunnelsEstablishedClientThreshold < 0 {
  488. return false
  489. }
  490. if config.runningOnlyInproxyBroker {
  491. // There will always be zero established clients when running only the
  492. // in-proxy broker and no tunnel protocols.
  493. return false
  494. }
  495. if atomic.LoadInt32(&config.dumpProfilesOnStopEstablishTunnelsDoneOnce) != 0 {
  496. return false
  497. }
  498. dump := (establishedClientsCount <= config.stopEstablishTunnelsEstablishedClientThreshold)
  499. if dump {
  500. atomic.StoreInt32(&config.dumpProfilesOnStopEstablishTunnelsDoneOnce, 1)
  501. }
  502. return dump
  503. }
  504. // GetOwnEncodedServerEntry returns one of the server's own server entries, as
  505. // identified by the server entry tag.
  506. func (config *Config) GetOwnEncodedServerEntry(serverEntryTag string) (string, bool) {
  507. serverEntry, ok := config.OwnEncodedServerEntries[serverEntryTag]
  508. return serverEntry, ok
  509. }
  510. // GetProviderID returns the provider ID associated with the server.
  511. func (config *Config) GetProviderID() string {
  512. return config.providerID
  513. }
  514. // GetFrontingProviderID returns the fronting provider ID associated with the
  515. // server's fronted protocol(s).
  516. func (config *Config) GetFrontingProviderID() string {
  517. return config.frontingProviderID
  518. }
  519. // GetRegion returns the region associated with the server.
  520. func (config *Config) GetRegion() string {
  521. return config.region
  522. }
  523. // GetRunningProtocols returns the list of protcols this server is running.
  524. // The caller must not mutate the return value.
  525. func (config *Config) GetRunningProtocols() []string {
  526. return config.runningProtocols
  527. }
  528. // GetRunningOnlyInproxyBroker indicates if the server is running only the
  529. // in-proxy broker and no tunnel protocols.
  530. func (config *Config) GetRunningOnlyInproxyBroker() bool {
  531. return config.runningOnlyInproxyBroker
  532. }
  533. // LoadConfig loads and validates a JSON encoded server config.
  534. func LoadConfig(configJSON []byte) (*Config, error) {
  535. var config Config
  536. err := json.Unmarshal(configJSON, &config)
  537. if err != nil {
  538. return nil, errors.Trace(err)
  539. }
  540. if config.ServerIPAddress == "" {
  541. return nil, errors.TraceNew("ServerIPAddress is required")
  542. }
  543. if config.MeekServerRunInproxyBroker {
  544. if config.InproxyBrokerSessionPrivateKey == "" {
  545. return nil, errors.TraceNew("Inproxy Broker requires InproxyBrokerSessionPrivateKey")
  546. }
  547. if config.InproxyBrokerObfuscationRootSecret == "" {
  548. return nil, errors.TraceNew("Inproxy Broker requires InproxyBrokerObfuscationRootSecret")
  549. }
  550. // There must be at least one meek tunnel protocol configured for
  551. // MeekServer to run and host an in-proxy broker. Since each
  552. // MeekServer instance runs its own in-proxy Broker instance, allow
  553. // at most one meek tunnel protocol to be configured so all
  554. // connections to the broker use the same, unambiguous instance.
  555. meekServerCount := 0
  556. for tunnelProtocol := range config.TunnelProtocolPorts {
  557. if protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  558. meekServerCount += 1
  559. }
  560. }
  561. if meekServerCount != 1 {
  562. return nil, errors.TraceNew("Inproxy Broker requires one MeekServer instance")
  563. }
  564. }
  565. if config.MeekServerInproxyBrokerOnly {
  566. if !config.MeekServerRunInproxyBroker {
  567. return nil, errors.TraceNew("Inproxy Broker-only mode requires MeekServerRunInproxyBroker")
  568. }
  569. }
  570. if config.ObfuscatedSSHKey != "" {
  571. // Any SSHServerVersion selected here will take precedence over a
  572. // value specified in the JSON config. Furthermore, the JSON config
  573. // may omit SSHServerVersion as long as ObfuscatedSSHKey is specified
  574. // and a value is selected.
  575. seed, err := protocol.DeriveSSHServerVersionPRNGSeed(config.ObfuscatedSSHKey)
  576. if err != nil {
  577. return nil, errors.Tracef(
  578. "DeriveSSHServerVersionPRNGSeed failed: %s", err)
  579. }
  580. serverVersion := values.GetSSHServerVersion(seed)
  581. if serverVersion != "" {
  582. config.SSHServerVersion = serverVersion
  583. }
  584. }
  585. config.runningProtocols = []string{}
  586. config.runningOnlyInproxyBroker = config.MeekServerRunInproxyBroker
  587. for tunnelProtocol := range config.TunnelProtocolPorts {
  588. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  589. return nil, errors.Tracef("Unsupported tunnel protocol: %s", tunnelProtocol)
  590. }
  591. if config.MeekServerInproxyBrokerOnly && protocol.TunnelProtocolUsesMeek(tunnelProtocol) {
  592. // In in-proxy broker-only mode, the TunnelProtocolPorts must be
  593. // specified in order to run the MeekServer, but none of the
  594. // following meek tunnel parameters are required.
  595. continue
  596. }
  597. if protocol.TunnelProtocolUsesInproxy(tunnelProtocol) && !inproxy.Enabled() {
  598. // Note that, technically, it may be possible to allow this case,
  599. // since PSIPHON_ENABLE_INPROXY is currently required only for
  600. // client/proxy-side WebRTC functionality, although that could change.
  601. return nil, errors.TraceNew("inproxy implementation is not enabled")
  602. }
  603. if protocol.TunnelProtocolUsesSSH(tunnelProtocol) ||
  604. protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  605. if config.SSHPrivateKey == "" || config.SSHServerVersion == "" ||
  606. config.SSHUserName == "" || config.SSHPassword == "" {
  607. return nil, errors.Tracef(
  608. "Tunnel protocol %s requires SSHPrivateKey, SSHServerVersion, SSHUserName, SSHPassword",
  609. tunnelProtocol)
  610. }
  611. }
  612. if protocol.TunnelProtocolUsesObfuscatedSSH(tunnelProtocol) {
  613. if config.ObfuscatedSSHKey == "" {
  614. return nil, errors.Tracef(
  615. "Tunnel protocol %s requires ObfuscatedSSHKey",
  616. tunnelProtocol)
  617. }
  618. }
  619. if protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  620. // Meek obfuscated key used for legacy reasons. See comment for
  621. // MeekObfuscatedKey.
  622. if config.MeekObfuscatedKey == "" {
  623. return nil, errors.Tracef(
  624. "Tunnel protocol %s requires MeekObfuscatedKey",
  625. tunnelProtocol)
  626. }
  627. }
  628. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  629. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  630. if config.MeekCookieEncryptionPrivateKey == "" || config.MeekObfuscatedKey == "" {
  631. return nil, errors.Tracef(
  632. "Tunnel protocol %s requires MeekCookieEncryptionPrivateKey, MeekObfuscatedKey",
  633. tunnelProtocol)
  634. }
  635. }
  636. // For FRONTED QUIC and HTTP, HTTPS is always used on the
  637. // edge-to-server hop, so it must be enabled or else this
  638. // configuration will not work. There is no FRONTED QUIC listener at
  639. // all; see TunnelServer.Run.
  640. if protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  641. _, ok := config.TunnelProtocolPorts[protocol.TUNNEL_PROTOCOL_FRONTED_MEEK]
  642. if !ok {
  643. return nil, errors.Tracef(
  644. "Tunnel protocol %s requires %s to be enabled",
  645. tunnelProtocol,
  646. protocol.TUNNEL_PROTOCOL_FRONTED_MEEK)
  647. }
  648. }
  649. config.runningProtocols = append(config.runningProtocols, tunnelProtocol)
  650. config.runningOnlyInproxyBroker = false
  651. }
  652. for tunnelProtocol, address := range config.TunnelProtocolPassthroughAddresses {
  653. if !protocol.TunnelProtocolSupportsPassthrough(tunnelProtocol) {
  654. return nil, errors.Tracef("Passthrough unsupported tunnel protocol: %s", tunnelProtocol)
  655. }
  656. if _, _, err := net.SplitHostPort(address); err != nil {
  657. if err != nil {
  658. return nil, errors.Tracef(
  659. "Tunnel protocol %s passthrough address %s invalid: %s",
  660. tunnelProtocol, address, err)
  661. }
  662. }
  663. }
  664. config.sshBeginHandshakeTimeout = SSH_BEGIN_HANDSHAKE_TIMEOUT
  665. if config.SSHBeginHandshakeTimeoutMilliseconds != nil {
  666. config.sshBeginHandshakeTimeout = time.Duration(*config.SSHBeginHandshakeTimeoutMilliseconds) * time.Millisecond
  667. }
  668. config.sshHandshakeTimeout = SSH_HANDSHAKE_TIMEOUT
  669. if config.SSHHandshakeTimeoutMilliseconds != nil {
  670. config.sshHandshakeTimeout = time.Duration(*config.SSHHandshakeTimeoutMilliseconds) * time.Millisecond
  671. }
  672. if config.UDPInterceptUdpgwServerAddress != "" {
  673. if err := validateNetworkAddress(config.UDPInterceptUdpgwServerAddress, true); err != nil {
  674. return nil, errors.Tracef("UDPInterceptUdpgwServerAddress is invalid: %s", err)
  675. }
  676. }
  677. if config.DNSResolverIPAddress != "" {
  678. if net.ParseIP(config.DNSResolverIPAddress) == nil {
  679. return nil, errors.Tracef("DNSResolverIPAddress is invalid")
  680. }
  681. }
  682. config.peakUpstreamFailureRateMinimumSampleSize = PEAK_UPSTREAM_FAILURE_RATE_MINIMUM_SAMPLE_SIZE
  683. if config.PeakUpstreamFailureRateMinimumSampleSize != nil {
  684. config.peakUpstreamFailureRateMinimumSampleSize = *config.PeakUpstreamFailureRateMinimumSampleSize
  685. }
  686. config.periodicGarbageCollection = PERIODIC_GARBAGE_COLLECTION
  687. if config.PeriodicGarbageCollectionSeconds != nil {
  688. config.periodicGarbageCollection = time.Duration(*config.PeriodicGarbageCollectionSeconds) * time.Second
  689. }
  690. config.stopEstablishTunnelsEstablishedClientThreshold = STOP_ESTABLISH_TUNNELS_ESTABLISHED_CLIENT_THRESHOLD
  691. if config.StopEstablishTunnelsEstablishedClientThreshold != nil {
  692. config.stopEstablishTunnelsEstablishedClientThreshold = *config.StopEstablishTunnelsEstablishedClientThreshold
  693. }
  694. err = accesscontrol.ValidateVerificationKeyRing(&config.AccessControlVerificationKeyRing)
  695. if err != nil {
  696. return nil, errors.Tracef(
  697. "AccessControlVerificationKeyRing is invalid: %s", err)
  698. }
  699. // Limitation: the following is a shortcut which extracts the server's
  700. // fronting provider ID from the server's OwnEncodedServerEntries. This logic
  701. // assumes a server has only one fronting provider. In principle, it's
  702. // possible for server with multiple server entries to run multiple fronted
  703. // protocols, each with a different fronting provider ID.
  704. //
  705. // TODO: add an explicit parameter mapping tunnel protocol ports to fronting
  706. // provider IDs.
  707. for _, encodedServerEntry := range config.OwnEncodedServerEntries {
  708. serverEntry, err := protocol.DecodeServerEntry(encodedServerEntry, "", "")
  709. if err != nil {
  710. return nil, errors.Tracef(
  711. "protocol.DecodeServerEntry failed: %s", err)
  712. }
  713. if config.providerID == "" {
  714. config.providerID = serverEntry.ProviderID
  715. } else if config.providerID != serverEntry.ProviderID {
  716. return nil, errors.Tracef("unsupported multiple ProviderID values")
  717. }
  718. if config.frontingProviderID == "" {
  719. config.frontingProviderID = serverEntry.FrontingProviderID
  720. } else if config.frontingProviderID != serverEntry.FrontingProviderID {
  721. return nil, errors.Tracef("unsupported multiple FrontingProviderID values")
  722. }
  723. if config.region == "" {
  724. config.region = serverEntry.Region
  725. } else if config.region != serverEntry.Region {
  726. return nil, errors.Tracef("unsupported multiple Region values")
  727. }
  728. }
  729. return &config, nil
  730. }
  731. func validateNetworkAddress(address string, requireIPaddress bool) error {
  732. host, portStr, err := net.SplitHostPort(address)
  733. if err != nil {
  734. return err
  735. }
  736. if requireIPaddress && net.ParseIP(host) == nil {
  737. return errors.TraceNew("host must be an IP address")
  738. }
  739. port, err := strconv.Atoi(portStr)
  740. if err != nil {
  741. return err
  742. }
  743. if port < 0 || port > 65535 {
  744. return errors.TraceNew("invalid port")
  745. }
  746. return nil
  747. }
  748. // GenerateConfigParams specifies customizations to be applied to
  749. // a generated server config.
  750. type GenerateConfigParams struct {
  751. LogFilename string
  752. SkipPanickingLogWriter bool
  753. LogLevel string
  754. ServerEntrySignaturePublicKey string
  755. ServerEntrySignaturePrivateKey string
  756. ServerIPAddress string
  757. TunnelProtocolPorts map[string]int
  758. TunnelProtocolPassthroughAddresses map[string]string
  759. TrafficRulesConfigFilename string
  760. OSLConfigFilename string
  761. TacticsConfigFilename string
  762. TacticsRequestPublicKey string
  763. TacticsRequestObfuscatedKey string
  764. Passthrough bool
  765. LegacyPassthrough bool
  766. LimitQUICVersions protocol.QUICVersions
  767. EnableGQUIC bool
  768. FrontingProviderID string
  769. }
  770. // GenerateConfig creates a new Psiphon server config. It returns JSON encoded
  771. // configs and a client-compatible "server entry" for the server. It generates
  772. // all necessary secrets and key material, which are emitted in the config
  773. // file and server entry as necessary.
  774. //
  775. // GenerateConfig uses sample values for many fields. The intention is for
  776. // generated configs to be used for testing or as examples for production
  777. // setup, not to generate production-ready configurations.
  778. //
  779. // When tactics key material is provided in GenerateConfigParams, tactics
  780. // capabilities are added for all meek protocols in TunnelProtocolPorts.
  781. func GenerateConfig(params *GenerateConfigParams) ([]byte, []byte, []byte, []byte, []byte, error) {
  782. // Input validation
  783. if net.ParseIP(params.ServerIPAddress) == nil {
  784. return nil, nil, nil, nil, nil, errors.TraceNew("invalid IP address")
  785. }
  786. if len(params.TunnelProtocolPorts) == 0 {
  787. return nil, nil, nil, nil, nil, errors.TraceNew("no tunnel protocols")
  788. }
  789. usedPort := make(map[int]bool)
  790. usingMeek := false
  791. usingTLSOSSH := false
  792. usingInproxy := false
  793. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  794. if !common.Contains(protocol.SupportedTunnelProtocols, tunnelProtocol) {
  795. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tunnel protocol")
  796. }
  797. if usedPort[port] {
  798. return nil, nil, nil, nil, nil, errors.TraceNew("duplicate listening port")
  799. }
  800. usedPort[port] = true
  801. if protocol.TunnelProtocolUsesTLSOSSH(tunnelProtocol) {
  802. usingTLSOSSH = true
  803. }
  804. if protocol.TunnelProtocolUsesMeekHTTP(tunnelProtocol) ||
  805. protocol.TunnelProtocolUsesMeekHTTPS(tunnelProtocol) {
  806. usingMeek = true
  807. }
  808. if protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  809. usingInproxy = true
  810. }
  811. }
  812. // One test mode populates the tactics config file; this will generate
  813. // keys. Another test mode passes in existing keys to be used in the
  814. // server entry. Both the filename and existing keys cannot be passed in.
  815. if (params.TacticsConfigFilename != "") &&
  816. (params.TacticsRequestPublicKey != "" || params.TacticsRequestObfuscatedKey != "") {
  817. return nil, nil, nil, nil, nil, errors.TraceNew("invalid tactics parameters")
  818. }
  819. // SSH config
  820. rsaKey, err := rsa.GenerateKey(rand.Reader, SSH_RSA_HOST_KEY_BITS)
  821. if err != nil {
  822. return nil, nil, nil, nil, nil, errors.Trace(err)
  823. }
  824. sshPrivateKey := pem.EncodeToMemory(
  825. &pem.Block{
  826. Type: "RSA PRIVATE KEY",
  827. Bytes: x509.MarshalPKCS1PrivateKey(rsaKey),
  828. },
  829. )
  830. signer, err := ssh.NewSignerFromKey(rsaKey)
  831. if err != nil {
  832. return nil, nil, nil, nil, nil, errors.Trace(err)
  833. }
  834. sshPublicKey := signer.PublicKey()
  835. sshUserNameSuffixBytes, err := common.MakeSecureRandomBytes(SSH_USERNAME_SUFFIX_BYTE_LENGTH)
  836. if err != nil {
  837. return nil, nil, nil, nil, nil, errors.Trace(err)
  838. }
  839. sshUserNameSuffix := hex.EncodeToString(sshUserNameSuffixBytes)
  840. sshUserName := "psiphon_" + sshUserNameSuffix
  841. sshPasswordBytes, err := common.MakeSecureRandomBytes(SSH_PASSWORD_BYTE_LENGTH)
  842. if err != nil {
  843. return nil, nil, nil, nil, nil, errors.Trace(err)
  844. }
  845. sshPassword := hex.EncodeToString(sshPasswordBytes)
  846. sshServerVersion := "SSH-2.0-Psiphon"
  847. // Obfuscated SSH config
  848. obfuscatedSSHKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  849. if err != nil {
  850. return nil, nil, nil, nil, nil, errors.Trace(err)
  851. }
  852. obfuscatedSSHKey := hex.EncodeToString(obfuscatedSSHKeyBytes)
  853. // Shadowsocks config
  854. shadowsocksKeyBytes, err := common.MakeSecureRandomBytes(SHADOWSOCKS_KEY_BYTE_LENGTH)
  855. if err != nil {
  856. return nil, nil, nil, nil, nil, errors.Trace(err)
  857. }
  858. shadowsocksKey := hex.EncodeToString(shadowsocksKeyBytes)
  859. // Meek config
  860. var meekCookieEncryptionPublicKey, meekCookieEncryptionPrivateKey, meekObfuscatedKey string
  861. if usingMeek {
  862. rawMeekCookieEncryptionPublicKey, rawMeekCookieEncryptionPrivateKey, err :=
  863. box.GenerateKey(rand.Reader)
  864. if err != nil {
  865. return nil, nil, nil, nil, nil, errors.Trace(err)
  866. }
  867. meekCookieEncryptionPublicKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPublicKey[:])
  868. meekCookieEncryptionPrivateKey = base64.StdEncoding.EncodeToString(rawMeekCookieEncryptionPrivateKey[:])
  869. }
  870. if usingMeek || usingTLSOSSH {
  871. meekObfuscatedKeyBytes, err := common.MakeSecureRandomBytes(SSH_OBFUSCATED_KEY_BYTE_LENGTH)
  872. if err != nil {
  873. return nil, nil, nil, nil, nil, errors.Trace(err)
  874. }
  875. meekObfuscatedKey = hex.EncodeToString(meekObfuscatedKeyBytes)
  876. }
  877. // Inproxy config
  878. var inproxyServerSessionPublicKey,
  879. inproxyServerSessionPrivateKey,
  880. inproxyServerObfuscationRootSecret string
  881. if usingInproxy {
  882. privateKey, err := inproxy.GenerateSessionPrivateKey()
  883. if err != nil {
  884. return nil, nil, nil, nil, nil, errors.Trace(err)
  885. }
  886. inproxyServerSessionPrivateKey = privateKey.String()
  887. publicKey, err := privateKey.GetPublicKey()
  888. if err != nil {
  889. return nil, nil, nil, nil, nil, errors.Trace(err)
  890. }
  891. inproxyServerSessionPublicKey = publicKey.String()
  892. obfuscationRootSecret, err := inproxy.GenerateRootObfuscationSecret()
  893. if err != nil {
  894. return nil, nil, nil, nil, nil, errors.Trace(err)
  895. }
  896. inproxyServerObfuscationRootSecret = obfuscationRootSecret.String()
  897. }
  898. // Other config
  899. discoveryValueHMACKeyBytes, err := common.MakeSecureRandomBytes(DISCOVERY_VALUE_KEY_BYTE_LENGTH)
  900. if err != nil {
  901. return nil, nil, nil, nil, nil, errors.Trace(err)
  902. }
  903. discoveryValueHMACKey := base64.StdEncoding.EncodeToString(discoveryValueHMACKeyBytes)
  904. // Generate a legacy web server secret, to accomodate test cases, such as deriving
  905. // a server entry tag when no tag is present.
  906. webServerSecretBytes, err := common.MakeSecureRandomBytes(WEB_SERVER_SECRET_BYTE_LENGTH)
  907. if err != nil {
  908. return nil, nil, nil, nil, nil, errors.Trace(err)
  909. }
  910. webServerSecret := hex.EncodeToString(webServerSecretBytes)
  911. // Assemble configs and server entry
  912. // Note: this config is intended for either testing or as an illustrative
  913. // example or template and is not intended for production deployment.
  914. logLevel := params.LogLevel
  915. if logLevel == "" {
  916. logLevel = "info"
  917. }
  918. // For testing, set the Psiphon server to create its log files; we do not
  919. // expect tests to necessarily run under log managers, such as logrotate.
  920. createMode := 0666
  921. config := &Config{
  922. LogLevel: logLevel,
  923. LogFilename: params.LogFilename,
  924. LogFileCreateMode: &createMode,
  925. SkipPanickingLogWriter: params.SkipPanickingLogWriter,
  926. GeoIPDatabaseFilenames: nil,
  927. HostID: "example-host-id",
  928. ServerIPAddress: params.ServerIPAddress,
  929. DiscoveryValueHMACKey: discoveryValueHMACKey,
  930. SSHPrivateKey: string(sshPrivateKey),
  931. SSHServerVersion: sshServerVersion,
  932. SSHUserName: sshUserName,
  933. SSHPassword: sshPassword,
  934. ShadowsocksKey: shadowsocksKey,
  935. ObfuscatedSSHKey: obfuscatedSSHKey,
  936. TunnelProtocolPorts: params.TunnelProtocolPorts,
  937. TunnelProtocolPassthroughAddresses: params.TunnelProtocolPassthroughAddresses,
  938. DNSResolverIPAddress: "8.8.8.8",
  939. UDPInterceptUdpgwServerAddress: "127.0.0.1:7300",
  940. MeekCookieEncryptionPrivateKey: meekCookieEncryptionPrivateKey,
  941. MeekObfuscatedKey: meekObfuscatedKey,
  942. MeekProhibitedHeaders: nil,
  943. MeekProxyForwardedForHeaders: []string{"X-Forwarded-For"},
  944. LoadMonitorPeriodSeconds: 300,
  945. TrafficRulesFilename: params.TrafficRulesConfigFilename,
  946. OSLConfigFilename: params.OSLConfigFilename,
  947. TacticsConfigFilename: params.TacticsConfigFilename,
  948. LegacyPassthrough: params.LegacyPassthrough,
  949. EnableGQUIC: params.EnableGQUIC,
  950. InproxyServerSessionPrivateKey: inproxyServerSessionPrivateKey,
  951. InproxyServerObfuscationRootSecret: inproxyServerObfuscationRootSecret,
  952. }
  953. encodedConfig, err := json.MarshalIndent(config, "\n", " ")
  954. if err != nil {
  955. return nil, nil, nil, nil, nil, errors.Trace(err)
  956. }
  957. intPtr := func(i int) *int {
  958. return &i
  959. }
  960. trafficRulesSet := &TrafficRulesSet{
  961. DefaultRules: TrafficRules{
  962. RateLimits: RateLimits{
  963. ReadUnthrottledBytes: new(int64),
  964. ReadBytesPerSecond: new(int64),
  965. WriteUnthrottledBytes: new(int64),
  966. WriteBytesPerSecond: new(int64),
  967. },
  968. IdleTCPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_TCP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  969. IdleUDPPortForwardTimeoutMilliseconds: intPtr(DEFAULT_IDLE_UDP_PORT_FORWARD_TIMEOUT_MILLISECONDS),
  970. MaxTCPPortForwardCount: intPtr(DEFAULT_MAX_TCP_PORT_FORWARD_COUNT),
  971. MaxUDPPortForwardCount: intPtr(DEFAULT_MAX_UDP_PORT_FORWARD_COUNT),
  972. AllowTCPPorts: nil,
  973. AllowUDPPorts: nil,
  974. },
  975. }
  976. encodedTrafficRulesSet, err := json.MarshalIndent(trafficRulesSet, "\n", " ")
  977. if err != nil {
  978. return nil, nil, nil, nil, nil, errors.Trace(err)
  979. }
  980. encodedOSLConfig, err := json.MarshalIndent(&osl.Config{}, "\n", " ")
  981. if err != nil {
  982. return nil, nil, nil, nil, nil, errors.Trace(err)
  983. }
  984. tacticsRequestPublicKey := params.TacticsRequestPublicKey
  985. tacticsRequestObfuscatedKey := params.TacticsRequestObfuscatedKey
  986. var tacticsRequestPrivateKey string
  987. var encodedTacticsConfig []byte
  988. if params.TacticsConfigFilename != "" {
  989. tacticsRequestPublicKey, tacticsRequestPrivateKey, tacticsRequestObfuscatedKey, err =
  990. tactics.GenerateKeys()
  991. if err != nil {
  992. return nil, nil, nil, nil, nil, errors.Trace(err)
  993. }
  994. decodedTacticsRequestPublicKey, err := base64.StdEncoding.DecodeString(tacticsRequestPublicKey)
  995. if err != nil {
  996. return nil, nil, nil, nil, nil, errors.Trace(err)
  997. }
  998. decodedTacticsRequestPrivateKey, err := base64.StdEncoding.DecodeString(tacticsRequestPrivateKey)
  999. if err != nil {
  1000. return nil, nil, nil, nil, nil, errors.Trace(err)
  1001. }
  1002. decodedTacticsRequestObfuscatedKey, err := base64.StdEncoding.DecodeString(tacticsRequestObfuscatedKey)
  1003. if err != nil {
  1004. return nil, nil, nil, nil, nil, errors.Trace(err)
  1005. }
  1006. tacticsConfig := &tactics.Server{
  1007. RequestPublicKey: decodedTacticsRequestPublicKey,
  1008. RequestPrivateKey: decodedTacticsRequestPrivateKey,
  1009. RequestObfuscatedKey: decodedTacticsRequestObfuscatedKey,
  1010. DefaultTactics: tactics.Tactics{
  1011. TTL: "1m",
  1012. },
  1013. }
  1014. encodedTacticsConfig, err = json.MarshalIndent(tacticsConfig, "\n", " ")
  1015. if err != nil {
  1016. return nil, nil, nil, nil, nil, errors.Trace(err)
  1017. }
  1018. }
  1019. // Capabilities
  1020. capabilities := []string{protocol.CAPABILITY_SSH_API_REQUESTS}
  1021. var frontingProviderID string
  1022. for tunnelProtocol := range params.TunnelProtocolPorts {
  1023. capability := protocol.GetCapability(tunnelProtocol)
  1024. // In-proxy tunnel protocol capabilities don't include
  1025. // v1/-PASSTHROUGHv2 suffixes; see comments in ServerEntry.hasCapability.
  1026. if !protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  1027. // Note: do not add passthrough annotation if HTTP unfronted meek
  1028. // because it would result in an invalid capability.
  1029. if params.Passthrough &&
  1030. protocol.TunnelProtocolSupportsPassthrough(tunnelProtocol) &&
  1031. tunnelProtocol != protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK {
  1032. if !params.LegacyPassthrough {
  1033. capability += "-PASSTHROUGH-v2"
  1034. } else {
  1035. capability += "-PASSTHROUGH"
  1036. }
  1037. }
  1038. if tunnelProtocol == protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH &&
  1039. !params.EnableGQUIC {
  1040. capability += "v1"
  1041. }
  1042. }
  1043. capabilities = append(capabilities, capability)
  1044. if params.TacticsRequestPublicKey != "" && params.TacticsRequestObfuscatedKey != "" &&
  1045. protocol.TunnelProtocolSupportsTactics(tunnelProtocol) {
  1046. capabilities = append(capabilities, protocol.GetTacticsCapability(tunnelProtocol))
  1047. }
  1048. if protocol.TunnelProtocolUsesFrontedMeek(tunnelProtocol) {
  1049. frontingProviderID = params.FrontingProviderID
  1050. }
  1051. }
  1052. // Tunnel protocol ports
  1053. // Limitations:
  1054. // - Only one meek port may be specified per server entry.
  1055. // - Neither fronted meek nor Conjuure protocols are supported here.
  1056. var sshPort, obfuscatedSSHPort, meekPort, obfuscatedSSHQUICPort, tlsOSSHPort, shadowsocksPort int
  1057. var inproxySSHPort, inproxyOSSHPort, inproxyQUICPort, inproxyMeekPort, inproxyTlsOSSHPort, inproxyShadowsocksPort int
  1058. for tunnelProtocol, port := range params.TunnelProtocolPorts {
  1059. if !protocol.TunnelProtocolUsesInproxy(tunnelProtocol) {
  1060. switch tunnelProtocol {
  1061. case protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  1062. tlsOSSHPort = port
  1063. case protocol.TUNNEL_PROTOCOL_SSH:
  1064. sshPort = port
  1065. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  1066. obfuscatedSSHPort = port
  1067. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  1068. obfuscatedSSHQUICPort = port
  1069. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  1070. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  1071. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  1072. meekPort = port
  1073. case protocol.TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  1074. shadowsocksPort = port
  1075. }
  1076. } else {
  1077. switch protocol.TunnelProtocolMinusInproxy(tunnelProtocol) {
  1078. case protocol.TUNNEL_PROTOCOL_TLS_OBFUSCATED_SSH:
  1079. inproxyTlsOSSHPort = port
  1080. case protocol.TUNNEL_PROTOCOL_SSH:
  1081. inproxySSHPort = port
  1082. case protocol.TUNNEL_PROTOCOL_OBFUSCATED_SSH:
  1083. inproxyOSSHPort = port
  1084. case protocol.TUNNEL_PROTOCOL_QUIC_OBFUSCATED_SSH:
  1085. inproxyQUICPort = port
  1086. case protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_HTTPS,
  1087. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK_SESSION_TICKET,
  1088. protocol.TUNNEL_PROTOCOL_UNFRONTED_MEEK:
  1089. inproxyMeekPort = port
  1090. case protocol.TUNNEL_PROTOCOL_SHADOWSOCKS_OSSH:
  1091. inproxyShadowsocksPort = port
  1092. }
  1093. }
  1094. }
  1095. // Note: fronting params are a stub; this server entry will exercise
  1096. // client and server fronting code paths, but not actually traverse
  1097. // a fronting hop.
  1098. serverEntry := &protocol.ServerEntry{
  1099. Tag: prng.Base64String(32),
  1100. IpAddress: params.ServerIPAddress,
  1101. WebServerSecret: webServerSecret,
  1102. TlsOSSHPort: tlsOSSHPort,
  1103. SshPort: sshPort,
  1104. SshUsername: sshUserName,
  1105. SshPassword: sshPassword,
  1106. SshHostKey: base64.StdEncoding.EncodeToString(sshPublicKey.Marshal()),
  1107. SshObfuscatedPort: obfuscatedSSHPort,
  1108. SshObfuscatedQUICPort: obfuscatedSSHQUICPort,
  1109. SshShadowsocksKey: shadowsocksKey,
  1110. SshShadowsocksPort: shadowsocksPort,
  1111. LimitQUICVersions: params.LimitQUICVersions,
  1112. SshObfuscatedKey: obfuscatedSSHKey,
  1113. Capabilities: capabilities,
  1114. Region: "US",
  1115. ProviderID: strings.ToUpper(prng.HexString(8)),
  1116. FrontingProviderID: frontingProviderID,
  1117. MeekServerPort: meekPort,
  1118. MeekCookieEncryptionPublicKey: meekCookieEncryptionPublicKey,
  1119. MeekObfuscatedKey: meekObfuscatedKey,
  1120. MeekFrontingHosts: []string{params.ServerIPAddress},
  1121. MeekFrontingAddresses: []string{params.ServerIPAddress},
  1122. MeekFrontingDisableSNI: false,
  1123. TacticsRequestPublicKey: tacticsRequestPublicKey,
  1124. TacticsRequestObfuscatedKey: tacticsRequestObfuscatedKey,
  1125. ConfigurationVersion: 1,
  1126. InproxySessionPublicKey: inproxyServerSessionPublicKey,
  1127. InproxySessionRootObfuscationSecret: inproxyServerObfuscationRootSecret,
  1128. InproxySSHPort: inproxySSHPort,
  1129. InproxyOSSHPort: inproxyOSSHPort,
  1130. InproxyQUICPort: inproxyQUICPort,
  1131. InproxyMeekPort: inproxyMeekPort,
  1132. InproxyTlsOSSHPort: inproxyTlsOSSHPort,
  1133. InproxyShadowsocksPort: inproxyShadowsocksPort,
  1134. }
  1135. if params.ServerEntrySignaturePublicKey != "" {
  1136. serverEntryJSON, err := json.Marshal(serverEntry)
  1137. if err != nil {
  1138. return nil, nil, nil, nil, nil, errors.Trace(err)
  1139. }
  1140. var serverEntryFields protocol.ServerEntryFields
  1141. err = json.Unmarshal(serverEntryJSON, &serverEntryFields)
  1142. if err != nil {
  1143. return nil, nil, nil, nil, nil, errors.Trace(err)
  1144. }
  1145. err = serverEntryFields.AddSignature(
  1146. params.ServerEntrySignaturePublicKey, params.ServerEntrySignaturePrivateKey)
  1147. if err != nil {
  1148. return nil, nil, nil, nil, nil, errors.Trace(err)
  1149. }
  1150. serverEntry, err = serverEntryFields.GetServerEntry()
  1151. if err != nil {
  1152. return nil, nil, nil, nil, nil, errors.Trace(err)
  1153. }
  1154. }
  1155. encodedServerEntry, err := protocol.EncodeServerEntry(serverEntry)
  1156. if err != nil {
  1157. return nil, nil, nil, nil, nil, errors.Trace(err)
  1158. }
  1159. return encodedConfig, encodedTrafficRulesSet, encodedOSLConfig, encodedTacticsConfig, []byte(encodedServerEntry), nil
  1160. }