config_backup.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. log "github.com/sirupsen/logrus"
  8. "github.com/spf13/cobra"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  10. "github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
  11. )
  12. func backupHub(dirPath string) error {
  13. var err error
  14. var itemDirectory string
  15. var upstreamParsers []string
  16. for _, itemType := range cwhub.ItemTypes {
  17. clog := log.WithFields(log.Fields{
  18. "type": itemType,
  19. })
  20. itemMap := cwhub.GetItemMap(itemType)
  21. if itemMap == nil {
  22. clog.Infof("No %s to backup.", itemType)
  23. continue
  24. }
  25. itemDirectory = fmt.Sprintf("%s/%s/", dirPath, itemType)
  26. if err := os.MkdirAll(itemDirectory, os.ModePerm); err != nil {
  27. return fmt.Errorf("error while creating %s : %s", itemDirectory, err)
  28. }
  29. upstreamParsers = []string{}
  30. for k, v := range itemMap {
  31. clog = clog.WithFields(log.Fields{
  32. "file": v.Name,
  33. })
  34. if !v.Installed { //only backup installed ones
  35. clog.Debugf("[%s] : not installed", k)
  36. continue
  37. }
  38. //for the local/tainted ones, we back up the full file
  39. if v.Tainted || v.Local || !v.UpToDate {
  40. //we need to back up stages for parsers
  41. if itemType == cwhub.PARSERS || itemType == cwhub.PARSERS_OVFLW {
  42. fstagedir := fmt.Sprintf("%s%s", itemDirectory, v.Stage)
  43. if err := os.MkdirAll(fstagedir, os.ModePerm); err != nil {
  44. return fmt.Errorf("error while creating stage dir %s : %s", fstagedir, err)
  45. }
  46. }
  47. clog.Debugf("[%s] : backuping file (tainted:%t local:%t up-to-date:%t)", k, v.Tainted, v.Local, v.UpToDate)
  48. tfile := fmt.Sprintf("%s%s/%s", itemDirectory, v.Stage, v.FileName)
  49. if err = CopyFile(v.LocalPath, tfile); err != nil {
  50. return fmt.Errorf("failed copy %s %s to %s : %s", itemType, v.LocalPath, tfile, err)
  51. }
  52. clog.Infof("local/tainted saved %s to %s", v.LocalPath, tfile)
  53. continue
  54. }
  55. clog.Debugf("[%s] : from hub, just backup name (up-to-date:%t)", k, v.UpToDate)
  56. clog.Infof("saving, version:%s, up-to-date:%t", v.Version, v.UpToDate)
  57. upstreamParsers = append(upstreamParsers, v.Name)
  58. }
  59. //write the upstream items
  60. upstreamParsersFname := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itemType)
  61. upstreamParsersContent, err := json.MarshalIndent(upstreamParsers, "", " ")
  62. if err != nil {
  63. return fmt.Errorf("failed marshaling upstream parsers : %s", err)
  64. }
  65. err = os.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
  66. if err != nil {
  67. return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
  68. }
  69. clog.Infof("Wrote %d entries for %s to %s", len(upstreamParsers), itemType, upstreamParsersFname)
  70. }
  71. return nil
  72. }
  73. /*
  74. Backup crowdsec configurations to directory <dirPath>:
  75. - Main config (config.yaml)
  76. - Profiles config (profiles.yaml)
  77. - Simulation config (simulation.yaml)
  78. - Backup of API credentials (local API and online API)
  79. - List of scenarios, parsers, postoverflows and collections that are up-to-date
  80. - Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
  81. - Acquisition files (acquis.yaml, acquis.d/*.yaml)
  82. */
  83. func backupConfigToDirectory(dirPath string) error {
  84. var err error
  85. if dirPath == "" {
  86. return fmt.Errorf("directory path can't be empty")
  87. }
  88. log.Infof("Starting configuration backup")
  89. /*if parent directory doesn't exist, bail out. create final dir with Mkdir*/
  90. parentDir := filepath.Dir(dirPath)
  91. if _, err := os.Stat(parentDir); err != nil {
  92. return fmt.Errorf("while checking parent directory %s existence: %w", parentDir, err)
  93. }
  94. if err = os.Mkdir(dirPath, 0o700); err != nil {
  95. return fmt.Errorf("while creating %s: %w", dirPath, err)
  96. }
  97. if csConfig.ConfigPaths.SimulationFilePath != "" {
  98. backupSimulation := filepath.Join(dirPath, "simulation.yaml")
  99. if err = CopyFile(csConfig.ConfigPaths.SimulationFilePath, backupSimulation); err != nil {
  100. return fmt.Errorf("failed copy %s to %s: %w", csConfig.ConfigPaths.SimulationFilePath, backupSimulation, err)
  101. }
  102. log.Infof("Saved simulation to %s", backupSimulation)
  103. }
  104. /*
  105. - backup AcquisitionFilePath
  106. - backup the other files of acquisition directory
  107. */
  108. if csConfig.Crowdsec != nil && csConfig.Crowdsec.AcquisitionFilePath != "" {
  109. backupAcquisition := filepath.Join(dirPath, "acquis.yaml")
  110. if err = CopyFile(csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition); err != nil {
  111. return fmt.Errorf("failed copy %s to %s: %s", csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition, err)
  112. }
  113. }
  114. acquisBackupDir := filepath.Join(dirPath, "acquis")
  115. if err = os.Mkdir(acquisBackupDir, 0o700); err != nil {
  116. return fmt.Errorf("error while creating %s: %s", acquisBackupDir, err)
  117. }
  118. if csConfig.Crowdsec != nil && len(csConfig.Crowdsec.AcquisitionFiles) > 0 {
  119. for _, acquisFile := range csConfig.Crowdsec.AcquisitionFiles {
  120. /*if it was the default one, it was already backup'ed*/
  121. if csConfig.Crowdsec.AcquisitionFilePath == acquisFile {
  122. continue
  123. }
  124. targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
  125. if err != nil {
  126. return fmt.Errorf("while saving %s to %s: %w", acquisFile, acquisBackupDir, err)
  127. }
  128. if err = CopyFile(acquisFile, targetFname); err != nil {
  129. return fmt.Errorf("failed copy %s to %s: %w", acquisFile, targetFname, err)
  130. }
  131. log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
  132. }
  133. }
  134. if ConfigFilePath != "" {
  135. backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
  136. if err = CopyFile(ConfigFilePath, backupMain); err != nil {
  137. return fmt.Errorf("failed copy %s to %s: %s", ConfigFilePath, backupMain, err)
  138. }
  139. log.Infof("Saved default yaml to %s", backupMain)
  140. }
  141. if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
  142. backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
  143. if err = CopyFile(csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds); err != nil {
  144. return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds, err)
  145. }
  146. log.Infof("Saved online API credentials to %s", backupCAPICreds)
  147. }
  148. if csConfig.API != nil && csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
  149. backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
  150. if err = CopyFile(csConfig.API.Client.CredentialsFilePath, backupLAPICreds); err != nil {
  151. return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Client.CredentialsFilePath, backupLAPICreds, err)
  152. }
  153. log.Infof("Saved local API credentials to %s", backupLAPICreds)
  154. }
  155. if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.ProfilesPath != "" {
  156. backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
  157. if err = CopyFile(csConfig.API.Server.ProfilesPath, backupProfiles); err != nil {
  158. return fmt.Errorf("failed copy %s to %s: %s", csConfig.API.Server.ProfilesPath, backupProfiles, err)
  159. }
  160. log.Infof("Saved profiles to %s", backupProfiles)
  161. }
  162. if err = backupHub(dirPath); err != nil {
  163. return fmt.Errorf("failed to backup hub config: %s", err)
  164. }
  165. return nil
  166. }
  167. func runConfigBackup(cmd *cobra.Command, args []string) error {
  168. if err := require.Hub(csConfig); err != nil {
  169. return err
  170. }
  171. if err := backupConfigToDirectory(args[0]); err != nil {
  172. return fmt.Errorf("failed to backup config: %w", err)
  173. }
  174. return nil
  175. }
  176. func NewConfigBackupCmd() *cobra.Command {
  177. cmdConfigBackup := &cobra.Command{
  178. Use: `backup "directory"`,
  179. Short: "Backup current config",
  180. Long: `Backup the current crowdsec configuration including :
  181. - Main config (config.yaml)
  182. - Simulation config (simulation.yaml)
  183. - Profiles config (profiles.yaml)
  184. - List of scenarios, parsers, postoverflows and collections that are up-to-date
  185. - Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
  186. - Backup of API credentials (local API and online API)`,
  187. Example: `cscli config backup ./my-backup`,
  188. Args: cobra.ExactArgs(1),
  189. DisableAutoGenTag: true,
  190. RunE: runConfigBackup,
  191. }
  192. return cmdConfigBackup
  193. }