main.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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 main
  20. import (
  21. "encoding/json"
  22. "flag"
  23. "fmt"
  24. "io"
  25. "io/ioutil"
  26. "os"
  27. "runtime/debug"
  28. "strconv"
  29. "strings"
  30. "syscall"
  31. "time"
  32. "github.com/Psiphon-Inc/rotate-safe-writer"
  33. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
  34. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/buildinfo"
  35. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/server"
  36. "github.com/mitchellh/panicwrap"
  37. )
  38. var loadedConfigJSON []byte
  39. func main() {
  40. var configFilename string
  41. var generateServerIPaddress string
  42. var generateServerNetworkInterface string
  43. var generateProtocolPorts stringListFlag
  44. var generateWebServerPort int
  45. var generateLogFilename string
  46. var generateTrafficRulesConfigFilename string
  47. var generateOSLConfigFilename string
  48. var generateTacticsConfigFilename string
  49. var generateServerEntryFilename string
  50. flag.StringVar(
  51. &configFilename,
  52. "config",
  53. server.SERVER_CONFIG_FILENAME,
  54. "run or generate with this config `filename`")
  55. flag.StringVar(
  56. &generateServerIPaddress,
  57. "ipaddress",
  58. server.DEFAULT_SERVER_IP_ADDRESS,
  59. "generate with this server `IP address`")
  60. flag.StringVar(
  61. &generateServerNetworkInterface,
  62. "interface",
  63. "",
  64. "generate with server IP address from this `network-interface`")
  65. flag.Var(
  66. &generateProtocolPorts,
  67. "protocol",
  68. "generate with `protocol:port`; flag may be repeated to enable multiple protocols")
  69. flag.IntVar(
  70. &generateWebServerPort,
  71. "web",
  72. 0,
  73. "generate with web server `port`; 0 for no web server")
  74. flag.StringVar(
  75. &generateLogFilename,
  76. "logFilename",
  77. "",
  78. "set application log file name and path; blank for stderr")
  79. flag.StringVar(
  80. &generateTrafficRulesConfigFilename,
  81. "trafficRules",
  82. server.SERVER_TRAFFIC_RULES_CONFIG_FILENAME,
  83. "generate with this traffic rules config `filename`")
  84. flag.StringVar(
  85. &generateOSLConfigFilename,
  86. "osl",
  87. server.SERVER_OSL_CONFIG_FILENAME,
  88. "generate with this OSL config `filename`")
  89. flag.StringVar(
  90. &generateTacticsConfigFilename,
  91. "tactics",
  92. server.SERVER_TACTICS_CONFIG_FILENAME,
  93. "generate with this tactics config `filename`")
  94. flag.StringVar(
  95. &generateServerEntryFilename,
  96. "serverEntry",
  97. server.SERVER_ENTRY_FILENAME,
  98. "generate with this server entry `filename`")
  99. flag.Usage = func() {
  100. fmt.Fprintf(os.Stderr,
  101. "Usage:\n\n"+
  102. "%s <flags> generate generates configuration files\n"+
  103. "%s <flags> run runs configured services\n\n",
  104. os.Args[0], os.Args[0])
  105. flag.PrintDefaults()
  106. }
  107. flag.Parse()
  108. args := flag.Args()
  109. if len(args) < 1 {
  110. flag.Usage()
  111. os.Exit(1)
  112. } else if args[0] == "generate" {
  113. serverIPaddress := generateServerIPaddress
  114. if generateServerNetworkInterface != "" {
  115. // TODO: IPv6 support
  116. serverIPv4Address, _, err := common.GetInterfaceIPAddresses(generateServerNetworkInterface)
  117. if err == nil && serverIPv4Address == nil {
  118. err = fmt.Errorf("no IPv4 address for interface %s", generateServerNetworkInterface)
  119. }
  120. if err != nil {
  121. fmt.Printf("generate failed: %s\n", err)
  122. os.Exit(1)
  123. }
  124. serverIPaddress = serverIPv4Address.String()
  125. }
  126. tunnelProtocolPorts := make(map[string]int)
  127. for _, protocolPort := range generateProtocolPorts {
  128. parts := strings.Split(protocolPort, ":")
  129. if len(parts) == 2 {
  130. port, err := strconv.Atoi(parts[1])
  131. if err != nil {
  132. fmt.Printf("generate failed: %s\n", err)
  133. os.Exit(1)
  134. }
  135. tunnelProtocolPorts[parts[0]] = port
  136. }
  137. }
  138. configJSON, trafficRulesConfigJSON, OSLConfigJSON,
  139. tacticsConfigJSON, encodedServerEntry, err :=
  140. server.GenerateConfig(
  141. &server.GenerateConfigParams{
  142. LogFilename: generateLogFilename,
  143. ServerIPAddress: serverIPaddress,
  144. TunnelProtocolPorts: tunnelProtocolPorts,
  145. TrafficRulesConfigFilename: generateTrafficRulesConfigFilename,
  146. OSLConfigFilename: generateOSLConfigFilename,
  147. TacticsConfigFilename: generateTacticsConfigFilename,
  148. })
  149. if err != nil {
  150. fmt.Printf("generate failed: %s\n", err)
  151. os.Exit(1)
  152. }
  153. err = ioutil.WriteFile(configFilename, configJSON, 0600)
  154. if err != nil {
  155. fmt.Printf("error writing configuration file: %s\n", err)
  156. os.Exit(1)
  157. }
  158. err = ioutil.WriteFile(generateTrafficRulesConfigFilename, trafficRulesConfigJSON, 0600)
  159. if err != nil {
  160. fmt.Printf("error writing traffic rule config file: %s\n", err)
  161. os.Exit(1)
  162. }
  163. err = ioutil.WriteFile(generateOSLConfigFilename, OSLConfigJSON, 0600)
  164. if err != nil {
  165. fmt.Printf("error writing OSL config file: %s\n", err)
  166. os.Exit(1)
  167. }
  168. err = ioutil.WriteFile(generateTacticsConfigFilename, tacticsConfigJSON, 0600)
  169. if err != nil {
  170. fmt.Printf("error writing tactics config file: %s\n", err)
  171. os.Exit(1)
  172. }
  173. err = ioutil.WriteFile(generateServerEntryFilename, encodedServerEntry, 0600)
  174. if err != nil {
  175. fmt.Printf("error writing server entry file: %s\n", err)
  176. os.Exit(1)
  177. }
  178. } else if args[0] == "run" {
  179. configJSON, err := ioutil.ReadFile(configFilename)
  180. if err != nil {
  181. fmt.Printf("error loading configuration file: %s\n", err)
  182. os.Exit(1)
  183. }
  184. loadedConfigJSON = configJSON
  185. // The initial call to panicwrap.Wrap will spawn a child process
  186. // running the same program.
  187. //
  188. // The parent process waits for the child to terminate and
  189. // panicHandler logs any panics from the child.
  190. //
  191. // The child will return immediately from Wrap without spawning
  192. // and fall through to server.RunServices.
  193. // Unhandled panic wrapper. Logs it, then re-executes the current executable
  194. exitStatus, err := panicwrap.Wrap(&panicwrap.WrapConfig{
  195. Handler: panicHandler,
  196. ForwardSignals: []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTSTP, syscall.SIGCONT},
  197. })
  198. if err != nil {
  199. fmt.Printf("failed to set up the panic wrapper: %s\n", err)
  200. os.Exit(1)
  201. }
  202. // Note: panicwrap.Wrap documentation states that exitStatus == -1
  203. // should be used to determine whether the process is the child.
  204. // However, we have found that this exitStatus is returned even when
  205. // the process is the parent. Likely due to panicwrap returning
  206. // syscall.WaitStatus.ExitStatus() as the exitStatus, which _can_ be
  207. // -1. Checking panicwrap.Wrapped(nil) is more reliable.
  208. if !panicwrap.Wrapped(nil) {
  209. os.Exit(exitStatus)
  210. }
  211. // Else, this is the child process.
  212. // As of Go 1.19.10, programs with Linux capabilities or setuid do not
  213. // dump panic stacks by default. See:
  214. // https://github.com/golang/go/commit/a7b1cd452ddc69a6606c2f35ac5786dc892e62cb.
  215. // To restore panic stacks, we call SetTraceback("single"), restoring
  216. // the default GOTRACKBACK value. The server program is run as a
  217. // non-privileged user and with CAP_NET capabilities; neither the
  218. // panic stack traces nor register dumps are expected to expose any
  219. // unexpected sensitive information.
  220. debug.SetTraceback("single")
  221. err = server.RunServices(configJSON)
  222. if err != nil {
  223. fmt.Printf("run failed: %s\n", err)
  224. os.Exit(1)
  225. }
  226. }
  227. }
  228. type stringListFlag []string
  229. func (list *stringListFlag) String() string {
  230. return strings.Join(*list, ", ")
  231. }
  232. func (list *stringListFlag) Set(flagValue string) error {
  233. *list = append(*list, flagValue)
  234. return nil
  235. }
  236. func panicHandler(output string) {
  237. if len(loadedConfigJSON) > 0 {
  238. config, err := server.LoadConfig([]byte(loadedConfigJSON))
  239. if err != nil {
  240. fmt.Printf("error parsing configuration file: %s\n%s\n", err, output)
  241. os.Exit(1)
  242. }
  243. logEvent := make(map[string]string)
  244. logEvent["host_id"] = config.HostID
  245. logEvent["build_rev"] = buildinfo.GetBuildInfo().BuildRev
  246. logEvent["timestamp"] = time.Now().Format(time.RFC3339)
  247. logEvent["event_name"] = "server_panic"
  248. // ELK has a maximum field length of 32766 UTF8 bytes. Over that length, the
  249. // log won't be delivered. Truncate the panic field, as it may be much longer.
  250. maxLen := 32766
  251. if len(output) > maxLen {
  252. output = output[:maxLen]
  253. }
  254. logEvent["panic"] = output
  255. // Logs are written to the configured file name. If no name is specified, logs are written to stderr
  256. var jsonWriter io.Writer
  257. if config.LogFilename != "" {
  258. retries, create, mode := config.GetLogFileReopenConfig()
  259. panicLog, err := rotate.NewRotatableFileWriter(
  260. config.LogFilename, retries, create, mode)
  261. if err != nil {
  262. fmt.Printf("unable to set panic log output: %s\n%s\n", err, output)
  263. os.Exit(1)
  264. }
  265. defer panicLog.Close()
  266. jsonWriter = panicLog
  267. } else {
  268. jsonWriter = os.Stderr
  269. }
  270. enc := json.NewEncoder(jsonWriter)
  271. err = enc.Encode(logEvent)
  272. if err != nil {
  273. fmt.Printf("unable to serialize panic message to JSON: %s\n%s\n", err, output)
  274. os.Exit(1)
  275. }
  276. } else {
  277. fmt.Printf("no configuration JSON was loaded, cannot continue\n%s\n", output)
  278. os.Exit(1)
  279. }
  280. os.Exit(1)
  281. }