api.go 9.0 KB

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