api.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. package csconfig
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "net"
  7. "os"
  8. "strings"
  9. "time"
  10. log "github.com/sirupsen/logrus"
  11. "gopkg.in/yaml.v2"
  12. "github.com/crowdsecurity/go-cs-lib/pkg/ptr"
  13. "github.com/crowdsecurity/go-cs-lib/pkg/yamlpatch"
  14. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  15. )
  16. type APICfg struct {
  17. Client *LocalApiClientCfg `yaml:"client"`
  18. Server *LocalApiServerCfg `yaml:"server"`
  19. CTI *CTICfg `yaml:"cti"`
  20. }
  21. type ApiCredentialsCfg struct {
  22. PapiURL string `yaml:"papi_url,omitempty" json:"papi_url,omitempty"`
  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 fmt.Errorf("failed to read api server credentials configuration file '%s': %w", o.CredentialsFilePath, err)
  74. }
  75. err = yaml.UnmarshalStrict(fcontent, o.Credentials)
  76. if err != nil {
  77. return fmt.Errorf("failed unmarshaling api server credentials configuration file '%s': %w", o.CredentialsFilePath, err)
  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 fmt.Errorf("failed unmarshaling api client credential configuration file '%s': %w", l.CredentialsFilePath, err)
  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 fmt.Errorf("failed to load cacert: %w", err)
  115. }
  116. caCertPool, err := x509.SystemCertPool()
  117. if err != nil {
  118. log.Warningf("Error loading system CA certificates: %s", err)
  119. }
  120. if caCertPool == nil {
  121. caCertPool = x509.NewCertPool()
  122. }
  123. caCertPool.AppendCertsFromPEM(caCert)
  124. apiclient.CaCertPool = caCertPool
  125. }
  126. if l.Credentials.CertPath != "" && l.Credentials.KeyPath != "" {
  127. cert, err := tls.LoadX509KeyPair(l.Credentials.CertPath, l.Credentials.KeyPath)
  128. if err != nil {
  129. return fmt.Errorf("failed to load api client certificate: %w", err)
  130. }
  131. apiclient.Cert = &cert
  132. }
  133. return nil
  134. }
  135. func (lapiCfg *LocalApiServerCfg) GetTrustedIPs() ([]net.IPNet, error) {
  136. trustedIPs := make([]net.IPNet, 0)
  137. for _, ip := range lapiCfg.TrustedIPs {
  138. cidr := toValidCIDR(ip)
  139. _, ipNet, err := net.ParseCIDR(cidr)
  140. if err != nil {
  141. return nil, err
  142. }
  143. trustedIPs = append(trustedIPs, *ipNet)
  144. }
  145. return trustedIPs, nil
  146. }
  147. func toValidCIDR(ip string) string {
  148. if strings.Contains(ip, "/") {
  149. return ip
  150. }
  151. if strings.Contains(ip, ":") {
  152. return ip + "/128"
  153. }
  154. return ip + "/32"
  155. }
  156. type CapiWhitelist struct {
  157. Ips []net.IP `yaml:"ips,omitempty"`
  158. Cidrs []*net.IPNet `yaml:"cidrs,omitempty"`
  159. }
  160. /*local api service configuration*/
  161. type LocalApiServerCfg struct {
  162. Enable *bool `yaml:"enable"`
  163. ListenURI string `yaml:"listen_uri,omitempty"` // 127.0.0.1:8080
  164. TLS *TLSCfg `yaml:"tls"`
  165. DbConfig *DatabaseCfg `yaml:"-"`
  166. LogDir string `yaml:"-"`
  167. LogMedia string `yaml:"-"`
  168. OnlineClient *OnlineApiClientCfg `yaml:"online_client"`
  169. ProfilesPath string `yaml:"profiles_path,omitempty"`
  170. ConsoleConfigPath string `yaml:"console_path,omitempty"`
  171. ConsoleConfig *ConsoleConfig `yaml:"-"`
  172. Profiles []*ProfileCfg `yaml:"-"`
  173. LogLevel *log.Level `yaml:"log_level"`
  174. UseForwardedForHeaders bool `yaml:"use_forwarded_for_headers,omitempty"`
  175. TrustedProxies *[]string `yaml:"trusted_proxies,omitempty"`
  176. CompressLogs *bool `yaml:"-"`
  177. LogMaxSize int `yaml:"-"`
  178. LogMaxAge int `yaml:"-"`
  179. LogMaxFiles int `yaml:"-"`
  180. TrustedIPs []string `yaml:"trusted_ips,omitempty"`
  181. PapiLogLevel *log.Level `yaml:"papi_log_level"`
  182. DisableRemoteLapiRegistration bool `yaml:"disable_remote_lapi_registration,omitempty"`
  183. CapiWhitelistsPath string `yaml:"capi_whitelists_path,omitempty"`
  184. CapiWhitelists *CapiWhitelist `yaml:"-"`
  185. }
  186. type TLSCfg struct {
  187. CertFilePath string `yaml:"cert_file"`
  188. KeyFilePath string `yaml:"key_file"`
  189. ClientVerification string `yaml:"client_verification,omitempty"`
  190. ServerName string `yaml:"server_name"`
  191. CACertPath string `yaml:"ca_cert_path"`
  192. AllowedAgentsOU []string `yaml:"agents_allowed_ou"`
  193. AllowedBouncersOU []string `yaml:"bouncers_allowed_ou"`
  194. CRLPath string `yaml:"crl_path"`
  195. CacheExpiration *time.Duration `yaml:"cache_expiration,omitempty"`
  196. }
  197. func (c *Config) LoadAPIServer() error {
  198. if c.DisableAPI {
  199. log.Warning("crowdsec local API is disabled from flag")
  200. }
  201. if c.API.Server == nil {
  202. log.Warning("crowdsec local API is disabled")
  203. c.DisableAPI = true
  204. return nil
  205. }
  206. //inherit log level from common, then api->server
  207. var logLevel log.Level
  208. if c.API.Server.LogLevel != nil {
  209. logLevel = *c.API.Server.LogLevel
  210. } else if c.Common.LogLevel != nil {
  211. logLevel = *c.Common.LogLevel
  212. } else {
  213. logLevel = log.InfoLevel
  214. }
  215. if c.API.Server.PapiLogLevel == nil {
  216. c.API.Server.PapiLogLevel = &logLevel
  217. }
  218. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  219. if err := c.API.Server.OnlineClient.Load(); err != nil {
  220. return fmt.Errorf("loading online client credentials: %w", err)
  221. }
  222. }
  223. if c.API.Server.OnlineClient == nil || c.API.Server.OnlineClient.Credentials == nil {
  224. log.Printf("push and pull to Central API disabled")
  225. }
  226. if err := c.LoadDBConfig(); err != nil {
  227. return err
  228. }
  229. if err := c.API.Server.LoadCapiWhitelists(); err != nil {
  230. return err
  231. }
  232. if c.API.Server.CapiWhitelistsPath != "" {
  233. log.Infof("loaded capi whitelist from %s: %d IPs, %d CIDRs", c.API.Server.CapiWhitelistsPath, len(c.API.Server.CapiWhitelists.Ips), len(c.API.Server.CapiWhitelists.Cidrs))
  234. }
  235. if c.API.Server.Enable == nil {
  236. // if the option is not present, it is enabled by default
  237. c.API.Server.Enable = ptr.Of(true)
  238. }
  239. if !*c.API.Server.Enable {
  240. log.Warning("crowdsec local API is disabled because 'enable' is set to false")
  241. c.DisableAPI = true
  242. return nil
  243. }
  244. if c.DisableAPI {
  245. return nil
  246. }
  247. if err := c.LoadCommon(); err != nil {
  248. return fmt.Errorf("loading common configuration: %s", err)
  249. }
  250. c.API.Server.LogDir = c.Common.LogDir
  251. c.API.Server.LogMedia = c.Common.LogMedia
  252. c.API.Server.CompressLogs = c.Common.CompressLogs
  253. c.API.Server.LogMaxSize = c.Common.LogMaxSize
  254. c.API.Server.LogMaxAge = c.Common.LogMaxAge
  255. c.API.Server.LogMaxFiles = c.Common.LogMaxFiles
  256. if c.API.Server.UseForwardedForHeaders && c.API.Server.TrustedProxies == nil {
  257. c.API.Server.TrustedProxies = &[]string{"0.0.0.0/0"}
  258. }
  259. if c.API.Server.TrustedProxies != nil {
  260. c.API.Server.UseForwardedForHeaders = true
  261. }
  262. if err := c.API.Server.LoadProfiles(); err != nil {
  263. return fmt.Errorf("while loading profiles for LAPI: %w", err)
  264. }
  265. if c.API.Server.ConsoleConfigPath == "" {
  266. c.API.Server.ConsoleConfigPath = DefaultConsoleConfigFilePath
  267. }
  268. if err := c.API.Server.LoadConsoleConfig(); err != nil {
  269. return fmt.Errorf("while loading console options: %w", err)
  270. }
  271. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  272. if err := c.API.Server.OnlineClient.Load(); err != nil {
  273. return fmt.Errorf("loading online client credentials: %w", err)
  274. }
  275. }
  276. if c.API.Server.OnlineClient == nil || c.API.Server.OnlineClient.Credentials == nil {
  277. log.Printf("push and pull to Central API disabled")
  278. }
  279. if c.API.CTI != nil {
  280. if err := c.API.CTI.Load(); err != nil {
  281. return fmt.Errorf("loading CTI configuration: %w", err)
  282. }
  283. }
  284. return nil
  285. }
  286. // we cannot unmarshal to type net.IPNet, so we need to do it manually
  287. type capiWhitelists struct {
  288. Ips []string `yaml:"ips"`
  289. Cidrs []string `yaml:"cidrs"`
  290. }
  291. func (s *LocalApiServerCfg) LoadCapiWhitelists() error {
  292. if s.CapiWhitelistsPath == "" {
  293. return nil
  294. }
  295. if _, err := os.Stat(s.CapiWhitelistsPath); os.IsNotExist(err) {
  296. return fmt.Errorf("capi whitelist file '%s' does not exist", s.CapiWhitelistsPath)
  297. }
  298. fd, err := os.Open(s.CapiWhitelistsPath)
  299. if err != nil {
  300. return fmt.Errorf("unable to open capi whitelist file '%s': %s", s.CapiWhitelistsPath, err)
  301. }
  302. var fromCfg capiWhitelists
  303. s.CapiWhitelists = &CapiWhitelist{}
  304. defer fd.Close()
  305. decoder := yaml.NewDecoder(fd)
  306. if err := decoder.Decode(&fromCfg); err != nil {
  307. return fmt.Errorf("while parsing capi whitelist file '%s': %s", s.CapiWhitelistsPath, err)
  308. }
  309. for _, v := range fromCfg.Ips {
  310. ip := net.ParseIP(v)
  311. if ip == nil {
  312. return fmt.Errorf("unable to parse ip whitelist '%s'", v)
  313. }
  314. s.CapiWhitelists.Ips = append(s.CapiWhitelists.Ips, ip)
  315. }
  316. for _, v := range fromCfg.Cidrs {
  317. _, tnet, err := net.ParseCIDR(v)
  318. if err != nil {
  319. return fmt.Errorf("unable to parse cidr whitelist '%s' : %v", v, err)
  320. }
  321. s.CapiWhitelists.Cidrs = append(s.CapiWhitelists.Cidrs, tnet)
  322. }
  323. return nil
  324. }
  325. func (c *Config) LoadAPIClient() error {
  326. if c.API == nil || c.API.Client == nil || c.API.Client.CredentialsFilePath == "" || c.DisableAgent {
  327. return fmt.Errorf("no API client section in configuration")
  328. }
  329. if err := c.API.Client.Load(); err != nil {
  330. return err
  331. }
  332. return nil
  333. }