api.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. /*local api service configuration*/
  152. type LocalApiServerCfg struct {
  153. Enable *bool `yaml:"enable"`
  154. ListenURI string `yaml:"listen_uri,omitempty"` // 127.0.0.1:8080
  155. TLS *TLSCfg `yaml:"tls"`
  156. DbConfig *DatabaseCfg `yaml:"-"`
  157. LogDir string `yaml:"-"`
  158. LogMedia string `yaml:"-"`
  159. OnlineClient *OnlineApiClientCfg `yaml:"online_client"`
  160. ProfilesPath string `yaml:"profiles_path,omitempty"`
  161. ConsoleConfigPath string `yaml:"console_path,omitempty"`
  162. ConsoleConfig *ConsoleConfig `yaml:"-"`
  163. Profiles []*ProfileCfg `yaml:"-"`
  164. LogLevel *log.Level `yaml:"log_level"`
  165. UseForwardedForHeaders bool `yaml:"use_forwarded_for_headers,omitempty"`
  166. TrustedProxies *[]string `yaml:"trusted_proxies,omitempty"`
  167. CompressLogs *bool `yaml:"-"`
  168. LogMaxSize int `yaml:"-"`
  169. LogMaxAge int `yaml:"-"`
  170. LogMaxFiles int `yaml:"-"`
  171. TrustedIPs []string `yaml:"trusted_ips,omitempty"`
  172. PapiLogLevel *log.Level `yaml:"papi_log_level"`
  173. }
  174. type TLSCfg struct {
  175. CertFilePath string `yaml:"cert_file"`
  176. KeyFilePath string `yaml:"key_file"`
  177. ClientVerification string `yaml:"client_verification,omitempty"`
  178. ServerName string `yaml:"server_name"`
  179. CACertPath string `yaml:"ca_cert_path"`
  180. AllowedAgentsOU []string `yaml:"agents_allowed_ou"`
  181. AllowedBouncersOU []string `yaml:"bouncers_allowed_ou"`
  182. CRLPath string `yaml:"crl_path"`
  183. CacheExpiration *time.Duration `yaml:"cache_expiration,omitempty"`
  184. }
  185. func (c *Config) LoadAPIServer() error {
  186. if c.DisableAPI {
  187. log.Warning("crowdsec local API is disabled from flag")
  188. }
  189. if c.API.Server != nil {
  190. //inherit log level from common, then api->server
  191. var logLevel log.Level
  192. if c.API.Server.LogLevel != nil {
  193. logLevel = *c.API.Server.LogLevel
  194. } else if c.Common.LogLevel != nil {
  195. logLevel = *c.Common.LogLevel
  196. } else {
  197. logLevel = log.InfoLevel
  198. }
  199. if c.API.Server.PapiLogLevel == nil {
  200. c.API.Server.PapiLogLevel = &logLevel
  201. }
  202. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  203. if err := c.API.Server.OnlineClient.Load(); err != nil {
  204. return errors.Wrap(err, "loading online client credentials")
  205. }
  206. }
  207. if c.API.Server.OnlineClient == nil || c.API.Server.OnlineClient.Credentials == nil {
  208. log.Printf("push and pull to Central API disabled")
  209. }
  210. if err := c.LoadDBConfig(); err != nil {
  211. return err
  212. }
  213. } else {
  214. log.Warning("crowdsec local API is disabled")
  215. c.DisableAPI = true
  216. return nil
  217. }
  218. if c.API.Server.Enable == nil {
  219. // if the option is not present, it is enabled by default
  220. c.API.Server.Enable = types.BoolPtr(true)
  221. }
  222. if !*c.API.Server.Enable {
  223. log.Warning("crowdsec local API is disabled because 'enable' is set to false")
  224. c.DisableAPI = true
  225. return nil
  226. }
  227. if c.DisableAPI {
  228. return nil
  229. }
  230. if err := c.LoadCommon(); err != nil {
  231. return fmt.Errorf("loading common configuration: %s", err)
  232. }
  233. c.API.Server.LogDir = c.Common.LogDir
  234. c.API.Server.LogMedia = c.Common.LogMedia
  235. c.API.Server.CompressLogs = c.Common.CompressLogs
  236. c.API.Server.LogMaxSize = c.Common.LogMaxSize
  237. c.API.Server.LogMaxAge = c.Common.LogMaxAge
  238. c.API.Server.LogMaxFiles = c.Common.LogMaxFiles
  239. if c.API.Server.UseForwardedForHeaders && c.API.Server.TrustedProxies == nil {
  240. c.API.Server.TrustedProxies = &[]string{"0.0.0.0/0"}
  241. }
  242. if c.API.Server.TrustedProxies != nil {
  243. c.API.Server.UseForwardedForHeaders = true
  244. }
  245. if err := c.API.Server.LoadProfiles(); err != nil {
  246. return errors.Wrap(err, "while loading profiles for LAPI")
  247. }
  248. if c.API.Server.ConsoleConfigPath == "" {
  249. c.API.Server.ConsoleConfigPath = DefaultConsoleConfigFilePath
  250. }
  251. if err := c.API.Server.LoadConsoleConfig(); err != nil {
  252. return errors.Wrap(err, "while loading console options")
  253. }
  254. if c.API.Server.OnlineClient != nil && c.API.Server.OnlineClient.CredentialsFilePath != "" {
  255. if err := c.API.Server.OnlineClient.Load(); err != nil {
  256. return errors.Wrap(err, "loading online client credentials")
  257. }
  258. }
  259. if c.API.Server.OnlineClient == nil || c.API.Server.OnlineClient.Credentials == nil {
  260. log.Printf("push and pull to Central API disabled")
  261. }
  262. if c.API.CTI != nil {
  263. if err := c.API.CTI.Load(); err != nil {
  264. return errors.Wrap(err, "loading CTI configuration")
  265. }
  266. }
  267. return nil
  268. }
  269. func (c *Config) LoadAPIClient() error {
  270. if c.API == nil || c.API.Client == nil || c.API.Client.CredentialsFilePath == "" || c.DisableAgent {
  271. return fmt.Errorf("no API client section in configuration")
  272. }
  273. if err := c.API.Client.Load(); err != nil {
  274. return err
  275. }
  276. return nil
  277. }