machines.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package main
  2. import (
  3. saferand "crypto/rand"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "math/big"
  8. "os"
  9. "strings"
  10. "time"
  11. "github.com/AlecAivazis/survey/v2"
  12. "github.com/crowdsecurity/crowdsec/pkg/csconfig"
  13. "github.com/crowdsecurity/crowdsec/pkg/database"
  14. "github.com/denisbrodbeck/machineid"
  15. "github.com/enescakir/emoji"
  16. "github.com/go-openapi/strfmt"
  17. "github.com/olekukonko/tablewriter"
  18. "github.com/pkg/errors"
  19. log "github.com/sirupsen/logrus"
  20. "github.com/spf13/cobra"
  21. "gopkg.in/yaml.v2"
  22. )
  23. var machineID string
  24. var machinePassword string
  25. var interactive bool
  26. var apiURL string
  27. var outputFile string
  28. var forceAdd bool
  29. var autoAdd bool
  30. var (
  31. passwordLength = 64
  32. upper = "ABCDEFGHIJKLMNOPQRSTUVWXY"
  33. lower = "abcdefghijklmnopqrstuvwxyz"
  34. digits = "0123456789"
  35. )
  36. const (
  37. uuid = "/proc/sys/kernel/random/uuid"
  38. )
  39. func generatePassword(length int) string {
  40. charset := upper + lower + digits
  41. charsetLength := len(charset)
  42. buf := make([]byte, length)
  43. for i := 0; i < length; i++ {
  44. rInt, err := saferand.Int(saferand.Reader, big.NewInt(int64(charsetLength)))
  45. if err != nil {
  46. log.Fatalf("failed getting data from prng for password generation : %s", err)
  47. }
  48. buf[i] = charset[rInt.Int64()]
  49. }
  50. return string(buf)
  51. }
  52. func generateID() (string, error) {
  53. id, err := machineid.ID()
  54. if err != nil {
  55. log.Debugf("failed to get machine-id with usual files : %s", err)
  56. }
  57. if id == "" || err != nil {
  58. bID, err := ioutil.ReadFile(uuid)
  59. if err != nil {
  60. return "", errors.Wrap(err, "generating machine id")
  61. }
  62. id = string(bID)
  63. }
  64. id = strings.ReplaceAll(id, "-", "")[:32]
  65. id = fmt.Sprintf("%s%s", id, generatePassword(16))
  66. return id, nil
  67. }
  68. func NewMachinesCmd() *cobra.Command {
  69. /* ---- DECISIONS COMMAND */
  70. var cmdMachines = &cobra.Command{
  71. Use: "machines [action]",
  72. Short: "Manage local API machines",
  73. Long: `
  74. Machines Management.
  75. To list/add/delete/register/validate machines
  76. `,
  77. Example: `cscli machines [action]`,
  78. }
  79. var cmdMachinesList = &cobra.Command{
  80. Use: "list",
  81. Short: "List machines",
  82. Long: `List `,
  83. Example: `cscli machines list`,
  84. Args: cobra.MaximumNArgs(1),
  85. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  86. var err error
  87. dbClient, err = database.NewClient(csConfig.DbConfig)
  88. if err != nil {
  89. log.Fatalf("unable to create new database client: %s", err)
  90. }
  91. },
  92. Run: func(cmd *cobra.Command, args []string) {
  93. machines, err := dbClient.ListMachines()
  94. if err != nil {
  95. log.Errorf("unable to list blockers: %s", err)
  96. }
  97. if csConfig.Cscli.Output == "human" {
  98. table := tablewriter.NewWriter(os.Stdout)
  99. table.SetCenterSeparator("")
  100. table.SetColumnSeparator("")
  101. table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
  102. table.SetAlignment(tablewriter.ALIGN_LEFT)
  103. table.SetHeader([]string{"Name", "IP Address", "Last Update", "Status", "Version"})
  104. for _, w := range machines {
  105. var validated string
  106. if w.IsValidated {
  107. validated = fmt.Sprintf("%s", emoji.CheckMark)
  108. } else {
  109. validated = fmt.Sprintf("%s", emoji.Prohibited)
  110. }
  111. table.Append([]string{w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version})
  112. }
  113. table.Render()
  114. } else if csConfig.Cscli.Output == "json" {
  115. x, err := json.MarshalIndent(machines, "", " ")
  116. if err != nil {
  117. log.Fatalf("failed to unmarshal")
  118. }
  119. fmt.Printf("%s", string(x))
  120. } else if csConfig.Cscli.Output == "raw" {
  121. for _, w := range machines {
  122. var validated string
  123. if w.IsValidated {
  124. validated = "true"
  125. } else {
  126. validated = "false"
  127. }
  128. fmt.Printf("%s,%s,%s,%s,%s\n", w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version)
  129. }
  130. } else {
  131. log.Errorf("unknown output '%s'", csConfig.Cscli.Output)
  132. }
  133. },
  134. }
  135. cmdMachines.AddCommand(cmdMachinesList)
  136. var cmdMachinesAdd = &cobra.Command{
  137. Use: "add",
  138. Short: "add machine to the database.",
  139. Long: `Register a new machine in the database. cscli should be on the same machine as LAPI.`,
  140. Example: `
  141. cscli machines add --auto
  142. cscli machines add MyTestMachine --auto
  143. cscli machines add MyTestMachine --password MyPassword
  144. `,
  145. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  146. var err error
  147. dbClient, err = database.NewClient(csConfig.DbConfig)
  148. if err != nil {
  149. log.Fatalf("unable to create new database client: %s", err)
  150. }
  151. },
  152. Run: func(cmd *cobra.Command, args []string) {
  153. var dumpFile string
  154. var err error
  155. // create machineID if doesn't specified by user
  156. if len(args) == 0 {
  157. if !autoAdd {
  158. err = cmd.Help()
  159. if err != nil {
  160. log.Fatalf("unable to print help(): %s", err)
  161. }
  162. return
  163. }
  164. machineID, err = generateID()
  165. if err != nil {
  166. log.Fatalf("unable to generate machine id : %s", err)
  167. }
  168. } else {
  169. machineID = args[0]
  170. }
  171. /*check if file already exists*/
  172. if outputFile != "" {
  173. dumpFile = outputFile
  174. } else if csConfig.API.Client.CredentialsFilePath != "" {
  175. dumpFile = csConfig.API.Client.CredentialsFilePath
  176. }
  177. // create password if doesn't specified by user
  178. if machinePassword == "" && !interactive {
  179. if !autoAdd {
  180. err = cmd.Help()
  181. if err != nil {
  182. log.Fatalf("unable to print help(): %s", err)
  183. }
  184. return
  185. }
  186. machinePassword = generatePassword(passwordLength)
  187. } else if machinePassword == "" && interactive {
  188. qs := &survey.Password{
  189. Message: "Please provide a password for the machine",
  190. }
  191. survey.AskOne(qs, &machinePassword)
  192. }
  193. password := strfmt.Password(machinePassword)
  194. _, err = dbClient.CreateMachine(&machineID, &password, "", true, forceAdd)
  195. if err != nil {
  196. log.Fatalf("unable to create machine: %s", err)
  197. }
  198. log.Infof("Machine '%s' created successfully", machineID)
  199. if apiURL == "" {
  200. if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
  201. apiURL = csConfig.API.Client.Credentials.URL
  202. } else if csConfig.API.Server != nil && csConfig.API.Server.ListenURI != "" {
  203. apiURL = "http://" + csConfig.API.Server.ListenURI
  204. } else {
  205. log.Fatalf("unable to dump an api URL. Please provide it in your configuration or with the -u parameter")
  206. }
  207. }
  208. apiCfg := csconfig.ApiCredentialsCfg{
  209. Login: machineID,
  210. Password: password.String(),
  211. URL: apiURL,
  212. }
  213. apiConfigDump, err := yaml.Marshal(apiCfg)
  214. if err != nil {
  215. log.Fatalf("unable to marshal api credentials: %s", err)
  216. }
  217. if dumpFile != "" {
  218. err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
  219. if err != nil {
  220. log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
  221. }
  222. log.Printf("API credentials dumped to '%s'", dumpFile)
  223. } else {
  224. fmt.Printf("%s\n", string(apiConfigDump))
  225. }
  226. },
  227. }
  228. cmdMachinesAdd.Flags().StringVarP(&machinePassword, "password", "p", "", "machine password to login to the API")
  229. cmdMachinesAdd.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
  230. cmdMachinesAdd.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the local API")
  231. cmdMachinesAdd.Flags().BoolVarP(&interactive, "interactive", "i", false, "interfactive mode to enter the password")
  232. cmdMachinesAdd.Flags().BoolVarP(&autoAdd, "auto", "a", false, "add the machine automatically (will generate also the username if not provided)")
  233. cmdMachinesAdd.Flags().BoolVar(&forceAdd, "force", false, "will force add the machine if it already exist")
  234. cmdMachines.AddCommand(cmdMachinesAdd)
  235. var cmdMachinesDelete = &cobra.Command{
  236. Use: "delete --machine MyTestMachine",
  237. Short: "delete machines",
  238. Example: `cscli machines delete <machine_name>`,
  239. Args: cobra.ExactArgs(1),
  240. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  241. var err error
  242. dbClient, err = database.NewClient(csConfig.DbConfig)
  243. if err != nil {
  244. log.Fatalf("unable to create new database client: %s", err)
  245. }
  246. },
  247. Run: func(cmd *cobra.Command, args []string) {
  248. machineID = args[0]
  249. err := dbClient.DeleteWatcher(machineID)
  250. if err != nil {
  251. log.Errorf("unable to delete machine: %s", err)
  252. return
  253. }
  254. log.Infof("machine '%s' deleted successfully", machineID)
  255. },
  256. }
  257. cmdMachinesDelete.Flags().StringVarP(&machineID, "machine", "m", "", "machine to delete")
  258. cmdMachines.AddCommand(cmdMachinesDelete)
  259. var cmdMachinesValidate = &cobra.Command{
  260. Use: "validate",
  261. Short: "validate a machine to access the local API",
  262. Long: `validate a machine to access the local API.`,
  263. Example: `cscli machines validate <machine_name>`,
  264. Args: cobra.ExactArgs(1),
  265. PersistentPreRun: func(cmd *cobra.Command, args []string) {
  266. var err error
  267. dbClient, err = database.NewClient(csConfig.DbConfig)
  268. if err != nil {
  269. log.Fatalf("unable to create new database client: %s", err)
  270. }
  271. },
  272. Run: func(cmd *cobra.Command, args []string) {
  273. machineID = args[0]
  274. if err := dbClient.ValidateMachine(machineID); err != nil {
  275. log.Fatalf("unable to validate machine '%s': %s", machineID, err)
  276. }
  277. log.Infof("machine '%s' validated successfuly", machineID)
  278. },
  279. }
  280. cmdMachines.AddCommand(cmdMachinesValidate)
  281. return cmdMachines
  282. }