api.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "math/rand"
  6. "path"
  7. "strings"
  8. "time"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwhub"
  10. "github.com/crowdsecurity/crowdsec/pkg/outputs"
  11. "github.com/crowdsecurity/crowdsec/pkg/sqlite"
  12. "github.com/crowdsecurity/crowdsec/pkg/types"
  13. "github.com/denisbrodbeck/machineid"
  14. log "github.com/sirupsen/logrus"
  15. "github.com/spf13/cobra"
  16. "gopkg.in/yaml.v2"
  17. )
  18. var (
  19. passwordLength = 64
  20. upper = "ABCDEFGHIJKLMNOPQRSTUVWXY"
  21. lower = "abcdefghijklmnopqrstuvwxyz"
  22. digits = "0123456789"
  23. )
  24. var (
  25. apiConfigFile = "api.yaml"
  26. )
  27. var userID string // for flag parsing
  28. var dbctx *sqlite.Context
  29. var outputCTX *outputs.Output
  30. func dumpCredentials() error {
  31. if config.output == "json" {
  32. credsYaml, err := json.Marshal(&outputCTX.API.Creds)
  33. if err != nil {
  34. log.Fatalf("Can't marshal credentials : %v", err)
  35. }
  36. fmt.Printf("%s\n", string(credsYaml))
  37. } else {
  38. credsYaml, err := yaml.Marshal(&outputCTX.API.Creds)
  39. if err != nil {
  40. log.Fatalf("Can't marshal credentials : %v", err)
  41. }
  42. fmt.Printf("%s\n", string(credsYaml))
  43. }
  44. return nil
  45. }
  46. func generatePassword() string {
  47. rand.Seed(time.Now().UnixNano())
  48. charset := upper + lower + digits
  49. buf := make([]byte, passwordLength)
  50. buf[0] = digits[rand.Intn(len(digits))]
  51. buf[1] = upper[rand.Intn(len(upper))]
  52. buf[2] = lower[rand.Intn(len(lower))]
  53. for i := 3; i < passwordLength; i++ {
  54. buf[i] = charset[rand.Intn(len(charset))]
  55. }
  56. rand.Shuffle(len(buf), func(i, j int) {
  57. buf[i], buf[j] = buf[j], buf[i]
  58. })
  59. return string(buf)
  60. }
  61. func pullTOP() error {
  62. /*profile from cwhub*/
  63. var profiles []string
  64. if _, ok := cwhub.HubIdx[cwhub.SCENARIOS]; !ok || len(cwhub.HubIdx[cwhub.SCENARIOS]) == 0 {
  65. log.Errorf("no loaded scenarios, can't fill profiles")
  66. return fmt.Errorf("no profiles")
  67. }
  68. for _, item := range cwhub.HubIdx[cwhub.SCENARIOS] {
  69. if item.Tainted || !item.Installed {
  70. continue
  71. }
  72. profiles = append(profiles, item.Name)
  73. }
  74. outputCTX.API.Creds.Profile = strings.Join(profiles[:], ",")
  75. if err := outputCTX.API.Signin(); err != nil {
  76. log.Fatalf(err.Error())
  77. }
  78. ret, err := outputCTX.API.PullTop()
  79. if err != nil {
  80. log.Fatalf(err.Error())
  81. }
  82. log.Warningf("api pull returned %d entries", len(ret))
  83. for _, item := range ret {
  84. if _, ok := item["range_ip"]; !ok {
  85. continue
  86. }
  87. if _, ok := item["scenario"]; !ok {
  88. continue
  89. }
  90. item["scenario"] = fmt.Sprintf("api: %s", item["scenario"])
  91. if _, ok := item["action"]; !ok {
  92. continue
  93. }
  94. if _, ok := item["expiration"]; !ok {
  95. continue
  96. }
  97. if _, ok := item["country"]; !ok {
  98. item["country"] = ""
  99. }
  100. if _, ok := item["as_org"]; !ok {
  101. item["as_org"] = ""
  102. }
  103. if _, ok := item["as_num"]; !ok {
  104. item["as_num"] = ""
  105. }
  106. var signalOcc types.SignalOccurence
  107. signalOcc, err = simpleBanToSignal(item["range_ip"], item["scenario"], item["expiration"], item["action"], item["as_name"], item["as_num"], item["country"], "api")
  108. if err := outputCTX.Insert(signalOcc); err != nil {
  109. log.Fatalf("Unable to write pull to sqliteDB : %+s", err.Error())
  110. }
  111. }
  112. outputCTX.Flush()
  113. log.Infof("Wrote %d bans from api to database.", len(ret))
  114. return nil
  115. }
  116. func NewAPICmd() *cobra.Command {
  117. var cmdAPI = &cobra.Command{
  118. Use: "api [action]",
  119. Short: "Crowdsec API interaction",
  120. Long: `
  121. Allow to register your machine into crowdsec API to send and receive signal.
  122. `,
  123. Example: `
  124. cscli api register # Register to Crowdsec API
  125. cscli api pull # Pull malevolant IPs from Crowdsec API
  126. cscli api reset # Reset your machines credentials
  127. cscli api enroll # Enroll your machine to the user account you created on Crowdsec backend
  128. cscli api credentials # Display your API credentials
  129. `,
  130. Args: cobra.MinimumNArgs(1),
  131. PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
  132. var err error
  133. if !config.configured {
  134. return fmt.Errorf("you must configure cli before interacting with hub")
  135. }
  136. outputConfig := outputs.OutputFactory{
  137. BackendFolder: config.BackendPluginFolder,
  138. }
  139. outputCTX, err = outputs.NewOutput(&outputConfig, false)
  140. if err != nil {
  141. return err
  142. }
  143. err = outputCTX.LoadAPIConfig(path.Join(config.InstallFolder, apiConfigFile))
  144. if err != nil {
  145. return err
  146. }
  147. return nil
  148. },
  149. }
  150. var cmdAPIRegister = &cobra.Command{
  151. Use: "register",
  152. Short: "Register on Crowdsec API",
  153. Long: `This command will register your machine to crowdsec API to allow you to receive list of malveolent IPs.
  154. The printed machine_id and password should be added to your api.yaml file.`,
  155. Example: `cscli api register`,
  156. Args: cobra.MinimumNArgs(0),
  157. Run: func(cmd *cobra.Command, args []string) {
  158. id, err := machineid.ID()
  159. if err != nil {
  160. log.Fatalf("failed to get machine id: %s", err)
  161. }
  162. password := generatePassword()
  163. if err := outputCTX.API.RegisterMachine(id, password); err != nil {
  164. log.Fatalf(err.Error())
  165. }
  166. fmt.Printf("machine_id: %s\n", outputCTX.API.Creds.User)
  167. fmt.Printf("password: %s\n", outputCTX.API.Creds.Password)
  168. return
  169. },
  170. }
  171. var cmdAPIEnroll = &cobra.Command{
  172. Use: "enroll",
  173. Short: "Associate your machine to an existing crowdsec user",
  174. Long: `Enrolling your machine into your user account will allow for more accurate lists and threat detection. See website to create user account.`,
  175. Example: `cscli api enroll -u 1234567890ffff`,
  176. Args: cobra.MinimumNArgs(0),
  177. Run: func(cmd *cobra.Command, args []string) {
  178. if err := outputCTX.API.Signin(); err != nil {
  179. log.Fatalf("unable to signin : %s", err)
  180. }
  181. if err := outputCTX.API.Enroll(userID); err != nil {
  182. log.Fatalf(err.Error())
  183. }
  184. return
  185. },
  186. }
  187. var cmdAPIResetPassword = &cobra.Command{
  188. Use: "reset",
  189. Short: "Reset password on CrowdSec API",
  190. Long: `Attempts to reset your credentials to the API.`,
  191. Example: `cscli api reset`,
  192. Args: cobra.MinimumNArgs(0),
  193. Run: func(cmd *cobra.Command, args []string) {
  194. id, err := machineid.ID()
  195. if err != nil {
  196. log.Fatalf("failed to get machine id: %s", err)
  197. }
  198. password := generatePassword()
  199. if err := outputCTX.API.ResetPassword(id, password); err != nil {
  200. log.Fatalf(err.Error())
  201. }
  202. fmt.Printf("machine_id: %s\n", outputCTX.API.Creds.User)
  203. fmt.Printf("password: %s\n", outputCTX.API.Creds.Password)
  204. return
  205. },
  206. }
  207. var cmdAPIPull = &cobra.Command{
  208. Use: "pull",
  209. Short: "Pull crowdsec API TopX",
  210. Long: `Pulls a list of malveolent IPs relevant to your situation and add them into the local ban database.`,
  211. Example: `cscli api pull`,
  212. Args: cobra.MinimumNArgs(0),
  213. Run: func(cmd *cobra.Command, args []string) {
  214. if err := cwhub.GetHubIdx(); err != nil {
  215. log.Fatalf(err.Error())
  216. }
  217. err := pullTOP()
  218. if err != nil {
  219. log.Fatalf(err.Error())
  220. }
  221. return
  222. },
  223. }
  224. var cmdAPICreds = &cobra.Command{
  225. Use: "credentials",
  226. Short: "Display api credentials",
  227. Long: ``,
  228. Example: `cscli api credentials`,
  229. Args: cobra.MinimumNArgs(0),
  230. Run: func(cmd *cobra.Command, args []string) {
  231. if err := dumpCredentials(); err != nil {
  232. log.Fatalf(err.Error())
  233. }
  234. return
  235. },
  236. }
  237. cmdAPI.AddCommand(cmdAPICreds)
  238. cmdAPIEnroll.Flags().StringVarP(&userID, "user", "u", "", "User ID (required)")
  239. cmdAPIEnroll.MarkFlagRequired("user")
  240. cmdAPI.AddCommand(cmdAPIEnroll)
  241. cmdAPI.AddCommand(cmdAPIResetPassword)
  242. cmdAPI.AddCommand(cmdAPIRegister)
  243. cmdAPI.AddCommand(cmdAPIPull)
  244. return cmdAPI
  245. }