simulation.go 8.2 KB

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