api.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package csconfig
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "net"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/pkg/errors"
  11. log "github.com/sirupsen/logrus"
  12. "gopkg.in/yaml.v2"
  13. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  14. "github.com/crowdsecurity/crowdsec/pkg/types"
  15. "github.com/crowdsecurity/crowdsec/pkg/yamlpatch"
  16. )
  17. type APICfg struct {
  18. Client *LocalApiClientCfg `yaml:"client"`
  19. Server *LocalApiServerCfg `yaml:"server"`
  20. }
  21. type ApiCredentialsCfg struct {
  22. URL string `yaml:"url,omitempty" json:"url,omitempty"`
  23. Login string `yaml:"login,omitempty" json:"login,omitempty"`
  24. Password string `yaml:"password,omitempty" json:"-"`
  25. CACertPath string `yaml:"ca_cert_path,omitempty"`
  26. KeyPath string `yaml:"key_path,omitempty"`
  27. CertPath string `yaml:"cert_path,omitempty"`
  28. }
  29. /*global api config (for lapi->oapi)*/
  30. type OnlineApiClientCfg struct {
  31. CredentialsFilePath string `yaml:"credentials_path,omitempty"` // credz will be edited by software, store in diff file
  32. Credentials *ApiCredentialsCfg `yaml:"-"`
  33. }
  34. /*local api config (for crowdsec/cscli->lapi)*/
  35. type LocalApiClientCfg struct {
  36. CredentialsFilePath string `yaml:"credentials_path,omitempty"` // credz will be edited by software, store in diff file
  37. Credentials *ApiCredentialsCfg `yaml:"-"`
  38. InsecureSkipVerify *bool `yaml:"insecure_skip_verify"` // check if api certificate is bad or not
  39. }
  40. func (o *OnlineApiClientCfg) Load() error {
  41. o.Credentials = new(ApiCredentialsCfg)
  42. fcontent, err := os.ReadFile(o.CredentialsFilePath)
  43. if err != nil {
  44. return errors.Wrapf(err, "failed to read api server credentials configuration file '%s'", o.CredentialsFilePath)
  45. }
  46. err = yaml.UnmarshalStrict(fcontent, o.Credentials)
  47. if err != nil {
  48. return errors.Wrapf(err, "failed unmarshaling api server credentials configuration file '%s'", o.CredentialsFilePath)
  49. }
  50. if o.Credentials.Login == "" || o.Credentials.Password == "" || o.Credentials.URL == "" {
  51. log.Warningf("can't load CAPI credentials from '%s' (missing field)", o.CredentialsFilePath)
  52. o.Credentials = nil
  53. }
  54. return nil
  55. }
  56. func (l *LocalApiClientCfg) Load() error {
  57. patcher := yamlpatch.NewPatcher(l.CredentialsFilePath, ".local")
  58. fcontent, err := patcher.MergedPatchContent()
  59. if err != nil {
  60. return err
  61. }
  62. err = yaml.UnmarshalStrict(fcontent, &l.Credentials)
  63. if err != nil {
  64. return errors.Wrapf(err, "failed unmarshaling api client credential configuration file '%s'", l.CredentialsFilePath)
  65. }
  66. if l.Credentials == nil || l.Credentials.URL == "" {
  67. return fmt.Errorf("no credentials or URL found in api client configuration '%s'", l.CredentialsFilePath)
  68. }
  69. if l.Credentials != nil && l.Credentials.URL != "" {
  70. if !strings.HasSuffix(l.Credentials.URL, "/") {
  71. l.Credentials.URL += "/"
  72. }
  73. }
  74. if l.Credentials.Login != "" && (l.Credentials.CACertPath != "" || l.Credentials.CertPath != "" || l.Credentials.KeyPath != "") {
  75. return fmt.Errorf("user/password authentication and TLS authentication are mutually exclusive")
  76. }
  77. if l.InsecureSkipVerify == nil {
  78. apiclient.InsecureSkipVerify = false
  79. } else {
  80. apiclient.InsecureSkipVerify = *l.InsecureSkipVerify
  81. }
  82. if l.Credentials.CACertPath != "" && l.Credentials.CertPath != "" && l.Credentials.KeyPath != "" {
  83. cert, err := tls.LoadX509KeyPair(l.Credentials.CertPath, l.Credentials.KeyPath)
  84. if err != nil {
  85. return errors.Wrapf(err, "failed to load api client certificate")
  86. }
  87. caCert, err := os.ReadFile(l.Credentials.CACertPath)
  88. if err != nil {
  89. return errors.Wrapf(err, "failed to load cacert")
  90. }
  91. caCertPool := x509.NewCertPool()
  92. caCertPool.AppendCertsFromPEM(caCert)
  93. apiclient.Cert = &cert
  94. apiclient.CaCertPool = caCertPool
  95. }
  96. return nil
  97. }
  98. func (lapiCfg *LocalApiServerCfg) GetTrustedIPs() ([]net.IPNet, error) {
  99. trustedIPs := make([]net.IPNet, 0)
  100. for _, ip := range lapiCfg.TrustedIPs {
  101. cidr := toValidCIDR(ip)
  102. _, ipNet, err := net.ParseCIDR(cidr)
  103. if err != nil {
  104. return nil, err
  105. }
  106. trustedIPs = append(trustedIPs, *ipNet)
  107. }
  108. return trustedIPs, nil
  109. }
  110. func toValidCIDR(ip string) string {
  111. if strings.Contains(ip, "/") {
  112. return ip
  113. }
  114. if strings.Contains(ip, ":") {
  115. return ip + "/128"
  116. }
  117. return ip + "/32"
  118. }
  119. /*local api service configuration*/
  120. type LocalApiServerCfg struct {
  121. Enable *bool `yaml:"enable"`
  122. ListenURI string `yaml:"listen_uri,omitempty"` // 127.0.0.1:8080
  123. TLS *TLSCfg `yaml:"tls"`
  124. DbConfig *DatabaseCfg `yaml:"-"`
  125. LogDir string `yaml:"-"`
  126. LogMedia string `yaml:"-"`
  127. OnlineClient *OnlineApiClientCfg `yaml:"online_client"`
  128. ProfilesPath string `yaml:"profiles_path,omitempty"`
  129. ConsoleConfigPath string `yaml:"console_path,omitempty"`
  130. ConsoleConfig *ConsoleConfig `yaml:"-"`
  131. Profiles []*ProfileCfg `yaml:"-"`
  132. LogLevel *log.Level `yaml:"log_level"`
  133. UseForwardedForHeaders bool `yaml:"use_forwarded_for_headers,omitempty"`
  134. TrustedProxies *[]string `yaml:"trusted_proxies,omitempty"`
  135. CompressLogs *bool `yaml:"-"`
  136. LogMaxSize int `yaml:"-"`
  137. LogMaxAge int `yaml:"-"`
  138. LogMaxFiles int `yaml:"-"`
  139. TrustedIPs []string `yaml:"trusted_ips,omitempty"`
  140. }
  141. type TLSCfg struct {
  142. CertFilePath string `yaml:"cert_file"`
  143. KeyFilePath string `yaml:"key_file"`
  144. ClientVerification string `yaml:"client_verification,omitempty"`
  145. ServerName string `yaml:"server_name"`
  146. CACertPath string `yaml:"ca_cert_path"`
  147. AllowedAgentsOU []string `yaml:"agents_allowed_ou"`
  148. AllowedBouncersOU []string `yaml:"bouncers_allowed_ou"`
  149. CRLPath string `yaml:"crl_path"`
  150. CacheExpiration *time.Duration `yaml:"cache_expiration,omitempty"`
  151. }
  152. func (c *Config) LoadAPIServer() error {
  153. if c.DisableAPI {
  154. log.Warning("crowdsec local API is disabled from flag")
  155. }
  156. if c.API.Server == nil {
  157. log.Warning("crowdsec local API is disabled because its configuration is not present")
  158. c.DisableAPI = true
  159. return nil
  160. }
  161. if c.API.Server.Enable == nil {
  162. // if the option is not present, it is enabled by default
  163. c.API.Server.Enable = types.BoolPtr(true)
  164. }
  165. if !*c.API.Server.Enable {
  166. log.Warning("crowdsec local API is disabled because 'enable' is set to false")
  167. c.DisableAPI = true
  168. return nil
  169. }
  170. if c.DisableAPI {
  171. return nil
  172. }
  173. if err := c.LoadCommon(); err != nil {
  174. return fmt.Errorf("loading common configuration: %s", err)
  175. }
  176. c.API.Server.LogDir = c.Common.LogDir
  177. c.API.Server.LogMedia = c.Common.LogMedia
  178. c.API.Server.CompressLogs = c.Common.CompressLogs
  179. c.API.Server.LogMaxSize = c.Common.LogMaxSize
  180. c.API.Server.LogMaxAge = c.Common.LogMaxAge
  181. c.API.Server.LogMaxFiles = c.Common.LogMaxFiles
  182. if c.API.Server.UseForwardedForHeaders && c.API.Server.TrustedProxies == nil {
  183. c.API.Server.TrustedProxies = &[]string{"0.0.0.0/0"}
  184. }
  185. if c.API.Server.TrustedProxies != nil {
  186. c.API.Server.UseForwardedForHeaders = true
  187. }
  188. if err := c.API.Server.LoadProfiles(); err != nil {
  189. return errors.Wrap(err, "while loading profiles for LAPI")
  190. }
  191. if c.API.Server.ConsoleConfigPath == "" {
  192. c.API.Server.ConsoleConfigPath = DefaultConsoleConfigFilePath
  193. }
  194. if err := c.API.Server.LoadConsoleConfig(); err != nil {
  195. return errors.Wrap(err, "while loading console options")
  196. }
  197. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  198. if err := c.API.Server.OnlineClient.Load(); err != nil {
  199. return errors.Wrap(err, "loading online client credentials")
  200. }
  201. }
  202. if err := c.LoadDBConfig(); err != nil {
  203. return err
  204. }
  205. return nil
  206. }
  207. func (c *Config) LoadAPIClient() error {
  208. if c.API == nil || c.API.Client == nil || c.API.Client.CredentialsFilePath == "" || c.DisableAgent {
  209. return fmt.Errorf("no API client section in configuration")
  210. }
  211. if err := c.API.Client.Load(); err != nil {
  212. return err
  213. }
  214. return nil
  215. }