api.go 12 KB

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