You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

214 lines
6.0 KiB

  1. /*
  2. Copyright © 2019 Devan Carpenter <mail@dvn.me>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /*
  15. TODO: Check if device_name already exists in DB, and quit, if so.
  16. */
  17. package cmd
  18. import (
  19. "fmt"
  20. "log"
  21. "os"
  22. "os/exec"
  23. "io"
  24. "strings"
  25. "boxen/config"
  26. "boxen/db"
  27. "boxen/utils"
  28. "github.com/eugenmayer/go-sshclient/sshwrapper"
  29. "github.com/sethvargo/go-password/password"
  30. "github.com/spf13/cobra"
  31. "gopkg.in/ini.v1"
  32. )
  33. var (
  34. host string
  35. user string
  36. port int
  37. name string
  38. privkey string
  39. sshKeyPath string = fmt.Sprintf("%sid_rsa_boxen", config.SshPath)
  40. )
  41. // initCmd represents the init command
  42. var initCmd = &cobra.Command{
  43. Use: "init",
  44. Short: "Initialize a new device",
  45. Long: `Initialize a new device.
  46. You will name it and authorize yourself as the owner.`,
  47. Run: initProcess,
  48. }
  49. func init() {
  50. RootCmd.AddCommand(initCmd)
  51. initCmd.Flags().StringVar(&host, "host", "", "Required: The hostname or IP of the device you want to initialize")
  52. initCmd.Flags().StringVar(&user, "user", "root", "Optional: The SSH user")
  53. initCmd.Flags().IntVar(&port, "port", 22, "Optional: SSH port")
  54. initCmd.Flags().StringVar(&privkey, "key", sshKeyPath, "Optional: Your SSH private key")
  55. initCmd.Flags().StringVar(&name, "name", "", "Required: The name to assign the device")
  56. }
  57. func initProcess(_ *cobra.Command, _ []string) {
  58. logFile, err := os.OpenFile(config.LogsPath+"init.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  59. if err != nil {
  60. log.Fatalf("error opening log file: %v", err)
  61. }
  62. defer logFile.Close()
  63. //if verbose {
  64. logWriter := io.MultiWriter(os.Stdout, logFile)
  65. log.SetOutput(logWriter)
  66. //} else {
  67. // log.SetOutput(logFile)
  68. //}
  69. // Generate SSH keys if they don't already exist
  70. if _, err := os.Stat(config.SshPrivKeyFile); os.IsNotExist(err) {
  71. log.Printf("Generating ssh private key '%s'...", config.SshPrivKeyFile)
  72. utils.GenerateSSHKeys(config.SshPrivKeyFile, config.SshPubKeyFile)
  73. log.Print("Done")
  74. }
  75. // Generate a password that is 50 characters long with 10 digits, 0 symbols,
  76. // allowing upper and lower case letters, allowing repeat characters.
  77. adminServiceSecret, err := password.Generate(50, 10, 0, false, true)
  78. if err != nil {
  79. log.Fatal(err)
  80. }
  81. log.Printf("Connecting to %s ...\n", host)
  82. setupRemoteService(adminServiceSecret)
  83. createIdentityCmd := fmt.Sprintf("gnunet-identity -C %s && gnunet-identity -d | grep %s", name, name)
  84. namestoreCmd := fmt.Sprintf("gnunet-namestore -z %s -t vpn -ap -e \"1 hour\" -n boxen -V \"6 $(gnunet-peerinfo -s -q) %s\"", name, adminServiceSecret)
  85. // It seems like doing an initial loiokup can help with DHT propagation,
  86. // but this is effectively a myth at this point, as I have not created
  87. // a test to verify this observation.
  88. gnsLookupCmd := fmt.Sprintf("gnunet-gns -u boxen.%s -t any", name)
  89. insertRecordCmd := namestoreCmd + "&&" + gnsLookupCmd
  90. if host == "" {
  91. log.Fatal("please set the --host option")
  92. }
  93. if name == "" {
  94. log.Fatal("please set the --name option")
  95. }
  96. sshApi, err := sshwrapper.DefaultSshApiSetup(host, port, user, privkey)
  97. if err != nil {
  98. log.Fatal(err)
  99. }
  100. var (
  101. stdout string
  102. stderr string
  103. )
  104. stdout, stderr, err = sshApi.Run(createIdentityCmd)
  105. if err != nil {
  106. log.Print(stdout)
  107. log.Print(stderr)
  108. log.Fatal(err)
  109. }
  110. s := stdout[strings.LastIndex(stdout, " ")+1:]
  111. deviceEgo := strings.TrimSpace(s)
  112. fmt.Printf(" The device is now named: '%s'\n\n Its administrative ego's PKEY is:\n %s\n\n Share with caution, or not at all.\n It can allow access to the administrative services on this device.\n", name, deviceEgo)
  113. stdout, stderr, err = sshApi.Run(insertRecordCmd)
  114. if err != nil {
  115. log.Print(stdout)
  116. log.Print(stderr)
  117. log.Fatal(err)
  118. }
  119. addZoneToLocalConfig(deviceEgo)
  120. db.InsertDevice(name, deviceEgo, "admin", fmt.Sprintf("boxen.%s", name), 1)
  121. log.Print(fmt.Sprintf("%s has returned:\n %s", name, stdout))
  122. }
  123. func addZoneToLocalConfig(deviceEgo string) {
  124. // TODO: allow to specify gnunet config path
  125. linkZone := exec.Command("gnunet-config", "--section=gns", fmt.Sprintf("--option=.%s", name), fmt.Sprintf("--value=%s", deviceEgo))
  126. err := linkZone.Run()
  127. log.Printf("Command finished with error: %v", err)
  128. }
  129. func setupRemoteService(serviceSecret string) {
  130. log.Printf("Setting up remote service...")
  131. // Copy over the gnunet.conf from the remote device.
  132. // TODO: Verify config path
  133. log.Printf("... SSH setup")
  134. sshApi, err := sshwrapper.DefaultSshApiSetup(host, port, user, privkey)
  135. if err != nil {
  136. log.Fatal(err)
  137. }
  138. log.Printf("... copy .config/gnunet.conf")
  139. err = sshApi.CopyFromRemote(".config/gnunet.conf", "/tmp/gnunet.conf")
  140. if err != nil {
  141. log.Fatal(err)
  142. }
  143. // Add the admin service to the Exit section of config
  144. log.Printf("... load /tmp/gnunet.conf")
  145. cfg, err := ini.LoadSources(ini.LoadOptions{
  146. IgnoreInlineComment: true,
  147. }, "/tmp/gnunet.conf")
  148. if err != nil {
  149. log.Panicf("Fail to read file: %v", err)
  150. }
  151. log.Printf("... update /tmp/gnunet.conf")
  152. serviceName := fmt.Sprintf("%s.gnunet.", serviceSecret)
  153. cfg.Section(serviceName).Key("TCP_REDIRECTS").SetValue("22:169.254.86.1:22")
  154. cfg.SaveTo("/tmp/gnunet.conf")
  155. log.Printf("... upload .config/gnunet.conf")
  156. err = sshApi.CopyToRemote("/tmp/gnunet.conf", ".config/gnunet.conf")
  157. if err != nil {
  158. log.Fatal(err)
  159. }
  160. // Restart GNUnet
  161. log.Printf("... restart gnunet")
  162. stdout, stderr, err := sshApi.Run("gnunet-arm -s ; gnunet-arm -r && sleep 20")
  163. if err != nil {
  164. log.Print(stdout)
  165. log.Print(stderr)
  166. log.Fatal(err)
  167. }
  168. log.Printf("...Done!")
  169. }