simulation.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. log "github.com/sirupsen/logrus"
  6. "github.com/spf13/cobra"
  7. "golang.org/x/exp/slices"
  8. "gopkg.in/yaml.v2"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  10. )
  11. func addToExclusion(name string) error {
  12. csConfig.Cscli.SimulationConfig.Exclusions = append(csConfig.Cscli.SimulationConfig.Exclusions, name)
  13. return nil
  14. }
  15. func removeFromExclusion(name string) error {
  16. index := indexOf(name, csConfig.Cscli.SimulationConfig.Exclusions)
  17. // Remove element from the slice
  18. csConfig.Cscli.SimulationConfig.Exclusions[index] = csConfig.Cscli.SimulationConfig.Exclusions[len(csConfig.Cscli.SimulationConfig.Exclusions)-1]
  19. csConfig.Cscli.SimulationConfig.Exclusions[len(csConfig.Cscli.SimulationConfig.Exclusions)-1] = ""
  20. csConfig.Cscli.SimulationConfig.Exclusions = csConfig.Cscli.SimulationConfig.Exclusions[:len(csConfig.Cscli.SimulationConfig.Exclusions)-1]
  21. return nil
  22. }
  23. func enableGlobalSimulation() error {
  24. csConfig.Cscli.SimulationConfig.Simulation = new(bool)
  25. *csConfig.Cscli.SimulationConfig.Simulation = true
  26. csConfig.Cscli.SimulationConfig.Exclusions = []string{}
  27. if err := dumpSimulationFile(); err != nil {
  28. log.Fatalf("unable to dump simulation file: %s", err)
  29. }
  30. log.Printf("global simulation: enabled")
  31. return nil
  32. }
  33. func dumpSimulationFile() error {
  34. newConfigSim, err := yaml.Marshal(csConfig.Cscli.SimulationConfig)
  35. if err != nil {
  36. return fmt.Errorf("unable to marshal simulation configuration: %s", err)
  37. }
  38. err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
  39. if err != nil {
  40. return fmt.Errorf("write simulation config in '%s' failed: %s", csConfig.ConfigPaths.SimulationFilePath, err)
  41. }
  42. log.Debugf("updated simulation file %s", csConfig.ConfigPaths.SimulationFilePath)
  43. return nil
  44. }
  45. func disableGlobalSimulation() error {
  46. csConfig.Cscli.SimulationConfig.Simulation = new(bool)
  47. *csConfig.Cscli.SimulationConfig.Simulation = false
  48. csConfig.Cscli.SimulationConfig.Exclusions = []string{}
  49. newConfigSim, err := yaml.Marshal(csConfig.Cscli.SimulationConfig)
  50. if err != nil {
  51. return fmt.Errorf("unable to marshal new simulation configuration: %s", err)
  52. }
  53. err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
  54. if err != nil {
  55. return fmt.Errorf("unable to write new simulation config in '%s' : %s", csConfig.ConfigPaths.SimulationFilePath, err)
  56. }
  57. log.Printf("global simulation: disabled")
  58. return nil
  59. }
  60. func simulationStatus() error {
  61. if csConfig.Cscli.SimulationConfig == nil {
  62. log.Printf("global simulation: disabled (configuration file is missing)")
  63. return nil
  64. }
  65. if *csConfig.Cscli.SimulationConfig.Simulation {
  66. log.Println("global simulation: enabled")
  67. if len(csConfig.Cscli.SimulationConfig.Exclusions) > 0 {
  68. log.Println("Scenarios not in simulation mode :")
  69. for _, scenario := range csConfig.Cscli.SimulationConfig.Exclusions {
  70. log.Printf(" - %s", scenario)
  71. }
  72. }
  73. } else {
  74. log.Println("global simulation: disabled")
  75. if len(csConfig.Cscli.SimulationConfig.Exclusions) > 0 {
  76. log.Println("Scenarios in simulation mode :")
  77. for _, scenario := range csConfig.Cscli.SimulationConfig.Exclusions {
  78. log.Printf(" - %s", scenario)
  79. }
  80. }
  81. }
  82. return nil
  83. }
  84. func NewSimulationCmds() *cobra.Command {
  85. var cmdSimulation = &cobra.Command{
  86. Use: "simulation [command]",
  87. Short: "Manage simulation status of scenarios",
  88. Example: `cscli simulation status
  89. cscli simulation enable crowdsecurity/ssh-bf
  90. cscli simulation disable crowdsecurity/ssh-bf`,
  91. DisableAutoGenTag: true,
  92. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  93. if err := csConfig.LoadSimulation(); err != nil {
  94. log.Fatal(err)
  95. }
  96. if csConfig.Cscli == nil {
  97. return fmt.Errorf("you must configure cli before using simulation")
  98. }
  99. if csConfig.Cscli.SimulationConfig == nil {
  100. return fmt.Errorf("no simulation configured")
  101. }
  102. return nil
  103. },
  104. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  105. if cmd.Name() != "status" {
  106. log.Infof(ReloadMessage())
  107. }
  108. },
  109. }
  110. cmdSimulation.Flags().SortFlags = false
  111. cmdSimulation.PersistentFlags().SortFlags = false
  112. cmdSimulation.AddCommand(NewSimulationEnableCmd())
  113. cmdSimulation.AddCommand(NewSimulationDisableCmd())
  114. cmdSimulation.AddCommand(NewSimulationStatusCmd())
  115. return cmdSimulation
  116. }
  117. func NewSimulationEnableCmd() *cobra.Command {
  118. var forceGlobalSimulation bool
  119. var cmdSimulationEnable = &cobra.Command{
  120. Use: "enable [scenario] [-global]",
  121. Short: "Enable the simulation, globally or on specified scenarios",
  122. Example: `cscli simulation enable`,
  123. DisableAutoGenTag: true,
  124. Run: func(cmd *cobra.Command, args []string) {
  125. if err := csConfig.LoadHub(); err != nil {
  126. log.Fatal(err)
  127. }
  128. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  129. log.Info("Run 'sudo cscli hub update' to get the hub index")
  130. log.Fatalf("Failed to get Hub index : %v", err)
  131. }
  132. if len(args) > 0 {
  133. for _, scenario := range args {
  134. var item = cwhub.GetItem(cwhub.SCENARIOS, scenario)
  135. if item == nil {
  136. log.Errorf("'%s' doesn't exist or is not a scenario", scenario)
  137. continue
  138. }
  139. if !item.Installed {
  140. log.Warningf("'%s' isn't enabled", scenario)
  141. }
  142. isExcluded := slices.Contains(csConfig.Cscli.SimulationConfig.Exclusions, scenario)
  143. if *csConfig.Cscli.SimulationConfig.Simulation && !isExcluded {
  144. log.Warning("global simulation is already enabled")
  145. continue
  146. }
  147. if !*csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  148. log.Warningf("simulation for '%s' already enabled", scenario)
  149. continue
  150. }
  151. if *csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  152. if err := removeFromExclusion(scenario); err != nil {
  153. log.Fatal(err)
  154. }
  155. log.Printf("simulation enabled for '%s'", scenario)
  156. continue
  157. }
  158. if err := addToExclusion(scenario); err != nil {
  159. log.Fatal(err)
  160. }
  161. log.Printf("simulation mode for '%s' enabled", scenario)
  162. }
  163. if err := dumpSimulationFile(); err != nil {
  164. log.Fatalf("simulation enable: %s", err)
  165. }
  166. } else if forceGlobalSimulation {
  167. if err := enableGlobalSimulation(); err != nil {
  168. log.Fatalf("unable to enable global simulation mode : %s", err)
  169. }
  170. } else {
  171. printHelp(cmd)
  172. }
  173. },
  174. }
  175. cmdSimulationEnable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Enable global simulation (reverse mode)")
  176. return cmdSimulationEnable
  177. }
  178. func NewSimulationDisableCmd() *cobra.Command {
  179. var forceGlobalSimulation bool
  180. var cmdSimulationDisable = &cobra.Command{
  181. Use: "disable [scenario]",
  182. Short: "Disable the simulation mode. Disable only specified scenarios",
  183. Example: `cscli simulation disable`,
  184. DisableAutoGenTag: true,
  185. Run: func(cmd *cobra.Command, args []string) {
  186. if len(args) > 0 {
  187. for _, scenario := range args {
  188. isExcluded := slices.Contains(csConfig.Cscli.SimulationConfig.Exclusions, scenario)
  189. if !*csConfig.Cscli.SimulationConfig.Simulation && !isExcluded {
  190. log.Warningf("%s isn't in simulation mode", scenario)
  191. continue
  192. }
  193. if !*csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  194. if err := removeFromExclusion(scenario); err != nil {
  195. log.Fatal(err)
  196. }
  197. log.Printf("simulation mode for '%s' disabled", scenario)
  198. continue
  199. }
  200. if isExcluded {
  201. log.Warningf("simulation mode is enabled but is already disable for '%s'", scenario)
  202. continue
  203. }
  204. if err := addToExclusion(scenario); err != nil {
  205. log.Fatal(err)
  206. }
  207. log.Printf("simulation mode for '%s' disabled", scenario)
  208. }
  209. if err := dumpSimulationFile(); err != nil {
  210. log.Fatalf("simulation disable: %s", err)
  211. }
  212. } else if forceGlobalSimulation {
  213. if err := disableGlobalSimulation(); err != nil {
  214. log.Fatalf("unable to disable global simulation mode : %s", err)
  215. }
  216. } else {
  217. printHelp(cmd)
  218. }
  219. },
  220. }
  221. cmdSimulationDisable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Disable global simulation (reverse mode)")
  222. return cmdSimulationDisable
  223. }
  224. func NewSimulationStatusCmd() *cobra.Command {
  225. var cmdSimulationStatus = &cobra.Command{
  226. Use: "status",
  227. Short: "Show simulation mode status",
  228. Example: `cscli simulation status`,
  229. DisableAutoGenTag: true,
  230. Run: func(cmd *cobra.Command, args []string) {
  231. if err := simulationStatus(); err != nil {
  232. log.Fatal(err)
  233. }
  234. },
  235. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  236. },
  237. }
  238. return cmdSimulationStatus
  239. }