simulation.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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.Crowdsec.SimulationConfig.Exclusions = append(csConfig.Crowdsec.SimulationConfig.Exclusions, name)
  12. return nil
  13. }
  14. func removeFromExclusion(name string) error {
  15. index := indexOf(name, csConfig.Crowdsec.SimulationConfig.Exclusions)
  16. // Remove element from the slice
  17. csConfig.Crowdsec.SimulationConfig.Exclusions[index] = csConfig.Crowdsec.SimulationConfig.Exclusions[len(csConfig.Crowdsec.SimulationConfig.Exclusions)-1]
  18. csConfig.Crowdsec.SimulationConfig.Exclusions[len(csConfig.Crowdsec.SimulationConfig.Exclusions)-1] = ""
  19. csConfig.Crowdsec.SimulationConfig.Exclusions = csConfig.Crowdsec.SimulationConfig.Exclusions[:len(csConfig.Crowdsec.SimulationConfig.Exclusions)-1]
  20. return nil
  21. }
  22. func enableGlobalSimulation() error {
  23. csConfig.Crowdsec.SimulationConfig.Simulation = new(bool)
  24. *csConfig.Crowdsec.SimulationConfig.Simulation = true
  25. csConfig.Crowdsec.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.Crowdsec.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.Crowdsec.SimulationConfig.Simulation = new(bool)
  46. *csConfig.Crowdsec.SimulationConfig.Simulation = false
  47. csConfig.Crowdsec.SimulationConfig.Exclusions = []string{}
  48. newConfigSim, err := yaml.Marshal(csConfig.Crowdsec.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.Crowdsec.SimulationConfig == nil {
  61. log.Printf("global simulation: disabled (configuration file is missing)")
  62. return nil
  63. }
  64. if *csConfig.Crowdsec.SimulationConfig.Simulation {
  65. log.Println("global simulation: enabled")
  66. if len(csConfig.Crowdsec.SimulationConfig.Exclusions) > 0 {
  67. log.Println("Scenarios not in simulation mode :")
  68. for _, scenario := range csConfig.Crowdsec.SimulationConfig.Exclusions {
  69. log.Printf(" - %s", scenario)
  70. }
  71. }
  72. } else {
  73. log.Println("global simulation: disabled")
  74. if len(csConfig.Crowdsec.SimulationConfig.Exclusions) > 0 {
  75. log.Println("Scenarios in simulation mode :")
  76. for _, scenario := range csConfig.Crowdsec.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. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  91. if csConfig.Cscli == nil {
  92. return fmt.Errorf("you must configure cli before using simulation")
  93. }
  94. return nil
  95. },
  96. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  97. if cmd.Name() != "status" {
  98. log.Infof("Run 'systemctl reload crowdsec' for the new configuration to be effective.")
  99. }
  100. },
  101. }
  102. cmdSimulation.Flags().SortFlags = false
  103. cmdSimulation.PersistentFlags().SortFlags = false
  104. var forceGlobalSimulation bool
  105. var cmdSimulationEnable = &cobra.Command{
  106. Use: "enable [scenario] [-global]",
  107. Short: "Enable the simulation, globally or on specified scenarios",
  108. Example: `cscli simulation enable`,
  109. Run: func(cmd *cobra.Command, args []string) {
  110. if err := cwhub.GetHubIdx(csConfig.Cscli); err != nil {
  111. log.Fatalf("failed to get Hub index : %v", err)
  112. }
  113. if len(args) > 0 {
  114. for _, scenario := range args {
  115. var (
  116. item *cwhub.Item
  117. )
  118. item = cwhub.GetItem(cwhub.SCENARIOS, scenario)
  119. if item == nil {
  120. log.Errorf("'%s' doesn't exist or is not a scenario", scenario)
  121. continue
  122. }
  123. if !item.Installed {
  124. log.Warningf("'%s' isn't enabled", scenario)
  125. }
  126. isExcluded := inSlice(scenario, csConfig.Crowdsec.SimulationConfig.Exclusions)
  127. if *csConfig.Crowdsec.SimulationConfig.Simulation && !isExcluded {
  128. log.Warningf("global simulation is already enabled")
  129. continue
  130. }
  131. if !*csConfig.Crowdsec.SimulationConfig.Simulation && isExcluded {
  132. log.Warningf("simulation for '%s' already enabled", scenario)
  133. continue
  134. }
  135. if *csConfig.Crowdsec.SimulationConfig.Simulation && isExcluded {
  136. if err := removeFromExclusion(scenario); err != nil {
  137. log.Fatalf(err.Error())
  138. }
  139. log.Printf("simulation enabled for '%s'", scenario)
  140. continue
  141. }
  142. if err := addToExclusion(scenario); err != nil {
  143. log.Fatalf(err.Error())
  144. }
  145. log.Printf("simulation mode for '%s' enabled", scenario)
  146. }
  147. if err := dumpSimulationFile(); err != nil {
  148. log.Fatalf("simulation enable: %s", err.Error())
  149. }
  150. } else if forceGlobalSimulation {
  151. if err := enableGlobalSimulation(); err != nil {
  152. log.Fatalf("unable to enable global simulation mode : %s", err.Error())
  153. }
  154. } else {
  155. cmd.Help()
  156. }
  157. },
  158. }
  159. cmdSimulationEnable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Enable global simulation (reverse mode)")
  160. cmdSimulation.AddCommand(cmdSimulationEnable)
  161. var cmdSimulationDisable = &cobra.Command{
  162. Use: "disable [scenario]",
  163. Short: "Disable the simulation mode. Disable only specified scenarios",
  164. Example: `cscli simulation disable`,
  165. Run: func(cmd *cobra.Command, args []string) {
  166. if len(args) > 0 {
  167. for _, scenario := range args {
  168. isExcluded := inSlice(scenario, csConfig.Crowdsec.SimulationConfig.Exclusions)
  169. if !*csConfig.Crowdsec.SimulationConfig.Simulation && !isExcluded {
  170. log.Warningf("%s isn't in simulation mode", scenario)
  171. continue
  172. }
  173. if !*csConfig.Crowdsec.SimulationConfig.Simulation && isExcluded {
  174. if err := removeFromExclusion(scenario); err != nil {
  175. log.Fatalf(err.Error())
  176. }
  177. log.Printf("simulation mode for '%s' disabled", scenario)
  178. continue
  179. }
  180. if isExcluded {
  181. log.Warningf("simulation mode is enabled but is already disable for '%s'", scenario)
  182. continue
  183. }
  184. if err := addToExclusion(scenario); err != nil {
  185. log.Fatalf(err.Error())
  186. }
  187. log.Printf("simulation mode for '%s' disabled", scenario)
  188. }
  189. if err := dumpSimulationFile(); err != nil {
  190. log.Fatalf("simulation disable: %s", err.Error())
  191. }
  192. } else if forceGlobalSimulation {
  193. if err := disableGlobalSimulation(); err != nil {
  194. log.Fatalf("unable to disable global simulation mode : %s", err.Error())
  195. }
  196. } else {
  197. cmd.Help()
  198. }
  199. },
  200. }
  201. cmdSimulationDisable.Flags().BoolVarP(&forceGlobalSimulation, "global", "g", false, "Disable global simulation (reverse mode)")
  202. cmdSimulation.AddCommand(cmdSimulationDisable)
  203. var cmdSimulationStatus = &cobra.Command{
  204. Use: "status",
  205. Short: "Show simulation mode status",
  206. Example: `cscli simulation status`,
  207. Run: func(cmd *cobra.Command, args []string) {
  208. if err := simulationStatus(); err != nil {
  209. log.Fatalf(err.Error())
  210. }
  211. },
  212. PersistentPostRun: func(cmd *cobra.Command, args []string) {
  213. },
  214. }
  215. cmdSimulation.AddCommand(cmdSimulationStatus)
  216. return cmdSimulation
  217. }