simulation.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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.Fatalf(err.Error())
  120. }
  121. if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
  122. log.Fatalf("Failed to get Hub index : %v", err)
  123. log.Infoln("Run 'sudo cscli hub update' to get the hub index")
  124. }
  125. if len(args) > 0 {
  126. for _, scenario := range args {
  127. var (
  128. item *cwhub.Item
  129. )
  130. item = cwhub.GetItem(cwhub.SCENARIOS, scenario)
  131. if item == nil {
  132. log.Errorf("'%s' doesn't exist or is not a scenario", scenario)
  133. continue
  134. }
  135. if !item.Installed {
  136. log.Warningf("'%s' isn't enabled", scenario)
  137. }
  138. isExcluded := inSlice(scenario, csConfig.Cscli.SimulationConfig.Exclusions)
  139. if *csConfig.Cscli.SimulationConfig.Simulation && !isExcluded {
  140. log.Warningf("global simulation is already enabled")
  141. continue
  142. }
  143. if !*csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  144. log.Warningf("simulation for '%s' already enabled", scenario)
  145. continue
  146. }
  147. if *csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  148. if err := removeFromExclusion(scenario); err != nil {
  149. log.Fatalf(err.Error())
  150. }
  151. log.Printf("simulation enabled for '%s'", scenario)
  152. continue
  153. }
  154. if err := addToExclusion(scenario); err != nil {
  155. log.Fatalf(err.Error())
  156. }
  157. log.Printf("simulation mode for '%s' enabled", scenario)
  158. }
  159. if err := dumpSimulationFile(); err != nil {
  160. log.Fatalf("simulation enable: %s", err.Error())
  161. }
  162. } else if forceGlobalSimulation {
  163. if err := enableGlobalSimulation(); err != nil {
  164. log.Fatalf("unable to enable global simulation mode : %s", err.Error())
  165. }
  166. } else {
  167. cmd.Help()
  168. }
  169. },
  170. }
  171. cmdSimulationEnable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Enable global simulation (reverse mode)")
  172. cmdSimulation.AddCommand(cmdSimulationEnable)
  173. var cmdSimulationDisable = &cobra.Command{
  174. Use: "disable [scenario]",
  175. Short: "Disable the simulation mode. Disable only specified scenarios",
  176. Example: `cscli simulation disable`,
  177. DisableAutoGenTag: true,
  178. Run: func(cmd *cobra.Command, args []string) {
  179. if len(args) > 0 {
  180. for _, scenario := range args {
  181. isExcluded := inSlice(scenario, csConfig.Cscli.SimulationConfig.Exclusions)
  182. if !*csConfig.Cscli.SimulationConfig.Simulation && !isExcluded {
  183. log.Warningf("%s isn't in simulation mode", scenario)
  184. continue
  185. }
  186. if !*csConfig.Cscli.SimulationConfig.Simulation && isExcluded {
  187. if err := removeFromExclusion(scenario); err != nil {
  188. log.Fatalf(err.Error())
  189. }
  190. log.Printf("simulation mode for '%s' disabled", scenario)
  191. continue
  192. }
  193. if isExcluded {
  194. log.Warningf("simulation mode is enabled but is already disable for '%s'", scenario)
  195. continue
  196. }
  197. if err := addToExclusion(scenario); err != nil {
  198. log.Fatalf(err.Error())
  199. }
  200. log.Printf("simulation mode for '%s' disabled", scenario)
  201. }
  202. if err := dumpSimulationFile(); err != nil {
  203. log.Fatalf("simulation disable: %s", err.Error())
  204. }
  205. } else if forceGlobalSimulation {
  206. if err := disableGlobalSimulation(); err != nil {
  207. log.Fatalf("unable to disable global simulation mode : %s", err.Error())
  208. }
  209. } else {
  210. cmd.Help()
  211. }
  212. },
  213. }
  214. cmdSimulationDisable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Disable global simulation (reverse mode)")
  215. cmdSimulation.AddCommand(cmdSimulationDisable)
  216. var cmdSimulationStatus = &cobra.Command{
  217. Use: "status",
  218. Short: "Show simulation mode status",
  219. Example: `cscli simulation status`,
  220. DisableAutoGenTag: true,
  221. Run: func(cmd *cobra.Command, args []string) {
  222. if err := simulationStatus(); err != nil {
  223. log.Fatalf(err.Error())
  224. }
  225. },
  226. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  227. },
  228. }
  229. cmdSimulation.AddCommand(cmdSimulationStatus)
  230. return cmdSimulation
  231. }