auth.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package cwapi
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "github.com/crowdsecurity/crowdsec/pkg/cwversion"
  10. "github.com/crowdsecurity/crowdsec/pkg/types"
  11. log "github.com/sirupsen/logrus"
  12. "gopkg.in/yaml.v2"
  13. "github.com/dghubble/sling"
  14. "gopkg.in/tomb.v2"
  15. )
  16. type ApiCtx struct {
  17. /*config*/
  18. ApiVersion string `yaml:"version"`
  19. PullPath string `yaml:"pull_path"`
  20. PushPath string `yaml:"push_path"`
  21. SigninPath string `yaml:"signin_path"`
  22. RegisterPath string `yaml:"register_path"`
  23. ResetPwdPath string `yaml:"reset_pwd_path"`
  24. EnrollPath string `yaml:"enroll_path"`
  25. BaseURL string `yaml:"url"`
  26. CfgUser string `yaml:"machine_id"`
  27. CfgPassword string `yaml:"password"`
  28. Creds ApiCreds `yaml:"-"`
  29. /*mostly for mocking/faking api*/
  30. Muted bool `yaml:"-"`
  31. DebugDump bool `yaml:"-"`
  32. /*runtime*/
  33. tokenExpired bool `yaml:"-"`
  34. toPush []types.Event `yaml:"-"`
  35. Http *sling.Sling `yaml:"-"`
  36. PusherTomb tomb.Tomb `yaml:"-"`
  37. }
  38. type ApiCreds struct {
  39. User string `json:"machine_id" yaml:"machine_id"`
  40. Password string `json:"password" yaml:"password"`
  41. Profile string `json:"profile,omitempty" yaml:"profile,omitempty"`
  42. }
  43. type ApiResp struct {
  44. StatusCode int `json:"statusCode"`
  45. Error string `json:"error"`
  46. Message string `json:"message"`
  47. }
  48. type PullResp struct {
  49. StatusCode int `json:"statusCode"`
  50. Body []map[string]string `json:"message"`
  51. }
  52. func (ctx *ApiCtx) WriteConfig(cfg string) error {
  53. ret, err := yaml.Marshal(ctx)
  54. if err != nil {
  55. return fmt.Errorf("failed to marshal config : %s", err)
  56. }
  57. if err := ioutil.WriteFile(cfg, ret, 0600); err != nil {
  58. return fmt.Errorf("failed to write api file %s : %s", cfg, ret)
  59. }
  60. return nil
  61. }
  62. func (ctx *ApiCtx) LoadConfig(cfg string) error {
  63. rcfg, err := ioutil.ReadFile(cfg)
  64. if err != nil {
  65. return fmt.Errorf("api load configuration: unable to read configuration file '%s' : %s", cfg, err)
  66. }
  67. if err := yaml.UnmarshalStrict(rcfg, &ctx); err != nil {
  68. return fmt.Errorf("api load configuration: unable to unmarshall configuration file '%s' : %s", cfg, err)
  69. }
  70. if ctx.ApiVersion != cwversion.Constraint_api {
  71. return fmt.Errorf("api load configuration: cscli version only supports %s api, not %s", cwversion.Constraint_api, ctx.ApiVersion)
  72. }
  73. ctx.Creds.User = ctx.CfgUser
  74. ctx.Creds.Password = ctx.CfgPassword
  75. /*
  76. For sling, if a path starts with '/', it's an absolute path, and it will get rid of the 'prefix',
  77. leading to bad urls
  78. */
  79. if strings.HasPrefix(ctx.PullPath, "/") ||
  80. strings.HasPrefix(ctx.PushPath, "/") ||
  81. strings.HasPrefix(ctx.SigninPath, "/") ||
  82. strings.HasPrefix(ctx.RegisterPath, "/") ||
  83. strings.HasPrefix(ctx.ResetPwdPath, "/") ||
  84. strings.HasPrefix(ctx.EnrollPath, "/") {
  85. log.Warningf("!API paths must not be prefixed by /")
  86. }
  87. httpClient := &http.Client{Timeout: 20 * time.Second}
  88. ctx.Http = sling.New().Client(httpClient).Base(ctx.BaseURL+"/"+ctx.ApiVersion+"/").Set("User-Agent", fmt.Sprintf("Crowdsec/%s", cwversion.VersionStr()))
  89. log.Printf("api load configuration: configuration loaded successfully (base:%s)", ctx.BaseURL+"/"+ctx.ApiVersion+"/")
  90. return nil
  91. }
  92. func (ctx *ApiCtx) Init(cfg string, profile string) error {
  93. var err error
  94. err = ctx.LoadConfig(cfg)
  95. if err != nil {
  96. return err
  97. }
  98. ctx.Creds.Profile = profile
  99. ctx.toPush = make([]types.Event, 0)
  100. err = ctx.Signin()
  101. if err != nil {
  102. return err
  103. }
  104. //start the background go-routine
  105. ctx.PusherTomb.Go(func() error {
  106. err := ctx.pushLoop()
  107. if err != nil {
  108. log.Errorf("api push error : %s", err)
  109. return err
  110. }
  111. return nil
  112. })
  113. return nil
  114. }
  115. func (ctx *ApiCtx) Shutdown() error {
  116. ctx.PusherTomb.Kill(nil)
  117. log.Infof("Waiting for API routine to finish")
  118. if err := ctx.PusherTomb.Wait(); err != nil {
  119. return fmt.Errorf("API routine returned error : %s", err)
  120. }
  121. return nil
  122. }
  123. func (ctx *ApiCtx) Signin() error {
  124. if ctx.Creds.User == "" || ctx.Creds.Password == "" {
  125. return fmt.Errorf("api signin: missing credentials in api.yaml")
  126. }
  127. jsonResp := &ApiResp{}
  128. errResp := &ApiResp{}
  129. resp, err := ctx.Http.New().Post(ctx.SigninPath).BodyJSON(ctx.Creds).Receive(jsonResp, errResp)
  130. if err != nil {
  131. return fmt.Errorf("api signin: HTTP request creation failed: %s", err)
  132. }
  133. if resp.StatusCode != 200 {
  134. return fmt.Errorf("api signin: return bad HTTP code (%d): %s", resp.StatusCode, errResp.Message)
  135. }
  136. if jsonResp.Message == "" || jsonResp.StatusCode != 200 {
  137. return fmt.Errorf("api signin failed")
  138. }
  139. ctx.Http = ctx.Http.Set("Authorization", jsonResp.Message)
  140. log.Printf("api signin: signed in successfuly")
  141. return nil
  142. }
  143. func (ctx *ApiCtx) RegisterMachine(machineID string, password string) error {
  144. if !validate(machineID) {
  145. log.Fatalf("Machine ID %s is not compliant to '^[a-zA-Z0-9]+$'", machineID)
  146. }
  147. ctx.Creds.User = machineID
  148. ctx.Creds.Password = password
  149. jsonResp := &ApiResp{}
  150. errResp := &ApiResp{}
  151. resp, err := ctx.Http.New().Post(ctx.RegisterPath).BodyJSON(ctx.Creds).Receive(jsonResp, errResp)
  152. if err != nil {
  153. return fmt.Errorf("api register machine: HTTP request creation failed: %s", err)
  154. }
  155. if resp.StatusCode != 200 {
  156. return fmt.Errorf("api register machine: return bad HTTP code (%d) : %s", resp.StatusCode, errResp.Message)
  157. }
  158. if jsonResp.Message == "" || jsonResp.Message != "OK" || jsonResp.StatusCode != 200 {
  159. return fmt.Errorf("api register machine failed")
  160. }
  161. return nil
  162. }
  163. func (ctx *ApiCtx) ResetPassword(machineID string, password string) error {
  164. if !validate(machineID) {
  165. log.Fatalf("Machine ID %s is not compliant to '^[a-zA-Z0-9]+$'", machineID)
  166. }
  167. ctx.Creds.User = machineID
  168. ctx.Creds.Password = password
  169. jsonResp := &ApiResp{}
  170. errResp := &ApiResp{}
  171. data := map[string]string{"machine_id": ctx.Creds.User, "password": ctx.Creds.Password}
  172. resp, err := ctx.Http.New().Post(ctx.ResetPwdPath).BodyJSON(data).Receive(jsonResp, errResp)
  173. if err != nil {
  174. return fmt.Errorf("api reset password: HTTP request creation failed: %s", err)
  175. }
  176. if resp.StatusCode != 200 {
  177. return fmt.Errorf("api reset password: return bad HTTP code (%d): %s", resp.StatusCode, errResp.Message)
  178. }
  179. if jsonResp.Message == "" || jsonResp.StatusCode != 200 {
  180. return fmt.Errorf("api reset password failed")
  181. }
  182. return nil
  183. }
  184. func validate(machineID string) bool {
  185. re := regexp.MustCompile("^[a-zA-Z0-9]+$")
  186. return re.MatchString(machineID)
  187. }