api.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. package csconfig
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "os"
  10. "strings"
  11. "time"
  12. log "github.com/sirupsen/logrus"
  13. "gopkg.in/yaml.v2"
  14. "github.com/crowdsecurity/go-cs-lib/ptr"
  15. "github.com/crowdsecurity/go-cs-lib/yamlpatch"
  16. "github.com/crowdsecurity/crowdsec/pkg/apiclient"
  17. )
  18. type APICfg struct {
  19. Client *LocalApiClientCfg `yaml:"client"`
  20. Server *LocalApiServerCfg `yaml:"server"`
  21. CTI *CTICfg `yaml:"cti"`
  22. }
  23. type ApiCredentialsCfg struct {
  24. PapiURL string `yaml:"papi_url,omitempty" json:"papi_url,omitempty"`
  25. URL string `yaml:"url,omitempty" json:"url,omitempty"`
  26. Login string `yaml:"login,omitempty" json:"login,omitempty"`
  27. Password string `yaml:"password,omitempty" json:"-"`
  28. CACertPath string `yaml:"ca_cert_path,omitempty"`
  29. KeyPath string `yaml:"key_path,omitempty"`
  30. CertPath string `yaml:"cert_path,omitempty"`
  31. }
  32. /*global api config (for lapi->oapi)*/
  33. type OnlineApiClientCfg struct {
  34. CredentialsFilePath string `yaml:"credentials_path,omitempty"` // credz will be edited by software, store in diff file
  35. Credentials *ApiCredentialsCfg `yaml:"-"`
  36. }
  37. /*local api config (for crowdsec/cscli->lapi)*/
  38. type LocalApiClientCfg struct {
  39. CredentialsFilePath string `yaml:"credentials_path,omitempty"` // credz will be edited by software, store in diff file
  40. Credentials *ApiCredentialsCfg `yaml:"-"`
  41. InsecureSkipVerify *bool `yaml:"insecure_skip_verify"` // check if api certificate is bad or not
  42. }
  43. type CTICfg struct {
  44. Key *string `yaml:"key,omitempty"`
  45. CacheTimeout *time.Duration `yaml:"cache_timeout,omitempty"`
  46. CacheSize *int `yaml:"cache_size,omitempty"`
  47. Enabled *bool `yaml:"enabled,omitempty"`
  48. LogLevel *log.Level `yaml:"log_level,omitempty"`
  49. }
  50. func (a *CTICfg) Load() error {
  51. if a.Key == nil {
  52. *a.Enabled = false
  53. }
  54. if a.Key != nil && *a.Key == "" {
  55. return fmt.Errorf("empty cti key")
  56. }
  57. if a.Enabled == nil {
  58. a.Enabled = new(bool)
  59. *a.Enabled = true
  60. }
  61. if a.CacheTimeout == nil {
  62. a.CacheTimeout = new(time.Duration)
  63. *a.CacheTimeout = 10 * time.Minute
  64. }
  65. if a.CacheSize == nil {
  66. a.CacheSize = new(int)
  67. *a.CacheSize = 100
  68. }
  69. return nil
  70. }
  71. func (o *OnlineApiClientCfg) Load() error {
  72. o.Credentials = new(ApiCredentialsCfg)
  73. fcontent, err := os.ReadFile(o.CredentialsFilePath)
  74. if err != nil {
  75. return fmt.Errorf("failed to read api server credentials configuration file '%s': %w", o.CredentialsFilePath, err)
  76. }
  77. err = yaml.UnmarshalStrict(fcontent, o.Credentials)
  78. if err != nil {
  79. return fmt.Errorf("failed unmarshaling api server credentials configuration file '%s': %w", o.CredentialsFilePath, err)
  80. }
  81. if o.Credentials.Login == "" || o.Credentials.Password == "" || o.Credentials.URL == "" {
  82. log.Warningf("can't load CAPI credentials from '%s' (missing field)", o.CredentialsFilePath)
  83. o.Credentials = nil
  84. }
  85. return nil
  86. }
  87. func (l *LocalApiClientCfg) Load() error {
  88. patcher := yamlpatch.NewPatcher(l.CredentialsFilePath, ".local")
  89. fcontent, err := patcher.MergedPatchContent()
  90. if err != nil {
  91. return err
  92. }
  93. err = yaml.UnmarshalStrict(fcontent, &l.Credentials)
  94. if err != nil {
  95. return fmt.Errorf("failed unmarshaling api client credential configuration file '%s': %w", l.CredentialsFilePath, err)
  96. }
  97. if l.Credentials == nil || l.Credentials.URL == "" {
  98. return fmt.Errorf("no credentials or URL found in api client configuration '%s'", l.CredentialsFilePath)
  99. }
  100. if l.Credentials != nil && l.Credentials.URL != "" {
  101. if !strings.HasSuffix(l.Credentials.URL, "/") {
  102. l.Credentials.URL += "/"
  103. }
  104. }
  105. if l.Credentials.Login != "" && (l.Credentials.CertPath != "" || l.Credentials.KeyPath != "") {
  106. return fmt.Errorf("user/password authentication and TLS authentication are mutually exclusive")
  107. }
  108. if l.InsecureSkipVerify == nil {
  109. apiclient.InsecureSkipVerify = false
  110. } else {
  111. apiclient.InsecureSkipVerify = *l.InsecureSkipVerify
  112. }
  113. if l.Credentials.CACertPath != "" {
  114. caCert, err := os.ReadFile(l.Credentials.CACertPath)
  115. if err != nil {
  116. return fmt.Errorf("failed to load cacert: %w", err)
  117. }
  118. caCertPool, err := x509.SystemCertPool()
  119. if err != nil {
  120. log.Warningf("Error loading system CA certificates: %s", err)
  121. }
  122. if caCertPool == nil {
  123. caCertPool = x509.NewCertPool()
  124. }
  125. caCertPool.AppendCertsFromPEM(caCert)
  126. apiclient.CaCertPool = caCertPool
  127. }
  128. if l.Credentials.CertPath != "" && l.Credentials.KeyPath != "" {
  129. cert, err := tls.LoadX509KeyPair(l.Credentials.CertPath, l.Credentials.KeyPath)
  130. if err != nil {
  131. return fmt.Errorf("failed to load api client certificate: %w", err)
  132. }
  133. apiclient.Cert = &cert
  134. }
  135. return nil
  136. }
  137. func (lapiCfg *LocalApiServerCfg) GetTrustedIPs() ([]net.IPNet, error) {
  138. trustedIPs := make([]net.IPNet, 0)
  139. for _, ip := range lapiCfg.TrustedIPs {
  140. cidr := toValidCIDR(ip)
  141. _, ipNet, err := net.ParseCIDR(cidr)
  142. if err != nil {
  143. return nil, err
  144. }
  145. trustedIPs = append(trustedIPs, *ipNet)
  146. }
  147. return trustedIPs, nil
  148. }
  149. func toValidCIDR(ip string) string {
  150. if strings.Contains(ip, "/") {
  151. return ip
  152. }
  153. if strings.Contains(ip, ":") {
  154. return ip + "/128"
  155. }
  156. return ip + "/32"
  157. }
  158. type CapiWhitelist struct {
  159. Ips []net.IP `yaml:"ips,omitempty"`
  160. Cidrs []*net.IPNet `yaml:"cidrs,omitempty"`
  161. }
  162. /*local api service configuration*/
  163. type LocalApiServerCfg struct {
  164. Enable *bool `yaml:"enable"`
  165. ListenURI string `yaml:"listen_uri,omitempty"` // 127.0.0.1:8080
  166. TLS *TLSCfg `yaml:"tls"`
  167. DbConfig *DatabaseCfg `yaml:"-"`
  168. LogDir string `yaml:"-"`
  169. LogMedia string `yaml:"-"`
  170. OnlineClient *OnlineApiClientCfg `yaml:"online_client"`
  171. ProfilesPath string `yaml:"profiles_path,omitempty"`
  172. ConsoleConfigPath string `yaml:"console_path,omitempty"`
  173. ConsoleConfig *ConsoleConfig `yaml:"-"`
  174. Profiles []*ProfileCfg `yaml:"-"`
  175. LogLevel *log.Level `yaml:"log_level"`
  176. UseForwardedForHeaders bool `yaml:"use_forwarded_for_headers,omitempty"`
  177. TrustedProxies *[]string `yaml:"trusted_proxies,omitempty"`
  178. CompressLogs *bool `yaml:"-"`
  179. LogMaxSize int `yaml:"-"`
  180. LogMaxAge int `yaml:"-"`
  181. LogMaxFiles int `yaml:"-"`
  182. TrustedIPs []string `yaml:"trusted_ips,omitempty"`
  183. PapiLogLevel *log.Level `yaml:"papi_log_level"`
  184. DisableRemoteLapiRegistration bool `yaml:"disable_remote_lapi_registration,omitempty"`
  185. CapiWhitelistsPath string `yaml:"capi_whitelists_path,omitempty"`
  186. CapiWhitelists *CapiWhitelist `yaml:"-"`
  187. }
  188. type TLSCfg struct {
  189. CertFilePath string `yaml:"cert_file"`
  190. KeyFilePath string `yaml:"key_file"`
  191. ClientVerification string `yaml:"client_verification,omitempty"`
  192. ServerName string `yaml:"server_name"`
  193. CACertPath string `yaml:"ca_cert_path"`
  194. AllowedAgentsOU []string `yaml:"agents_allowed_ou"`
  195. AllowedBouncersOU []string `yaml:"bouncers_allowed_ou"`
  196. CRLPath string `yaml:"crl_path"`
  197. CacheExpiration *time.Duration `yaml:"cache_expiration,omitempty"`
  198. }
  199. func (c *Config) LoadAPIServer() error {
  200. if c.DisableAPI {
  201. log.Warning("crowdsec local API is disabled from flag")
  202. }
  203. if c.API.Server == nil {
  204. log.Warning("crowdsec local API is disabled")
  205. c.DisableAPI = true
  206. return nil
  207. }
  208. if c.API.Server.Enable == nil {
  209. // if the option is not present, it is enabled by default
  210. c.API.Server.Enable = ptr.Of(true)
  211. }
  212. if !*c.API.Server.Enable {
  213. log.Warning("crowdsec local API is disabled because 'enable' is set to false")
  214. c.DisableAPI = true
  215. return nil
  216. }
  217. if c.DisableAPI {
  218. return nil
  219. }
  220. //inherit log level from common, then api->server
  221. var logLevel log.Level
  222. if c.API.Server.LogLevel != nil {
  223. logLevel = *c.API.Server.LogLevel
  224. } else if c.Common.LogLevel != nil {
  225. logLevel = *c.Common.LogLevel
  226. } else {
  227. logLevel = log.InfoLevel
  228. }
  229. if c.API.Server.PapiLogLevel == nil {
  230. c.API.Server.PapiLogLevel = &logLevel
  231. }
  232. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  233. if err := c.API.Server.OnlineClient.Load(); err != nil {
  234. return fmt.Errorf("loading online client credentials: %w", err)
  235. }
  236. }
  237. if c.API.Server.OnlineClient == nil || c.API.Server.OnlineClient.Credentials == nil {
  238. log.Printf("push and pull to Central API disabled")
  239. }
  240. if err := c.LoadDBConfig(); err != nil {
  241. return err
  242. }
  243. if err := c.API.Server.LoadCapiWhitelists(); err != nil {
  244. return err
  245. }
  246. if c.API.Server.CapiWhitelistsPath != "" {
  247. 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))
  248. }
  249. c.API.Server.LogDir = c.Common.LogDir
  250. c.API.Server.LogMedia = c.Common.LogMedia
  251. c.API.Server.CompressLogs = c.Common.CompressLogs
  252. c.API.Server.LogMaxSize = c.Common.LogMaxSize
  253. c.API.Server.LogMaxAge = c.Common.LogMaxAge
  254. c.API.Server.LogMaxFiles = c.Common.LogMaxFiles
  255. if c.API.Server.UseForwardedForHeaders && c.API.Server.TrustedProxies == nil {
  256. c.API.Server.TrustedProxies = &[]string{"0.0.0.0/0"}
  257. }
  258. if c.API.Server.TrustedProxies != nil {
  259. c.API.Server.UseForwardedForHeaders = true
  260. }
  261. if err := c.API.Server.LoadProfiles(); err != nil {
  262. return fmt.Errorf("while loading profiles for LAPI: %w", err)
  263. }
  264. if c.API.Server.ConsoleConfigPath == "" {
  265. c.API.Server.ConsoleConfigPath = DefaultConsoleConfigFilePath
  266. }
  267. if err := c.API.Server.LoadConsoleConfig(); err != nil {
  268. return fmt.Errorf("while loading console options: %w", err)
  269. }
  270. if c.API.CTI != nil {
  271. if err := c.API.CTI.Load(); err != nil {
  272. return fmt.Errorf("loading CTI configuration: %w", err)
  273. }
  274. }
  275. return nil
  276. }
  277. // we cannot unmarshal to type net.IPNet, so we need to do it manually
  278. type capiWhitelists struct {
  279. Ips []string `yaml:"ips"`
  280. Cidrs []string `yaml:"cidrs"`
  281. }
  282. func parseCapiWhitelists(fd io.Reader) (*CapiWhitelist, error) {
  283. fromCfg := capiWhitelists{}
  284. decoder := yaml.NewDecoder(fd)
  285. if err := decoder.Decode(&fromCfg); err != nil {
  286. if errors.Is(err, io.EOF) {
  287. return nil, fmt.Errorf("empty file")
  288. }
  289. return nil, err
  290. }
  291. ret := &CapiWhitelist{
  292. Ips: make([]net.IP, len(fromCfg.Ips)),
  293. Cidrs: make([]*net.IPNet, len(fromCfg.Cidrs)),
  294. }
  295. for idx, v := range fromCfg.Ips {
  296. ip := net.ParseIP(v)
  297. if ip == nil {
  298. return nil, fmt.Errorf("invalid IP address: %s", v)
  299. }
  300. ret.Ips[idx] = ip
  301. }
  302. for idx, v := range fromCfg.Cidrs {
  303. _, tnet, err := net.ParseCIDR(v)
  304. if err != nil {
  305. return nil, err
  306. }
  307. ret.Cidrs[idx] = tnet
  308. }
  309. return ret, nil
  310. }
  311. func (s *LocalApiServerCfg) LoadCapiWhitelists() error {
  312. if s.CapiWhitelistsPath == "" {
  313. return nil
  314. }
  315. if _, err := os.Stat(s.CapiWhitelistsPath); os.IsNotExist(err) {
  316. return fmt.Errorf("capi whitelist file '%s' does not exist", s.CapiWhitelistsPath)
  317. }
  318. fd, err := os.Open(s.CapiWhitelistsPath)
  319. if err != nil {
  320. return fmt.Errorf("while opening capi whitelist file: %s", err)
  321. }
  322. defer fd.Close()
  323. s.CapiWhitelists, err = parseCapiWhitelists(fd)
  324. if err != nil {
  325. return fmt.Errorf("while parsing capi whitelist file '%s': %w", s.CapiWhitelistsPath, err)
  326. }
  327. return nil
  328. }
  329. func (c *Config) LoadAPIClient() error {
  330. if c.API == nil || c.API.Client == nil || c.API.Client.CredentialsFilePath == "" || c.DisableAgent {
  331. return fmt.Errorf("no API client section in configuration")
  332. }
  333. if err := c.API.Client.Load(); err != nil {
  334. return err
  335. }
  336. return nil
  337. }