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.

198 lines
5.5 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. "strings"
  24. "boxen/config"
  25. "boxen/db"
  26. "boxen/utils"
  27. "github.com/eugenmayer/go-sshclient/sshwrapper"
  28. "github.com/sethvargo/go-password/password"
  29. "github.com/spf13/cobra"
  30. "gopkg.in/ini.v1"
  31. )
  32. var (
  33. host string
  34. user string
  35. port int
  36. name string
  37. privkey string
  38. sshKeyPath string = fmt.Sprintf("%sid_rsa_boxen", config.SshPath)
  39. )
  40. // initCmd represents the init command
  41. var initCmd = &cobra.Command{
  42. Use: "init",
  43. Short: "Initialize a new device",
  44. Long: `Initialize a new device.
  45. You will name it and authorize yourself as the owner.`,
  46. Run: initProcess,
  47. }
  48. func init() {
  49. RootCmd.AddCommand(initCmd)
  50. initCmd.Flags().StringVar(&host, "host", "", "Required: The hostname or IP of the device you want to initialize")
  51. initCmd.Flags().StringVar(&user, "user", "root", "Optional: The SSH user")
  52. initCmd.Flags().IntVar(&port, "port", 22, "Optional: SSH port")
  53. initCmd.Flags().StringVar(&privkey, "key", sshKeyPath, "Optional: Your SSH private key")
  54. initCmd.Flags().StringVar(&name, "name", "", "Required: The name to assign the device")
  55. }
  56. func initProcess(_ *cobra.Command, _ []string) {
  57. logFile, err := os.OpenFile(config.LogsPath+"init.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
  58. if err != nil {
  59. log.Fatalf("error opening log file: %v", err)
  60. }
  61. defer logFile.Close()
  62. log.SetOutput(logFile)
  63. // Generate SSH keys if they don't already exist
  64. if _, err := os.Stat(config.SshPrivKeyFile); os.IsNotExist(err) {
  65. utils.GenerateSSHKeys(config.SshPrivKeyFile, config.SshPubKeyFile)
  66. }
  67. // Generate a password that is 50 characters long with 10 digits, 0 symbols,
  68. // allowing upper and lower case letters, allowing repeat characters.
  69. adminServiceSecret, err := password.Generate(50, 10, 0, false, true)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. fmt.Printf("Connecting to %s ...\n", host)
  74. setupRemoteService(adminServiceSecret)
  75. createIdentityCmd := fmt.Sprintf("gnunet-identity -C %s && gnunet-identity -d | grep %s", name, name)
  76. namestoreCmd := fmt.Sprintf("gnunet-namestore -z %s -t vpn -ap -e \"1 hour\" -n boxen -V \"6 $(gnunet-peerinfo -s -q) %s\"", name, adminServiceSecret)
  77. // It seems like doing an initial loiokup can help with DHT propagation,
  78. // but this is effectively a myth at this point, as I have not created
  79. // a test to verify this observation.
  80. gnsLookupCmd := fmt.Sprintf("gnunet-gns -u boxen.%s -t any", name)
  81. insertRecordCmd := namestoreCmd + "&&" + gnsLookupCmd
  82. if host == "" {
  83. log.Fatal("please set the --host option")
  84. }
  85. if name == "" {
  86. log.Fatal("please set the --name option")
  87. }
  88. sshApi, err := sshwrapper.DefaultSshApiSetup(host, port, user, privkey)
  89. if err != nil {
  90. log.Fatal(err)
  91. }
  92. var (
  93. stdout string
  94. stderr string
  95. )
  96. stdout, stderr, err = sshApi.Run(createIdentityCmd)
  97. if err != nil {
  98. log.Print(stdout)
  99. log.Print(stderr)
  100. log.Fatal(err)
  101. }
  102. s := stdout[strings.LastIndex(stdout, " ")+1:]
  103. deviceEgo := strings.TrimSpace(s)
  104. 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)
  105. stdout, stderr, err = sshApi.Run(insertRecordCmd)
  106. if err != nil {
  107. log.Print(stdout)
  108. log.Print(stderr)
  109. log.Fatal(err)
  110. }
  111. addZoneToLocalConfig(deviceEgo)
  112. db.InsertDevice(name, deviceEgo, "admin", fmt.Sprintf("boxen.%s", name), 1)
  113. log.Print(fmt.Sprintf("%s has returned:\n %s", name, stdout))
  114. }
  115. func addZoneToLocalConfig(deviceEgo string) {
  116. // TODO: allow to specify gnunet config path
  117. linkZone := exec.Command("gnunet-config", "--section=gns", fmt.Sprintf("--option=.%s", name), fmt.Sprintf("--value=%s", deviceEgo))
  118. err := linkZone.Run()
  119. log.Printf("Command finished with error: %v", err)
  120. }
  121. func setupRemoteService(serviceSecret string) {
  122. // Copy over the gnunet.conf from the remote device.
  123. // TODO: Verify config path
  124. sshApi, err := sshwrapper.DefaultSshApiSetup(host, port, user, privkey)
  125. if err != nil {
  126. log.Fatal(err)
  127. }
  128. err = sshApi.CopyFromRemote(".config/gnunet.conf", "/tmp/gnunet.conf")
  129. if err != nil {
  130. log.Fatal(err)
  131. }
  132. // Add the admin service to the Exit section of config
  133. cfg, err := ini.LoadSources(ini.LoadOptions{
  134. IgnoreInlineComment: true,
  135. }, "/tmp/gnunet.conf")
  136. if err != nil {
  137. fmt.Printf("Fail to read file: %v", err)
  138. os.Exit(1)
  139. }
  140. serviceName := fmt.Sprintf("%s.gnunet.", serviceSecret)
  141. cfg.Section(serviceName).Key("TCP_REDIRECTS").SetValue("22:169.254.86.1:22")
  142. cfg.SaveTo("/tmp/gnunet.conf")
  143. err = sshApi.CopyToRemote("/tmp/gnunet.conf", ".config/gnunet.conf")
  144. if err != nil {
  145. log.Fatal(err)
  146. }
  147. // Restart GNUnet
  148. stdout, stderr, err := sshApi.Run("gnunet-arm -s; gnunet-arm -r; sleep 20")
  149. if err != nil {
  150. log.Print(stdout)
  151. log.Print(stderr)
  152. log.Fatal(err)
  153. }
  154. }