config.go 51 KB

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