auth.go 6.8 KB

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