Compare commits

...

1218 commits

Author SHA1 Message Date
Laurence Jones
05b54687b6
feat: support stdout in cscli support dump (#2939)
* feat: support stdout in cscli support dump

* fix: skip log.info if stdout

* fix: handle errors by returning to runE instead
2024-04-26 15:56:15 +01:00
mmetc
c4473839c4
Refact pkg/parser/node (#2953)
* extract method processFilter()

* extract method processWhitelist()

* lint (whitespace, errors)
2024-04-25 17:53:10 +02:00
mmetc
d2c4bc55fc
plugins: use yaml.v3 (#2969)
* plugins: use yaml.v3

* lint
2024-04-25 17:34:49 +02:00
mmetc
2abc078e53
use go 1.22.2 (#2826) 2024-04-25 15:11:08 +02:00
blotus
ceb4479ec4
add zfs magic for GetFSType (#2950) 2024-04-25 15:05:11 +02:00
mmetc
845d4542bb
cscli: use yaml.v3 (#2965)
* cscli: use yaml.v3

* lint
2024-04-25 14:41:02 +02:00
Thibault "bui" Koechlin
f4ed7b3520
Truncate meta data (#2966)
* truncate meta-data if they are too big
2024-04-25 13:43:38 +02:00
mmetc
60431804d8
db config: don't exit setup if can't detect fs, improve detection for freebsd (#2963) 2024-04-25 11:11:57 +02:00
mmetc
0f942a95f1
pkg/cwhub - rename methods for clarity (#2961)
* pkg/cwhub - rename methods for clarity

* lint
2024-04-24 11:09:37 +02:00
mmetc
97e6588a45
cscli hub items: avoid global (#2960)
* cscli hub items: avoid global

* lint (whitespace, errors)

* lint
2024-04-24 10:05:55 +02:00
mmetc
725cae1fa8
CI: upload coverage with token (#2958) 2024-04-23 12:41:50 +02:00
mmetc
c64332d30a
cscli config show: avoid globals, use yaml v3 (#2863)
* cscli config show: avoid globals, use yaml v3

* lint (whitespace/errors)
2024-04-23 12:28:38 +02:00
mmetc
718d1c54b2
pkg/database/decisiosn: remove filter parameter, which is always passed empty (#2954) 2024-04-23 11:15:27 +02:00
mmetc
b48b728317
cscli support: include stack traces (#2935) 2024-04-22 23:54:51 +02:00
mmetc
fb393f1c57
tests: bump yq, cfssl (#2952) 2024-04-22 17:19:00 +02:00
mmetc
630cbf0c70
update linter list and descriptions (#2951) 2024-04-22 17:18:11 +02:00
Laurence Jones
95f27677e4
enhance: add refactoring to governance (#2955) 2024-04-22 14:18:34 +01:00
blotus
c6e40191dd
Revert "docker: pre-download all hub items and data, opt-in hub updat… (#2947) 2024-04-18 15:33:51 +02:00
AlteredCoder
0746e0c091
Rename bouncers to Remediation component in openAPI (#2936)
* Rename bouncers to Remediation component in openAPI
2024-04-11 11:23:19 +02:00
mmetc
2291a232cb
docker: pre-download hub items (debian image) (#2934) 2024-04-08 15:00:45 +02:00
mmetc
0e8a1c681b
docker: pre-download all hub items and data, opt-in hub update/upgrade (#2933)
* docker: pre-download all hub items and data, opt-in hub update/upgrade

* docker/bars: don't purge anything before pre-downloading hub

* Docker: README update
2024-04-08 14:53:12 +02:00
mmetc
990dd5e08e
use go 1.21.9; update dependencies (#2931) 2024-04-05 15:11:11 +02:00
mmetc
2682f801df
windows: fix data file update (remove before rename) (#2930) 2024-04-05 14:57:33 +02:00
Thibault "bui" Koechlin
912c4bca70
split & reorganize tests a bit. Add tests on existing zones (#2925) 2024-04-03 17:49:05 +02:00
mmetc
26bcd0912a
docker: distribute geoip db in slim image (#2920) 2024-04-03 13:34:35 +02:00
Thibault "bui" Koechlin
63bd31b471
Fix REQUEST_URI behavior + fix #2891 (#2917)
* fix our behavior to comply more with modsec, REQUEST_URI should be: path+query string

* fix #2891 as well

* add new transforms

* add transform tests
2024-03-29 17:57:54 +01:00
mmetc
be97466809
CI: use golangci-lint 1.57 (#2916) 2024-03-26 09:30:32 +01:00
dependabot[bot]
df13f43156
Bump github.com/docker/docker (#2913)
Bumps [github.com/docker/docker](https://github.com/docker/docker) from 24.0.7+incompatible to 24.0.9+incompatible.
- [Release notes](https://github.com/docker/docker/releases)
- [Commits](https://github.com/docker/docker/compare/v24.0.7...v24.0.9)

---
updated-dependencies:
- dependency-name: github.com/docker/docker
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-26 09:13:16 +01:00
dependabot[bot]
368d22ec30
Bump github.com/jackc/pgx/v4 from 4.14.1 to 4.18.2 (#2887)
Bumps [github.com/jackc/pgx/v4](https://github.com/jackc/pgx) from 4.14.1 to 4.18.2.
- [Changelog](https://github.com/jackc/pgx/blob/v4.18.2/CHANGELOG.md)
- [Commits](https://github.com/jackc/pgx/compare/v4.14.1...v4.18.2)

---
updated-dependencies:
- dependency-name: github.com/jackc/pgx/v4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-03-26 09:12:57 +01:00
Christian Kampka
f6bb8412c5
Add patterns_dir configuration option (#2868)
* Add patterns_dir configuration option

* Update config.yaml

---------

Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2024-03-25 16:20:16 +01:00
mmetc
2e1ddec107
cscli: Add user-agent to all hub requests (#2915)
* cscli: Add user-agent to all hub requests

* fix unit test and avoid httpmock

* fix windows test
2024-03-25 10:40:41 +01:00
blotus
52f86c2d10
add libinjection expr helpers (#2914) 2024-03-21 11:39:37 +01:00
mmetc
7779c7ff0c
hub update: reload crowdsec if only data files have changed (#2912) 2024-03-20 15:46:14 +01:00
Thibault "bui" Koechlin
75a50c0c9d
improve a bit cscli examples when it comes to list mgmt (#2911) 2024-03-20 14:02:29 +01:00
mmetc
d9f2a22ee5
cscli metrics -> sort table order (#2908) 2024-03-20 13:27:28 +01:00
blotus
c76325b91b
Update windows pipeline (#2909) 2024-03-19 17:42:08 +01:00
mmetc
dd71f0a866
CI: bump lint version and update configuration (#2901)
* bump golangci-lint to 1.56

* lint (testifylint)

* update lint configuration

* windows test: remove stale code
2024-03-19 10:48:49 +01:00
Thibault "bui" Koechlin
b63e64ee9f
Fix locking logic for HA + add list unsubscribe for PAPI (#2904)
* add list unsubscribe operation for papi

* fix the locking logic for HA
2024-03-19 10:29:16 +01:00
blotus
6de62a1468
warn if user is using inotify to tail a symlink (#2881) 2024-03-19 10:22:43 +01:00
mmetc
b411782648
CI: use go 1.21.8 (#2906) 2024-03-19 10:03:54 +01:00
mmetc
2f49088163
file acquisition: don't bubble error when tailed file disappears (#2903)
* file acquisition: don't bubble error when tailed file disappears
* don't call t.Kill()
* lint (whitespace)
2024-03-18 11:25:45 +01:00
Manuel Sabban
fd2bb8927c
Fix rpm build (#2894)
* fix rpm build
2024-03-15 14:36:34 +01:00
Laurence Jones
e9b0f3c54e
wip: fix unix socket error (#2897) 2024-03-14 15:36:47 +00:00
mmetc
a6b0e58380
CI: bump github actions (#2895) 2024-03-14 14:04:45 +01:00
mmetc
caca4032d1
lapi: log error "can't sinchronize with console" only if papi is enabled (#2896) 2024-03-14 14:03:43 +01:00
blotus
7dd86e2b95
add cron as a suggested package (#2799) 2024-03-14 14:02:53 +01:00
dependabot[bot]
06bebdeac7
Bump google.golang.org/protobuf from 1.31.0 to 1.33.0 (#2893)
Bumps google.golang.org/protobuf from 1.31.0 to 1.33.0.
2024-03-14 14:01:09 +01:00
blotus
742f5e8cda
[appsec] delete api key header before processing the request (#2890) 2024-03-14 14:00:39 +01:00
mmetc
6c042f18f0
LAPI: local api unix socket support (#2770) 2024-03-14 10:43:02 +01:00
Thibault "bui" Koechlin
2a7e8383c8
fix #2889 (#2892)
* fix #2889
2024-03-13 17:20:06 +01:00
Thibault "bui" Koechlin
b1c09f7512
acquisition : take prometheus level into account (#2885)
* properly take into account the aggregation level of prometheus metrics in acquisition
2024-03-13 14:57:19 +01:00
Manuel Sabban
bd785ede15
Fix armhf (#2886)
* armhf compile fix
2024-03-12 17:33:22 +01:00
Manuel Sabban
1a56a0e0b9
armhf fix for getfstype (#2884)
* armhf fix for getfstype
2024-03-12 14:33:10 +01:00
mmetc
49e0735b53
cscli tests + fix bouncer/machine prune (#2883)
* func tests: "cscli config feature-flags"
* func tests: "cscli bouncers list"
* func tests + fix: "cscli bouncers/machines prune"
* lint
2024-03-11 13:14:01 +01:00
blotus
6daaab1789
support both scope and scopes parameter in decisions filter (#2882) 2024-03-11 10:54:40 +01:00
blotus
e8ff13bc17
appsec: get the original UA from headers (#2809) 2024-03-08 15:04:36 +01:00
mmetc
a928b4d001
bump dependencies for geoip db / lookup (#2880) 2024-03-08 14:22:23 +01:00
blotus
44ec3b9e01
file acquis: add mutex to protect access to the internal tail map (#2878) 2024-03-08 13:56:59 +01:00
mmetc
6c5e8afde9
pkg/cwhub: download data assets to temporary files to avoid partial fetch (#2879) 2024-03-08 10:55:30 +01:00
mmetc
1eab943ec2
crowdsec: remove warning if prometheus port is taken during cold logs processing (#2857)
i.e. remove a "Warning: port is already in use" because it's probably LAPI
2024-03-07 14:36:28 +01:00
mmetc
8108e4156d
CI: "make generate" target; use ent 0.12.5 (#2871)
* CI: "make generate" target; pin tool versions
* use ent 0.12.5
* fix make help
* fix model generation target; re-run swagger
2024-03-07 14:25:25 +01:00
blotus
5731491b4e
Auto detect if reading logs or storing sqlite db on a network share (#2241) 2024-03-07 14:04:50 +01:00
mmetc
98560d0cf5
bin/crowdsec: avoid writing errors twice when log_media=stdout (#2876)
* bin/crowdsec: avoid writing errors twice when log_media=stdout
simpler, correct hook usage
* lint
2024-03-07 12:29:10 +01:00
mmetc
e611d01c90
cscli: hide hashed api keys (#2874)
* cscli: hide hashed api keys
* lint
2024-03-06 14:27:05 +01:00
mmetc
5356ccc6cd
cron: spread server load when upgrading hub and data files (#2873) 2024-03-06 13:42:57 +01:00
mmetc
d8877a71fc
lp metrics: collect datasources and console options (#2870) 2024-03-05 14:56:14 +01:00
mmetc
e7ecea764e
pkg/csconfig: use yaml.v3; deprecate yaml.v2 for new code (#2867)
* pkg/csconfig: use yaml.v3; deprecate yaml.v2 for new code
* yaml.v3: handle empty files
* Lint whitespace, errors
2024-03-04 14:22:53 +01:00
mmetc
41b43733b0
fix: log stack trace while computing metrics (#2865) 2024-03-01 10:52:35 +01:00
mmetc
8e9e091656
systemd: check configuration before attempting reload (#2861) 2024-02-26 13:44:40 +01:00
mmetc
a23fe06d68
remove dependencies on enescakir/emoji, gotest.tools (#2837)
* wrap emoji package in pkg/emoji
* remove dependency on enescakir/emoji
* remove dependency on gotest.tools
* lint (whitespace)
2024-02-23 16:05:01 +01:00
mmetc
4bf640c6e8
refact pkg/apiserver (auth helpers) (#2856) 2024-02-23 14:03:50 +01:00
mmetc
e34af358d7
refact cscli (globals) (#2854)
* cscli capi: avoid globals, extract methods
* cscli config restore: avoid global
* cscli hubtest: avoid global
* lint (whitespace, wrapped errors)
2024-02-23 10:37:04 +01:00
Laurence Jones
0df8f54fbb
Add unix socket option to http plugin, we have to use this in conjunction with URL parameter as we dont know which path the user wants so if they would like to communicate over unix socket they need to use both, however, the hostname can be whatever they want. We could be a little smarter and actually parse the url, however, increasing code when a user can just define it correctly make no sense (#2764) 2024-02-22 11:18:29 +00:00
mmetc
8da490f593
refact pkg/apiclient (#2846)
* extract resperr.go
* extract method prepareRequest()
* reset token inside mutex
2024-02-22 11:42:33 +01:00
mmetc
3e3df5e4c6
refact "cscli config", remove flag "cscli restore --old-backup" (#2832)
* refact "cscli config show"
* refact "cscli config backup"
* refact "cscli confgi show-yaml"
* refact "cscli config restore"
* refact "cscli config feature-flags"
* cscli restore: remove 'old-backup' option
* lint (whitespace, wrapped errors)
2024-02-22 11:04:36 +01:00
Laurence Jones
f3ea88f64c
Appsec unix socket (#2737)
* Appsec socket

* Patch detection of nil listenaddr

* Allow TLS unix socket

* Merge diff issue
2024-02-21 13:40:38 +00:00
mmetc
e976614645
cscli metrics: rename buckets -> scenarios (#2848)
* cscli metrics: rename buckets -> scenarios
* update lint configuration
* lint
2024-02-15 14:34:12 +01:00
Thibault "bui" Koechlin
717fc97ca0
add SetMeta and SetParsed helpers (#2845)
* add SetMeta and SetParsed helpers
2024-02-14 13:38:40 +01:00
he2ss
97c441dab6
implement highAvailability feature (#2506)
* implement highAvailability feature
---------

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2024-02-14 12:26:42 +01:00
mmetc
8de8bf0e06
pkg/hubtest: extract methods + consistent error handling (#2756)
* pkg/hubtest: extract methods + consistent error handling
* lint
* rename variables for further refactor
2024-02-14 11:53:12 +01:00
mmetc
2bbf0b4762
re-generate ent code (#2844) 2024-02-14 11:19:13 +01:00
mmetc
45571cea08
use go 1.21.7 (#2830) 2024-02-14 09:47:12 +01:00
mmetc
d34fb7e8a8
log processor: share apiclient in output goroutines (#2836) 2024-02-13 14:22:19 +01:00
mmetc
4561eb787b
bats: color formatter in CI (#2838) 2024-02-12 20:15:16 +01:00
mmetc
a6a4d460d7
refact "cscli console" (#2834) 2024-02-12 11:45:58 +01:00
mmetc
eada3739e6
refact "cscli notifications" (#2833) 2024-02-12 11:40:59 +01:00
blotus
bdecf38616
update codeql action to v3 (#2822) 2024-02-12 11:33:44 +01:00
mmetc
5c83695177
refact "cscli explain" (#2835) 2024-02-12 11:23:17 +01:00
mmetc
2853410576
refact "cscli alerts" (#2827) 2024-02-09 17:51:29 +01:00
mmetc
58a1d7164f
refact "cscli lapi" (#2825) 2024-02-09 17:39:50 +01:00
blotus
332af5dd8d
appsec: split return code for bouncer and user (#2821) 2024-02-09 14:39:34 +01:00
Laurence Jones
fa56d35a48
[Loki] Set headers/basic auth if set for queryRange (#2815) 2024-02-09 14:37:49 +01:00
mmetc
df159b0167
update calls to deprecated x509 methods (#2824) 2024-02-09 13:55:24 +01:00
mmetc
af1df0696b
refact cscli metric processing (#2816)
* typos
* refact cscli metric processing
* lint
2024-02-07 11:10:25 +01:00
Thibault "bui" Koechlin
3208a40ef3
Dedicated whitelist metrics (#2813)
* add proper whitelist metrics : both its own table and an extension to acquis metrics to track discarded/whitelisted lines
2024-02-06 18:04:17 +01:00
mmetc
4e724f6c0a
refact "cscli" root cmd (#2811)
* refact "cscli" root cmd
* lint (naming, imports, whitespace)
2024-02-06 10:50:28 +01:00
mmetc
fdc525164a
refact "cscli metrics" part 3 (#2807) 2024-02-06 10:07:05 +01:00
mmetc
81acad0d66
refact "cscli metrics" part 2 (#2806) 2024-02-02 10:40:55 +01:00
mmetc
5ff8a03195
refact "cscli metrics" par 1 (#2805) 2024-02-02 09:45:03 +01:00
mmetc
4160bb8102
refact "cscli decisions" (#2804)
* refact "cscli decisions"
* CI: relax mysql test timing
* lint
2024-02-01 22:36:21 +01:00
mmetc
f5fbe4a200
refact "cscli dashboard" (#2803) 2024-02-01 17:27:15 +01:00
mmetc
45c669fb65
refact "cscli papi" (#2802) 2024-02-01 17:27:00 +01:00
mmetc
825c08aa9d
refact "cscli simulation" (#2801) 2024-02-01 17:26:46 +01:00
mmetc
af14f1085f
refact "cscli <itemtype>" (#2782) 2024-02-01 17:26:06 +01:00
mmetc
e6f5d157b8
refact "cscli hub" (#2800) 2024-02-01 17:25:29 +01:00
mmetc
785fce4dc7
refact "cscli alerts" (#2778) 2024-02-01 17:24:00 +01:00
mmetc
17db4cb970
refact "cscli machines" (#2777) 2024-02-01 17:22:52 +01:00
mmetc
4192af30d5
refact "cscli bouncers" (#2776) 2024-01-31 12:40:41 +01:00
mmetc
3921c3f480
CI: rename workflows, improve docker build and tests (#2798) 2024-01-31 12:07:27 +01:00
mmetc
6507e8f4cd
cscli: don't print use_wal warning (#2794) 2024-01-30 11:07:53 +01:00
mmetc
66544baa7f
CI: workflow improvements (#2792)
- update deprecated action dependencies
- remove go version matrix (track stable version)
- optimize docker builds
- comments, renamed workflow
2024-01-30 10:20:25 +01:00
mmetc
311dfdee1f
Decouple docker image from package release (#2791)
- entry point fixes for 1.6.0
 - correctly override BUILD_VERSION argument
 - manual release workflow
2024-01-29 22:05:26 +01:00
mmetc
91b0fce955
option to override hub url template. for testers only. (#2785) 2024-01-25 12:53:20 +01:00
mmetc
532e97e00f
disable docker flavor test (#2783) 2024-01-25 09:58:48 +01:00
mmetc
d7116a4a6f
disable docker flavor test (#2781) 2024-01-25 00:03:56 +01:00
Laurence Jones
2fb6f209aa
Update docker_start.sh (#2780)
* Update docker_start.sh

* disable 'set -e' in docker entrypoint

---------

Co-authored-by: marco <marco@crowdsec.net>
2024-01-24 22:51:33 +00:00
Manuel Sabban
3f9e8e81e6
fix some bats tests (#2775) 2024-01-24 19:51:55 +01:00
mmetc
8c75efdb2a
lint: disallow naked returns (#2771) 2024-01-24 17:31:34 +01:00
mmetc
f75cdeb239
lint: enalble linter "wastedassign" (#2772) 2024-01-24 17:31:11 +01:00
mmetc
4b8e6cd780
appsec: avoid nil dereference (#2773) 2024-01-23 09:32:41 +01:00
blotus
84606eb207
Appsec hooks fixes (#2769) 2024-01-22 13:33:20 +01:00
mmetc
dc698ecea8
log "loading papi client" only if papi is enabled (#2762) 2024-01-22 13:25:36 +01:00
mmetc
455acf7c90
lapi/papi: when receiving alerts, log and discard invalid addr/range (#2708)
https://github.com/crowdsecurity/crowdsec/issues/2687
2024-01-22 12:24:26 +01:00
Thibault "bui" Koechlin
19d36c0fb2
Support console options in console enroll (#2760)
* make dev.yaml has a valid/default console path

* simplify and make more consistent help message about console opts

* allow enroll to specify options to enable

* allow 'all' shortcut for --enable
2024-01-19 15:49:00 +01:00
mmetc
ce32fc019e
func tests improvements (#2759)
* faster reload test
* decode-jwt script
* replace 'netcat' requirement with python script
* fix lapi status test
2024-01-19 13:55:28 +01:00
mmetc
6ffb68322f
pkg/hubtest: split hubtest_item.go (#2753)
* split hubtest_item.go, update linter config
* extract loops to methods
* split installParser
* split installScenario
* split installPostoverflow
* split installAppsecRule
* generalize method installHubItems()
2024-01-18 11:09:14 +01:00
mmetc
fa8d5b6992
post-install: reduce verbosity (#2751)
* post install: avoid message "no such file or directory" when looking for logs
* post install: avoid info and warning messages when registering to capi
* lint (backtick)
2024-01-18 09:20:52 +01:00
mmetc
5d0d5ac9c9
CI: enable code complexity linters (#2752) 2024-01-17 21:57:45 +01:00
mmetc
d760b401e6
apiclient: split auth_key, auth_retry, auth_jwt (#2743) 2024-01-17 15:08:41 +01:00
Laurence Jones
4df4e5b3bf
[parser/scenarios] defer yaml file closure (#2689)
* Defer close the fd's
* Convert fatals into return with errors
2024-01-17 12:09:01 +01:00
AlteredCoder
70e8377c0d
Fix appsec evt send order (#2749) 2024-01-17 11:59:31 +01:00
Thibault "bui" Koechlin
685cda545b
fix the reload process for appsec (#2750) 2024-01-17 11:54:44 +01:00
Laurence Jones
f156f178cd
Update governance.yml (#2748) 2024-01-16 16:49:14 +00:00
AlteredCoder
a52f1b75ff
Don't close the body of the request (#2747) 2024-01-16 17:23:35 +01:00
blotus
421ef3bf9c
add cpu-profile flag (#2723) 2024-01-16 11:40:29 +01:00
mmetc
08794c5b6d
[appsec] waf tester (#2746) 2024-01-16 11:39:23 +01:00
AlteredCoder
a65223aa5b
Add original http request to hooks (#2740) 2024-01-16 10:33:44 +01:00
mmetc
24b5e8f100
Fix #2733 "cscli hang forever when i try to delete a decision" (#2745) 2024-01-16 09:16:21 +01:00
mmetc
c6e4762f28
apiserver: remove cached field isEnrolled (#2744)
not worth it just to avoid parsing a string twice
2024-01-16 09:14:33 +01:00
blotus
6acbcb0a33
Various appsec fixes (#2742) 2024-01-15 16:38:11 +01:00
blotus
e452dc80bd
ignore native modsec rules that were either pass or allow (#2684) 2024-01-15 15:12:02 +01:00
blotus
fd309134a2
log death reason of file reader if available (#2721) 2024-01-15 15:00:49 +01:00
mmetc
48f011dc1c
apiclient/apiserver: lint/2 (#2741) 2024-01-15 12:38:31 +01:00
mmetc
75d8ad9798
apiclient/apiserver: lint (#2739) 2024-01-15 11:44:38 +01:00
mmetc
03bb194d2c
Docker: allow setting BUILD_VERSION as a build argument (#2736)
* Docker: allow setting BUILD_VERSION as a build argument
* CI: don't attempt to publish docker images outside of crowdecurity org
* use go 1.21.6 for docker and windows too
2024-01-15 11:05:27 +01:00
Thibault "bui" Koechlin
6ca053ca67
fix #2720 #2719 (#2724)
* fix order of display of parsers

* add a --no-clean opt
2024-01-15 09:16:03 +01:00
mmetc
1e0bcedef5
Ignore missing console/context.yaml if not explicitly required by config.yaml (#2726) 2024-01-12 16:29:04 +01:00
mmetc
733f5e165b
csprofiles: fix default decision duration, lint (#2703)
* return nil with errors
* errors.Wrap -> fmt.Errorf
* var -> const
* fix default decision duration
* lint (whitespace)
2024-01-12 15:18:59 +01:00
mmetc
0ef5f20aa7
bin/crowdsec: avoid writing errors twice when log_media=stdout (#2729)
* bin/crowdsec: avoid writing errors twice when log_media=stdout
* lint
2024-01-12 14:44:09 +01:00
mmetc
fca8883cd9
cscli capi status -> message for missing credentials (#2730)
* cscli capi status -> message for missing credentials
* lint
2024-01-12 14:41:36 +01:00
Thibault "bui" Koechlin
896dfefcdf
[appsec] implement count transformation (#2698)
* implement count transfo
2024-01-12 14:30:08 +01:00
mmetc
6960419a2e
Remove redundant file check for capi_whitelists_path (#2728) 2024-01-12 14:17:01 +01:00
Thibault "bui" Koechlin
adba4e2a2f
fix multizone multivar (#2727) 2024-01-12 10:11:13 +01:00
mmetc
aa4f02c798
wizard: while installing, don't hide hub download/timeout errors (#2710)
* wizard: while installing, don't hide hub download/timeout errors
* lint, whitespace
2024-01-11 16:30:42 +01:00
mmetc
260f5a7992
pkg/cwhub: improve error messages (#2712)
* pkg/cwhub: improve error messages
* lint
2024-01-11 10:28:58 +01:00
mmetc
0f722916b8
use go 1.21.6 (#2714)
* use go 1.21.6
2024-01-11 09:40:51 +01:00
mmetc
a59ae61441
Makefile: use GO macro if set, to check for version (#2706) 2024-01-11 09:25:33 +01:00
mmetc
437a97510a
apiclient: handle 0-byte error response (#2716)
* apiclient: correctly handle 0-byte response
* lint
2024-01-10 12:00:22 +01:00
mmetc
f306d59016
logging: full timestamp with timezone in crowdsec.log (#2707)
RFC3339 = "2006-01-02T15:04:05Z07:00" (same as /var/log/syslog)
2024-01-08 21:20:25 +01:00
blotus
58f91dc951
update coraza (#2705) 2024-01-08 19:44:24 +01:00
AlteredCoder
bd47dac6a3
Fix #2697 (#2702)
* Print also sec lang rules in cscli inspect
2024-01-08 16:44:05 +01:00
blotus
5d5a1117e1
Send installed appsec rules as part of the scenarios on login (#2704) 2024-01-08 14:33:53 +01:00
Sebastien Blot
ecd1a8bfed
Revert "Send installed appsec rules as part of the scenarios on login"
This reverts commit f99f003a50.
2024-01-08 10:54:39 +01:00
Sebastien Blot
f99f003a50
Send installed appsec rules as part of the scenarios on login 2024-01-08 10:54:07 +01:00
mmetc
5622ac8338
CI: enable testifylint (#2696)
- reverse actual and expected values
 - use assert.False, assert.True
 - use assert.Len, assert.Emtpy
 - use require.Error, require.NoError
 - use assert.InDelta
2024-01-05 15:26:13 +01:00
mmetc
da746f77d5
apiserver/apiclient: compact tests (#2694)
* apiserver/apiclient: compact tests
* update golangci-lint configuration
2024-01-04 17:10:36 +01:00
Thibault "bui" Koechlin
1c03fbe99e
minor waf fixes (#2693) 2024-01-03 17:19:48 +01:00
mmetc
a504113186
lint (wsl) (#2692) 2024-01-03 10:55:41 +01:00
mmetc
2a2b09b52a
cwhub: install --force repair tainted, non-installed items (#2686) 2024-01-03 10:08:45 +01:00
mmetc
ca784b147b
test and log fixes (#2690)
* cscli inspect: suggest --diff if an item is tainted
* appropriate warning, or error if context configuration file is empty
* fix user/group lookup unit test
* fix: allow hub upgrade --force with local items
* fix pkg/parser lookup for 8.8.8.8
* fix func test
* fix hubtests: machines add --force
2024-01-03 09:33:52 +01:00
blotus
b6f272d09a
always set the transaction in the current request (#2682) 2023-12-22 11:44:06 +01:00
blotus
a62e28fdfb
always set inband transaction even if we have no rules (#2681) 2023-12-22 10:18:35 +01:00
Laurence Jones
bc9bfa81b2
[notifications] fix segfault because url is not loaded (#2679) 2023-12-21 12:27:34 +00:00
mmetc
162768bdec
Bump golangci-lint run to 1.55, update defaults (#2677)
The plan is to enable linters first, then fix issues types one by one.
2023-12-21 12:30:20 +01:00
Laurence Jones
2212c2f847
[notifications] Fix bug, list show non active (#2678)
* Fix bug, show non active notifications and sort based on profiles

* diff fix
2023-12-21 11:16:54 +00:00
blotus
33e3fdabe4
Appsec additional fixes (#2676) 2023-12-21 11:51:04 +01:00
Zafer Balkan
e1932ff01e
Used asterisk for Defender Firewall log name (#2671)
Log name is configurable. MD Docs recommend a log file per profile: https://learn.microsoft.com/en-us/windows/security/operating-system-security/network-security/windows-firewall/configure-logging?tabs=intune
2023-12-20 10:28:40 +01:00
Manuel Sabban
052accd6bb
welcome message when installing packages (#2672)
* welcome message when installing packages
2023-12-20 09:44:10 +01:00
mmetc
240f057f95
postinst: update check for enabled lapi (#2674) 2023-12-19 21:46:34 +01:00
mmetc
6e34d609b7
cscli: silence cwhub logger for non-hub related commands (#2675) 2023-12-19 17:20:09 +01:00
mmetc
fd22bb5ec2
CI: update test dependencies (#2668) 2023-12-19 15:28:30 +01:00
mmetc
1530d93fc1
Update localstack services + loki (dev and CI) (#2649) 2023-12-19 15:27:04 +01:00
dependabot[bot]
e0e9e3ef16
Bump golang.org/x/crypto from 0.16.0 to 0.17.0 (#2670)
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.16.0 to 0.17.0.
- [Commits](https://github.com/golang/crypto/compare/v0.16.0...v0.17.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-12-19 09:45:53 +01:00
mmetc
44eb4d4a94
Makefile: "make help" target, remove obsolete "notification-email" target (#2282) 2023-12-18 10:13:08 +01:00
mmetc
822fcdacbb
fflags: don't print deprecation warning if there is no message (papi) (#2666) 2023-12-18 09:35:57 +01:00
mmetc
08694adf1b
lint (errorlint) (#2644) 2023-12-18 09:35:28 +01:00
mmetc
c2c173ac7e
Parallel hubtests (#2667)
* generate hub tests in python
* run hub tests in 3 batches at the same time (hardcoded)
2023-12-15 18:30:20 +01:00
mmetc
a79fcaf378
Add "taintedBy" and "--diff" flag to cscli... inspect (#2665)
* "cscli inspect" reports tainted sub-items
* cscli... inspect --diff
* unified diff
* option --diff --rev
* tainted message
* correctly report multiple taint reasons
2023-12-15 15:27:22 +01:00
blotus
bc3a179af9
Add env vars to install/remove appsec-{configs,rules} in docker image (#2664) 2023-12-14 16:54:12 +01:00
blotus
9b07e1f7ce
update scenarios and parsers constraints (#2663) 2023-12-14 16:34:51 +01:00
mmetc
a851e14c88
improve deprecation message with file location (#2662)
* better "lapi context" messages
* func tests: include all items in hub_purge_all
* docker + tests: update yq
2023-12-14 16:11:11 +01:00
AlteredCoder
a941576acc
Improvement to run hubtest for appsec in docker (#2660) 2023-12-14 16:05:16 +01:00
mmetc
89f704ef18
light pkg/api{client,server} refact (#2659)
* tests: don't run crowdsec if not necessary
* make listen_uri report the random port number when 0 is requested
* move apiserver.getTLSAuthType() -> csconfig.TLSCfg.GetAuthType()
* move apiserver.isEnrolled() -> apiclient.ApiClient.IsEnrolled()
* extract function apiserver.recoverFromPanic()
* simplify and move APIServer.GetTLSConfig() -> TLSCfg.GetTLSConfig()
* moved TLSCfg type to csconfig/tls.go
* APIServer.InitController(): early return / happy path
* extract function apiserver.newGinLogger()
* lapi tests
* update unit test
* lint (testify)
* lint (whitespace, variable names)
* update docker tests
2023-12-14 14:54:11 +01:00
mmetc
67cdf91f94
Short build tag in version number (#2658)
* use short commit hash in version number
* var -> const
* cscli: extract version.go, doc.go
* don't repeat commit hash in version number
2023-12-14 09:16:38 +01:00
Thibault "bui" Koechlin
51f70e47e3
Minor improvements to hubtest and appsec component (#2656) 2023-12-13 17:45:56 +01:00
mmetc
12d9fba4b3
cscli machines: lint + write output to stdout instead of log (#2657)
* feedback on stdout, not log.Info
* rename parameters to silence warnings from "unusedparams"
* debian postinst: skip duplicate warnings with 'cscli machines add'
* rpm postinst: skip duplicate warnings in 'cscli machines add'
* update func tests
* debian prerm: if dashboard remove fails, explain it's ok
* debian prerm: suppress warnings about wal, capi when attempting to remove the dashboard
* wizard.sh: log format like crowdsec
2023-12-13 15:43:46 +01:00
Manuel Sabban
6eabb461ce
copy debian behavior for now (#2655) 2023-12-12 13:22:15 +01:00
Laurence Jones
b1c9717e21
[http plugin] Add capath, certpath, keypath to load custom certs (#2634)
* Add cacert, certpath, certkey to http plugin to load custom cetificates

* rename func to get tls client as it doesnt make sense calling it api

* Fix is capath is empty we should return the current certificates

* Remove comment
2023-12-12 10:36:45 +00:00
he2ss
4a4b309790
docker: add new env var to enable console_management (#2599) 2023-12-12 10:24:03 +01:00
mmetc
acd2a14dc9
docker: add -slim variant to ghcr.io (#2653) 2023-12-11 13:51:00 +01:00
mmetc
c10aad79d9
cscli refact / encapsulate methods for capi, hubtest, dashboard, alerts, decisions, simulation (#2650) 2023-12-11 10:32:54 +01:00
mmetc
1b4ec66148
fix package tests for 1.5.6-rc2 (#2652)
* fix go deps for test
* fix package tests for 1.5.6-rc2
* fix context func tests
* docker: pin build image version for alpine

---------

Co-authored-by: sabban <github@sabban.eu>
2023-12-11 10:07:09 +01:00
blotus
04f3dc09f9
remove PAPI feature flag (#2601) 2023-12-08 14:55:45 +01:00
Manuel Sabban
c707b72b03
fix lapi credentials creation for debian package (#2646)
* fix lapi credentials creation for package s
---------

Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2023-12-08 12:10:23 +01:00
mmetc
84cbff16d4
restrict file permissions from "machines add" (#2648) 2023-12-08 10:51:15 +01:00
AlteredCoder
b1f85693c2
Appsec improvement and fixes after merge (#2645) 2023-12-08 10:25:00 +01:00
mmetc
518c7f178a
update dependency on aws sdk (#2647) 2023-12-08 10:07:53 +01:00
mmetc
4acb4f8df3
cwhub: context type (#2631)
* add hub type "context"
* cscli lapi: log.Fatal -> fmt.Errorf; lint
* tests for context.yaml
* load console context from hub
* original & compiled context
* deprecate "cscli lapi context delete"
$ cscli lapi context delete
Command "delete" is deprecated, please manually edit the context file.
* cscli completion: add appsec-rules, appsec-configs, explain, hubtest
2023-12-07 16:20:13 +01:00
mmetc
3e86f52250
cscli refact - encapsulation with types (#2643)
* refactor type cliHub, cliBouncers, cliMachines, cliPapi, cliNotifications, cliSupport, type cliExplain
2023-12-07 14:36:35 +01:00
Thibault "bui" Koechlin
8cca4346a5
Application Security Engine Support (#2273)
Add a new datasource that:
- Receives HTTP requests from remediation components
- Apply rules on them to determine whether they are malicious or not
- Rules can be evaluated in-band (the remediation component will block the request directly) or out-band (the RC will let the request through, but crowdsec can still process the rule matches with scenarios)

The PR also adds support for 2 new hub items:
- appsec-configs: Configure the Application Security Engine (which rules to load, in which phase)
- appsec-rules: a rule that is added in the Application Security Engine (can use either our own format, or seclang)

---------

Co-authored-by: alteredCoder <kevin@crowdsec.net>
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
Co-authored-by: Marco Mariani <marco@crowdsec.net>
2023-12-07 12:21:04 +01:00
mmetc
90d3a21853
CI: use go 1.21.5 (#2640)
* use go 1.21.5
* Simpler go:build directives
2023-12-06 12:38:36 +01:00
mmetc
1ab4487b65
cscli hub list: show only non-empty tables with -o human
* agent config: remove unused LintOnly bool
* Item.IsLocal() -> Item.State.IsLocal(); split method InstallStatus()
* cscli hub list: show only non-empty tables with -o human
2023-12-05 13:38:52 +01:00
mmetc
486f96e7ac
cscli context detect: fix nil dereference (#2635)
* cscli context detect: fix nil dereference
* Remove log.warning for missing pattern
2023-12-05 12:08:35 +01:00
mmetc
8bb7da3994
docker tests: force local machine creation (#2636)
This is required from 1.5.6 to overwrite the local credentials file
2023-12-05 11:52:04 +01:00
mmetc
0f3ae64062
cscli config show: pretty print with package "litter" (#2633) 2023-12-05 10:38:21 +01:00
mmetc
0c4093dcca
Test for acquisition errors in crowdsec -t (#2629) 2023-12-04 23:09:42 +01:00
mmetc
23968e472d
Refact bouncer auth (#2456)
Co-authored-by: blotus <sebastien@crowdsec.net>
2023-12-04 23:06:01 +01:00
mmetc
a5ab73d458
cscli machines add: don't overwrite existing credential file (#2625)
* cscli machines add: don't overwrite existing credential file
* keep old behavior with --force
Now --force is used both to override the replacement of and existing machine,
and an existing credentials file. To retain the old behavior, the
existence of the file is only checked for the default configuration, not
if explicitly specified.
2023-12-04 22:59:52 +01:00
Laurence Jones
f8755be9cd
Fix formt on documentation (#2577)
When generating decisions import docusarus v3 now does not allow `{` without escaping this adds escaping
2023-12-04 15:52:14 +00:00
Laurence Jones
d1bfaddb69
[Plugin] Pass down ctx and use it (#2626)
* Pass down cancellable context and update http plugin

* Use context where we can
2023-12-04 12:05:26 +00:00
Laurence Jones
bfc92ca1c5
[Explain] Ignore blank lines as crowdsec will anyways (#2630)
* Ignore blank lines within file and stdin

* change cleanup to be persistent postrun so if we exit early it always cleans

* When using log flag we should add a newline so we know where EOF is

* Inverse the check for log line since we dont want to modify the line itself

* Wrap run explain with a function that returns the error after cleaning up

* Wrap run explain with a function that returns the error after cleanup

* Use a defer iif instead of global var

* Add invalid len input to err count so it more obvious what is happening

---------

Co-authored-by: Manuel Sabban <github@sabban.eu>
2023-12-04 11:48:12 +00:00
Laurence Jones
ed3d501081
[Metabase] QOL Changes and chown wal files (#2627)
* Add detection sqlie wal for dashboard chown

* Lean it down a little

* Change to for loop with extensions

* Keep existing uid on files incase user is running as a unpriviledge user

* I have no idea 🤷

* Exclude dash.go and update windows

* Update

* Renam

* Remove the os check since we no longer get to this stage for those os's

---------

Co-authored-by: Manuel Sabban <github@sabban.eu>
2023-12-04 10:06:41 +00:00
mmetc
7e5ab344a2
command "cscli hub types" (#2632)
* Command "cscli hub types"; de-duplicate test/bin/preload-hub-items
* don't export Hub.Items -> hub.items
2023-12-01 09:36:38 +01:00
Cristian Nitescu
7c5cbef51a
manage force_pull message for one blocklist (#2615)
* manage force_pull message for one blocklist

* fix info message on force pull blocklist
2023-11-29 11:37:46 +01:00
mmetc
6b0bdc5eeb
Refact pkg/cwhub: fix some known issues and reorganize files (#2616)
* bump gopkg.in/yaml.v3
* test: cannot remove local items with cscli
* test dangling links
* test: cannot install local item with cscli
* pkg/cwhub: reorg (move) functions in files
* allow hub upgrade with local items
* data download: honor Last-Modified header
* fatal -> warning when attempting to remove a local item (allows remove --all)
* cscli...inspect -o yaml|human: rename remote_path -> path
* Correct count of removed items
Still no separate counter for the --purge option, but should be clear enough
2023-11-28 23:51:51 +01:00
mmetc
1aa4fc5949
CI: avoid pipe in makefile, correctly report error in CI when tests fail (#2621)
so we don't assume bash+pipefail for the makefile
2023-11-28 17:10:44 +01:00
blotus
380cbf70a9
force rfc 3339 date format in metrics push (#2402) 2023-11-28 16:30:20 +01:00
Laurence Jones
05c1825622
Add to dump after postoverflow so we can test within hubtest (#2511)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-11-28 13:18:41 +00:00
Laurence Jones
6a61b919e7
[cscli] notifications test command and slight re write (#2391)
* Merge main and apply stash

* Rework some of cscli notif stuff and add a generic test which works with non active profiles

* Update wording

* Fix merge

* Final version

* Cleanup
2023-11-28 13:17:54 +00:00
mmetc
15542b78fb
refact BulkDeleteDecisions (#2308)
Code cleanup and de-duplication.
2023-11-26 22:30:03 +01:00
mmetc
b164373997
update dependencies: k8s apiserver, docker and related (#2476) 2023-11-24 16:20:39 +01:00
mmetc
ffcab0b2bc
Refactor hub management and cscli commands (#2545) 2023-11-24 15:57:32 +01:00
mmetc
32e9eb4be4
Minor dependency updates (#2505)
* update AlecAivazis/survey
* update Masterminds/semver
* update Masterminds/sprig
* update alexliesenfeld/health
* update golang.org/x/net
2023-11-24 15:30:54 +01:00
mmetc
76d4bc7788
cscli bouncers: increase key size, deprecate and ignore --length option (#2531)
the switch to base64 made the keys shorter (24 characters), this PR increases their size to 32 bytes, 42 chars once encoded

Also deprecate the --length option, users can already provide a key
2023-11-24 15:01:13 +01:00
mmetc
ec199162dc
iso8601: use yyyy-mm-dd in log timestamps instead of dd-mm-yyyy (#2564)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-11-24 14:59:28 +01:00
Thibault "bui" Koechlin
1dcf9d1ae1
Improved expr debugger (#2495)
* new expr debugger

---------

Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2023-11-24 11:10:54 +01:00
mmetc
7ffa0cc787
docker: replace cp -an with rsync to allow bind-mount of files in /etc/crowdsec (#2611)
fix for https://github.com/crowdsecurity/crowdsec/issues/2480
2023-11-23 11:08:14 +01:00
blotus
ec53c672dc
Kafka acquisition: warn if no consumer group id and allow to read from a specific partition (#2612) 2023-11-23 10:02:53 +01:00
lperdereau
92f923cfa8
Loki integration #2 (#2306)
* Add support for loki datasource

---------

Co-authored-by: Mathieu Lecarme <mathieu@garambrogne.net>
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-11-22 13:31:39 +01:00
he2ss
947b247a40
kafkaAcquisition: add more debug (#2609)
* kafkaAcquisition: add more debug
2023-11-22 09:35:58 +01:00
blotus
d7ef51e6ba
properly update the cs_syslogsource_parsed_total metric (#2608) 2023-11-22 09:04:23 +01:00
dependabot[bot]
a51bce8f8d
Bump google.golang.org/grpc from 1.56.1 to 1.56.3 (#2566)
Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.56.1 to 1.56.3.
- [Release notes](https://github.com/grpc/grpc-go/releases)
- [Commits](https://github.com/grpc/grpc-go/compare/v1.56.1...v1.56.3)

---
updated-dependencies:
- dependency-name: google.golang.org/grpc
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-11-20 11:55:29 +01:00
mmetc
47eb2e240d
Use go 1.21.4 (#2595) 2023-11-16 11:09:13 +01:00
guangwu
ddd6ee8e42
fix: typo (#2582)
Signed-off-by: guoguangwu <guoguangwu@magic-shield.com>
2023-11-08 09:26:34 +01:00
mmetc
5cd4406f5e
typos/grammar (#2561) 2023-11-07 15:07:36 +01:00
Manuel Sabban
4934fce769
update gantsign.golang name (#2558) 2023-11-07 14:53:14 +01:00
mmetc
272cf543b3
Release action: fix asset upload (#2565) 2023-10-25 14:51:36 +02:00
Laurence Jones
d2d788c5dc
[hubtest] escpae scenario asssert meta keys (#2551) 2023-10-17 15:29:21 +01:00
Thibault "bui" Koechlin
a4dc5053d2
fix null deref in cti calls if key is empty (#2540)
* fix null deref in cti calls if key is empty

* avoid hardcoded error check
2023-10-17 09:34:53 +01:00
Laurence Jones
19de3a8a77
Runtime whitelist parsing improvement (#2422)
* Improve whitelist parsing

* Split whitelist check into a function tied to whitelist, also since we check node debug we can make a pointer to node containing whitelist

* No point passing clog as an argument since it is just a pointer to node we already know about

* We should break instead of returning false, false as it may have been whitelisted by ips/cidrs

* reimplement early return if expr errors

* Fix lint and dont need to parse ip back to string just loop over sources

* Log error with node logger as it provides context

* Move getsource to a function cleanup some code

* Change func name

* Split out compile to a function so we can use in tests. Add a bunch of tests

* spell correction

* Use node logger so it has context

* alternative solution

* quick fixes

* Use containswls

* Change whitelist test to use parseipsource and only events

* Make it simpler

* Postoverflow tests, some basic ones to make sure it works

* Use official pkg

* Add @mmetc reco

* Add @mmetc reco

* Change if if to a switch to only evaluate once

* simplify assertions

---------

Co-authored-by: bui <thibault@crowdsec.net>
Co-authored-by: Marco Mariani <marco@crowdsec.net>
2023-10-16 10:08:57 +01:00
Laurence Jones
e7ad3d88ae
Clear up some community confusion (#2543) 2023-10-16 10:08:41 +01:00
Thibault "bui" Koechlin
3cd4847093
sort map keys when generating asserts (#2494)
* sort map keys when generating asserts
2023-10-16 09:54:19 +02:00
Laurence Jones
b2a6eb92bf
Dont create 3 maps just pass the same one to expr (#2421) 2023-10-13 22:35:30 +01:00
Laurence Jones
f0cda0406b
Load file only once if specified twice, and bail earlier if type is unknown (#2419) 2023-10-13 22:34:57 +01:00
Laurence Jones
ff7acd3347
Reset grokky once all patterns are compiled as we do not need to hold them in memoory (#2420) 2023-10-13 12:53:42 +01:00
mmetc
a6b55f2b5e
cscli config feeature-flags: point user to the right location of feature.yaml (#2539) 2023-10-13 09:52:51 +02:00
mmetc
a254b436c7
use go 1.12.3 (#2535) 2023-10-12 16:28:24 +02:00
mmetc
3b1563a538
Refact cscli hub / pkg/cwhub (part 6) (#2524)
* hub.ConfigDir -> hub.InstallDir; hub.DataDir -> hub.InstallDataDir
* cleanup GetInstalledItemsAsString()
* lint: ReferenceMissingError -> ErrMissingReference
* lint: parent_dir -> parentDir
* link: export Walker type
* lint: return error last
* lint: shadow
* move around and group variable definitions
2023-10-09 21:33:35 +02:00
mmetc
0ecb6eefee
add missing scenarios in first login when authenticating with TLS (#2454)
* refact jwt:Authenticator
* include scenarios in first login request for machines with tlsAuth
* log.Printf -> log.Infof
* errors.Wrap -> fmt.Errorf
* don't override validation error
* fix test
2023-10-09 15:26:38 +02:00
Manuel Sabban
6e228f3f3f
pkg/cwhub: cleanup in argument call (#2527)
* cleanup in argument call
* update test as well
* cwhub_tests: reduce verbosity and use helpers

---------

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2023-10-09 13:26:34 +02:00
Laurence Jones
28238cb01f
reverse nil statement instead of else (#2530) 2023-10-09 11:36:05 +01:00
Laurence Jones
0dd22e8b93
convert ifelseif to switch (#2529) 2023-10-09 11:23:19 +01:00
mmetc
9ae8bd79c5
Refact pkg/csconfig tests (#2526)
* remove unused method
* whitespace, redundant comments
* use test helpers
* move DumpConsoleConfig() from pkg/csconfig to cscli
* package doc header
* var -> const
* rename ./tests -> ./testdata
* shorter tests with more error checks
* lint/formatting
* use helpers; fix tests that didn't actually test
* lint; rename expectedResult -> expected
2023-10-09 11:10:51 +02:00
blotus
6b5da29e3d
Use a default duration if no duration is provided in a profile (#2520) 2023-10-06 14:43:17 +02:00
Thibault "bui" Koechlin
6c20d38c41
ligten bucket logger (#2523) 2023-10-06 14:42:44 +02:00
mmetc
338141f067
Refact cscli hub / pkg/cwhub (part 5) (#2521)
* remove unused yaml tags
* cscli/cwhub: deduplicate, remove dead code
* log.Fatal -> fmt.Errorf
* deflate utils.go by moving functions to respective files
* indexOf() -> slices.Index()
* ItemStatus() + toEmoji() -> Item.status()
* Item.versionStatus()
* move getSHA256() to loader.go
2023-10-06 13:59:51 +02:00
mmetc
9235f55c47
Refact pkg/cwhub (part 4) (#2518)
* generalize function: GetInstalledItems, GetInstalledItemsAsString
* extracted function itemKey, happy path
* review comments / remove redundant; rename file to remove build tags
* remove unused fields in Item struct
* unix build tag
2023-10-05 09:35:03 +02:00
mmetc
61d4ccbfdd
use go 1.21.1 (#2418)
* use go 1.21.1, require 1.21
* import "slices" from stdlib
* allow codeql to set version number from tags
* codeql: custom WASM build - the automated one can silently fail
2023-10-04 13:01:57 +02:00
mmetc
89028f17cf
Refact pkg/cwhub (part 3) (#2516)
* removed unused error; comment
* rename loop variables
* happy path
* rename loop variables
* extract function, method
* log.Printf -> log.Infof
* tests -> testdata

from "go help test":

The go tool will ignore a directory named "testdata", making it available
to hold ancillary data needed by the tests.

* align tags
* extract function toEmoji
2023-10-04 12:54:21 +02:00
mmetc
3253b16f0f
Refact pkg/cwhub (part 2) (#2513)
* remove globals for walker callback
* extract method getItemInfo()
* code dedup, if/else -> switch
* dedent: happy path
* remove target variable
2023-10-04 11:17:35 +02:00
mmetc
5618ba9f46
cscli: refactor hub commands (#2500) 2023-10-04 10:42:47 +02:00
mmetc
d39131d154
Refact pkg/cwhub (part 1) (#2512)
* wrap errors, whitespace
* remove named return
* reverse CheckSuffix logic, rename function
* drop redundant if/else, happy path
* log.Fatal -> fmt.Errorf
* simplify GetItemMap, AddItem
* var -> const
* removed short-lived vars
* de-duplicate function and reverse logic
2023-10-04 10:34:10 +02:00
mmetc
8b5ad6990d
lint: pkg/cwhub (#2510)
no functional changes
 
 - reformat
 - comments
 - whitespace
 - removed a dot or two in log messages
 - some "var x=y" -> x:=y
2023-10-03 11:20:56 +02:00
mmetc
6dadfcb2ef
refact: simplify hubtest CopyDir() (#2509) 2023-10-03 11:17:02 +02:00
mmetc
7a4796d655
Support Postgres 16 (update entgo.io/ent to 0.12.4) (#2368) 2023-10-02 16:30:09 +02:00
mmetc
cba6de024f
cscli: restore config correctly if acquis.d already exists (#2504) 2023-10-02 13:31:04 +02:00
mmetc
bfda483c0a
fix issue #2499 - nil dereference while using capi whitelists (#2501) 2023-10-02 11:42:17 +02:00
mmetc
3cb9dbdb21
notification-email: configurable timeouts (#2465)
* configurable timeouts
* parse email timeouts as duration string
* add helo_host to email.yaml
* move html and body tags outside of the loops
* added quotes to href=.., and formatting test
2023-09-29 16:59:06 +02:00
Laurence Jones
b8e6bd8c9a
[Explain] s02 can cause panic if empty (#2486)
* Add parsers length check as it can panic is enrich is empty

* Lets get smarter and loop backwards to find last successful stage

* Shorten code

---------

Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-09-29 12:03:56 +01:00
mmetc
95ed308207
cscli setup: accept stdin; fix proftpd detection test and service unmask (#2496) 2023-09-29 12:58:35 +02:00
mmetc
0d1c4c6070
update test dependencies (#2490) 2023-09-29 10:19:55 +02:00
Thibault "bui" Koechlin
8f6659a2ec
fix the float comparison by using Abs(a,b) < 1e-6 approach (IEEE 754). Move the initializiation of expr helpers (#2492) 2023-09-28 17:22:00 +02:00
Laurence Jones
9dba6db676
add alert alias (#2485) 2023-09-23 19:35:02 +01:00
Laurence Jones
37c0c067a8
cscli hubtest whitelist (#2479)
* Initial tests

* Always print whitelist as we can compare if we mess up the opposite way
2023-09-20 16:42:19 +01:00
Thibault "bui" Koechlin
e4dcdd2572
fix include_capi filter (#2478) 2023-09-20 11:56:00 +02:00
mmetc
ac01faf483
strip '=' signs from encoded api keys (#2472)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-09-19 14:00:23 +02:00
Thibault "bui" Koechlin
4c08e1e68c
exclude 'lists' too if we exclude CAPI (#2474) 2023-09-19 13:56:22 +02:00
mmetc
d5b6f2974b
Avoid sending nil body with metrics (#2470) 2023-09-19 13:53:50 +02:00
Laurence Jones
64deeab1ec
Fix PO expr whitelist (#2471) 2023-09-19 12:51:03 +01:00
mmetc
b2212f4225
Use go 1.20.8 (#2473) 2023-09-19 13:21:55 +02:00
Manuel Sabban
ce276d3838
Fix fc38 (#2468)
* fix installation on fc38
2023-09-18 11:54:09 +02:00
blotus
43ef32aa8d
Kafka acquisition: do not create empty events when a read error occurs (#2466) 2023-09-13 13:20:36 +02:00
Thibault "bui" Koechlin
0040569fa9
if 'include capi' is false, only exclude capi alerts instead of assuming they necessarily have attached decisions (#2435) 2023-09-12 11:19:36 +02:00
mmetc
6b9e065764
CI: update pytest-cs - don't remove stopped containers after tests (#2459) 2023-09-12 11:10:22 +02:00
mmetc
d45bec4047
minor log message improvements (#2455) 2023-09-12 11:04:56 +02:00
Laurence Jones
702da0f59a
[enhancement] cscli explain --labels (#2461)
* Add label support for explain and allow user to provide multiple labels

* Change my mind about empty string

* Add debug and im an idiot 😄
2023-09-11 14:18:04 +01:00
mmetc
f02f34d64c
CI: remove explicit cache-dependency-path (#2452)
not required anymore after moving the plugins to cmd/
2023-09-04 16:55:48 +02:00
mmetc
fd94e2c056
refactor alert/decisions insert/update to avoid database locking in bulk operations (#2446) 2023-09-04 14:21:45 +02:00
Laurence Jones
aff80a2863
Add html escape function so it can be invoked from template (#2451) 2023-09-04 09:49:39 +01:00
mmetc
22146eb3e4
fix "cscli console disable --all"; cleanup "cscli console" command (#2444) 2023-08-29 11:44:23 +02:00
mmetc
b562103024
Make: build with debug symbols in func tests or if DEBUG=1; drop BUILD_VENDOR_FLAGS (#2443) 2023-08-28 15:58:26 +02:00
mmetc
25868f27de
option db_client.decision_bulk_size (#2440) 2023-08-25 17:05:17 +02:00
mmetc
0c9943b740
CI: alternate vendor file (xz compression and version number) (#2425) 2023-08-25 17:02:00 +02:00
mmetc
32f196a774
use go 1.20.7 (#2409) 2023-08-25 16:24:04 +02:00
mmetc
c588be0842
golangci-lint: use v1.54, remove unnecessary byte/string conversions (#2438) 2023-08-25 16:22:10 +02:00
mmetc
f2154e362b
update functional tests for build pipeline (#2442) 2023-08-25 16:15:28 +02:00
mmetc
2aa55e9444
move plugins/notifications/* to cmd/notification-* (#2429)
This ensures keeping all dependencies in sync, and simplifies
packaging under freebsd/gentoo/etc because there is a single
vendor directory.
2023-08-24 09:46:25 +02:00
mmetc
e36df40ba7
pkg/types cleanup (#2398)
* move function GetLineCountForFile from pkg/types to cscli
* move ParseDuration from pkg/types to pkg/database
* remove unused types.Profile, types.RemediationProfile
2023-08-24 09:44:46 +02:00
Laurence Jones
86d9384954
Whitelist reason (#2439)
* Update node.go

Dont update whitelist reason if event is whitelisted

* oops
2023-08-23 14:51:37 +01:00
Rasmus
b4d9223625
Update main.go (#2431) 2023-08-22 14:09:53 +02:00
Efren
1ec52431b6
Remove duplicate line (#2432)
Remove duplicate line (60) which is outputting `Configuration Folder` twice in `cscli config show`
2023-08-22 14:09:19 +02:00
mmetc
e8e2ade8f0
remove calls to log.Fatal (#2399)
* remove log.Fatal from scenarios.go
* remove log.Fatal from collections.go
* remove log.Fatal from parsers.go and postoverflows.go
2023-08-16 21:04:46 +02:00
mmetc
6a6501691a
change behavior of flag disable_http_retry_backoff (#2426)
now it does not attempt any retry, instead of attempting all retries
immediately

example: cannot reach LAPI

Before:

$ CROWDSEC_FEATURE_DISABLE_HTTP_RETRY_BACKOFF=true cscli decisions list
ERRO[27-07-2023 10:44:44] error while performing request: dial tcp [::1]:8080: connect: connection refused; 4 retries left
INFO[27-07-2023 10:44:44] retrying in 0 seconds (attempt 2 of 5)
[...]
ERRO[27-07-2023 10:44:44] error while performing request: dial tcp [::1]:8080: connect: connection refused; 1 retries left
INFO[27-07-2023 10:44:44] retrying in 0 seconds (attempt 5 of 5)
ERRO[27-07-2023 10:44:44] error while performing request: dial tcp [::1]:8080: connect: connection refused; 0 retries left
FATA[27-07-2023 10:44:44] Unable to list decisions : performing request: Get "http://localhost:8080/v1/alerts?has_active_decision=true&include_capi=false&limit=100": could not get jwt token: Post "http://localhost:8080/v1/watchers/login": dial tcp [::1]:8080: connect: connection refused

After:

$ CROWDSEC_FEATURE_DISABLE_HTTP_RETRY_BACKOFF=true ./test/local/bin/cscli decisions list
FATA[11-08-2023 16:49:58] unable to retrieve decisions: performing request: Get "http://127.0.0.1:8080/v1/alerts?has_active_decision=true&include_capi=false&limit=100": could not get jwt token: Post "http://127.0.0.1:8080/v1/watchers/login": dial tcp 127.0.0.1:8080: connect: connection refused
2023-08-16 21:04:07 +02:00
mmetc
caaed7c515
Timeout on shutdown while waiting for events to be flushed (#2423) 2023-08-16 21:03:15 +02:00
mmetc
afeb541eac
apic: minor refactoring (#2415)
* apic: minor refactoring

* Add whitelist length check

If user configures the file but fails to define and actual whitelist we should check length to save allocs

* Init with length from file

* extract loop method from ApplyApicWhitelists

* pass pointer

* extract loop method updateBlocklist

---------

Co-authored-by: Laurence Jones <laurence.jones@live.co.uk>
2023-08-10 13:03:47 +02:00
Laurence Jones
93c22f29cf
Unmarshal Json (#2414)
Log the actual line that caused an error to help debugging
2023-08-09 09:42:08 +01:00
mmetc
0f319b31fd
update pytest dependencies (#2407) 2023-08-09 00:49:52 +02:00
Manuel Sabban
d6361d0a40
conditional overflow doesn't overflow on capacity (#2412)
* conditional overflow doesn't overflow on capacity

* typo
2023-08-08 16:12:50 +01:00
mmetc
cd9d8f309d
CI: increase test sleep to fix flaky acquisition/file test under win (#2410)
* CI: increase test sleep to attempt fix for flaky windows acquitition/file test

* wip
2023-08-08 16:11:32 +02:00
Laurence Jones
0334a9afe8
Add method name to child logger so we can see which function is erroring when in enrichers (#2411) 2023-08-08 13:38:11 +01:00
AlteredCoder
31c5727a90
Simplify context add (#2408) 2023-08-04 16:50:35 +02:00
mmetc
644c767019
cscli decisions list -o json => [] instead of null; same for alerts (#2397) 2023-08-03 12:51:50 +02:00
Laurence Jones
6ba682a32f
Update bouncers.go (#2404)
Fix wrong short
2023-08-03 11:26:08 +01:00
Manuel Sabban
1d5baa657f
should fix the rpm build (#2396) 2023-08-01 08:20:39 +02:00
Manuel Sabban
2cb7b0bee6
Fix unit file after modification (#2395)
* fix service file for rpm packages build
2023-07-31 16:57:23 +02:00
Laurence Jones
a18df9c3bb
Add bouncers prune command (#2379)
* Add bouncers prune command

* No point overloading functions

* Add prune to list of commands

* change all short desc to be similar, and made it really really clear when pruning it is not recoverable

* Dont use log. and dont return error on user input to abort
2023-07-28 15:37:39 +01:00
mmetc
ffadd42779
update dependency on go-cs-lib; drop the pkg/ part (#2393) 2023-07-28 16:35:08 +02:00
Laurence Jones
55247cd46a
Add machines prune command (#2011)
* Add machines prune command

* Fix scope variable for naming scheme

* Add some freshness and add new features

* Fix force and fix duration if less than 60

* Allow duration to be more readable

* Fix description

* Improve func wording and make int machines length

* No point overloading functions

* Add prune to list of commands

* Check if GID is already the group if so no need to chown

* Revert "Check if GID is already the group if so no need to chown"

This reverts commit c7cef1773e.

* change all short desc to be similar, and made it really really clear when pruning it is not recoverable

* Better examples

* Match bouncer like for like

* Fix merge error

* Dont use log. and dont return error on user input to abort
2023-07-28 15:23:47 +01:00
mmetc
643445b7cf
docker: allow GID with no persistent sqlite db (#2381) 2023-07-28 16:01:50 +02:00
mmetc
9dfc66ef04
update pytest dependencies (#2389) 2023-07-28 14:39:03 +02:00
mmetc
ae53c0f1cc
fix "crowdsec-cli/require" log verbosity (#2390) 2023-07-28 09:56:20 +02:00
Thibault "bui" Koechlin
718721b341
fix a confusing debug message (#2386)
* fix a confusing debug message

* make CTIHelper simply log the error to avoid failing template rendering
2023-07-28 09:52:21 +02:00
mmetc
5cb7013575
Check cscli preconditions with crowdsec-cli/require package (#2388) 2023-07-27 17:02:20 +02:00
mmetc
a01ce18b98
replace imports of path with path/filepath (#2330) 2023-07-26 10:29:58 +02:00
mmetc
1a6f12c88e
Build target for "make tidy" (#2378)
The make tidy target runs "go mod tidy" in the root directory and all plugins.
2023-07-26 10:24:37 +02:00
mmetc
5e7c0e0f49
update google/winops dependency (#2366) 2023-07-26 10:14:29 +02:00
blotus
867245aefb
go mod tidy for sentinel plugin (#2377) 2023-07-25 15:43:15 +02:00
Laurence Jones
389ea4293f
Add metabase version override and update (#2370)
* Add version override and update

* Ooppsie

* Quick fix

* fgs copilot

* Allow user to overwrite image, add warning for exposing metabase and general cleanup

* One ix

* Default image if not found in config, and add a warning to remove and update

* Reorder check system memory checks so it inline with @mmetc best pratices

* No need for err

* Clean up some group code

* Change ipv6 as [] seems to wildcard

* Split loopback warn and disclaimer. Add force yes to start to allow user to accept disclaimer by default

* All cmd commands are RunE clean up

* Update flag name and dont allow a shorthand
2023-07-25 14:21:25 +01:00
blotus
77d58652a3
add sentinel notification plugin (#2268) 2023-07-25 15:07:10 +02:00
mmetc
4bc225f26b
change output of "cscli metrics -o [json|raw]" from list of objects to map with table names (#2375) 2023-07-25 13:33:50 +02:00
mmetc
fc78845a97
update gin-gonic/gin to 1.9.1 (#2230) 2023-07-25 13:32:32 +02:00
mmetc
395cace69f
fix double push of metrics by properly handling tickers (#2374) 2023-07-25 12:19:26 +02:00
blotus
7106d396dc
expose the FormatAlert function to other packages (#2248) 2023-07-25 09:55:39 +02:00
Manuel Sabban
f12ff3dfed
CI: update ansible requirements (#2364) 2023-07-24 15:35:07 +02:00
AlteredCoder
b52b4252c1
scenario labels to map string interface (#2201)
* labels are now map string interface

* restore api url

---------

Co-authored-by: Laurence Jones <laurence.jones@live.co.uk>
2023-07-24 15:19:28 +02:00
mmetc
202112bcae
CI: test with postgres 15 (#2149)
Postgres 15 restricts the default privileges for the public schema. We set crowdsec_test as owner which is shorter than granting permissions explicitly.
2023-07-24 11:56:04 +02:00
mmetc
46fff0b544
Update dependency: docker/docker (#2360) 2023-07-24 11:53:33 +02:00
mmetc
b6b6fd026b
typo fix, uppercase 'API', adjusted log level (#2361) 2023-07-21 23:23:24 +02:00
Manuel Sabban
9ac5aeda79
fix the ci by adding the ability to enforce event ordering (#2347)
* fix the ci by adding the ability to enforce event ordering
2023-07-20 11:41:30 +02:00
mmetc
3c16139c44
Reduce log verbosity at startup (#2363)
A configuration syntax test is performed every time the service is
started from systemd. The resulting error, if any, is shown on
journalctl logs.
This PR removes the unnecessary output in crowdsec.log generated by the
configuration test.
2023-07-19 13:28:52 +02:00
mmetc
bb16552aca
Use same levenshtein package for cscli, ent, hcl (#2359)
remove one dependency, slightly smaller binary
2023-07-18 11:30:14 +02:00
mmetc
e73ceafdba
Use go 1.20.6 (#2358) 2023-07-18 09:51:32 +02:00
mmetc
9af546bd0a
update pytest dependencies (#2356) 2023-07-18 09:50:06 +02:00
mmetc
11b7b1bc88
Update dependencies: k8s, swag, jwt (#2357)
this also removes dependencies on some deprecated packages
2023-07-18 09:33:32 +02:00
mmetc
6c8ddbccac
Make: error if BUILD_VERSION does not start with "v" (#2355) 2023-07-18 09:31:04 +02:00
blotus
f9ca14f010
add object key in src for S3 acquis (#2342) 2023-07-07 10:09:18 +02:00
blotus
1295de928a
Properly match new files on windows when doing file acquisition (#2329) 2023-07-06 14:45:38 +02:00
mmetc
01d7c1a5c2
update dependency on goccy/go-yaml for arm32 fix (#2343) 2023-07-06 12:05:34 +02:00
mmetc
c10bca93df update dependencies on go-plugin and go-hclog (#2341)
* update dependencies on go-plugin and go-hclog
* bump logrus (panic fix)
* implement HCLogAdapter.Getleve() to satisfy the new interface
2023-07-06 12:01:07 +02:00
mmetc
2fa826318e
CI: bump and lock pytest dependencies (#2340) 2023-07-06 10:29:08 +02:00
mmetc
59afb285f3
Update grpc dependency to latest stable version (#2339) 2023-07-06 10:15:17 +02:00
mmetc
9967d60987
errors.Wrap -> fmt.Errorf (#2333) 2023-07-06 10:14:45 +02:00
mmetc
486b56d1ed
CI: reduce test verbosity; set PKG_CONFIG_PATH for re2 in rpm distros (#2331)
* wip

* wip

* go install with commit hash
2023-07-05 17:45:31 +02:00
mmetc
8bcb4c2436
Update go-re2 dep to fix arm32 build (#2332) 2023-07-05 13:14:40 +02:00
mmetc
73f71a0aa3
tests: vagrant refactoring (#2328) 2023-07-04 12:26:32 +02:00
mmetc
17cd792826
CI: update ansible tests for re2 (#2318) 2023-06-29 16:35:19 +02:00
mmetc
bd41f855cf
errors.Wrap -> fmt.Errorf (#2317) 2023-06-29 11:34:59 +02:00
blotus
e61d5a3034
rename status to state in fire response (#2313) 2023-06-29 11:06:49 +02:00
mmetc
ebe25d7653
func tests: install dependencies from make, log test helpers (#2314) 2023-06-28 10:07:05 +02:00
mmetc
893394ef5f
rename metabase APIClient to avoid confusion (#2305) 2023-06-27 15:07:16 +02:00
mmetc
e404e0b608
raise error with invalid 'on_success', 'on_failure' in profile (#2303) 2023-06-27 15:03:07 +02:00
mmetc
956703c31a
CI: Update setup-go action to v4 (with automatic cache) (#2168) 2023-06-27 14:50:45 +02:00
mmetc
85839b0199
support for stdin with "cscli decision import" and raw values (#2291)
and remove Origin from the struct, which was ignored anyway
2023-06-27 14:29:42 +02:00
mmetc
6e18c652cb
docker: build same re2 version for alpine/debian; bump yq (#2311)
also slightly improve layer cache usage
2023-06-27 13:43:42 +02:00
mmetc
a910b7beca
non-fatal error if some datasource can't be run (i.e. journalctl but systemd is missing) (#2309)
This on the other hand, gives a new fatal error when there are no valid datasources.
In the previous version, crowdsec kept running with just a warning if no
acquisition yaml or dir were specified.
2023-06-27 10:13:13 +02:00
he2ss
d26e17f505
update debian version to have latest systemd (#2304)
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2023-06-26 12:52:10 +02:00
mmetc
aeca8f40c2
build docker version with c++ re2 (static) (#2307) 2023-06-25 23:45:20 +02:00
mmetc
4137482f65
docker: always merge .yaml.local in conf_get() (#2272)
With this change, all queries to the configuration will return the
values from .local if they are set. However, conf_set will only write
to .yaml and never to .local. This means users can potentially override
values that are supposed to be under control of the entrypoint
(credentials and things set from envvars).
2023-06-23 15:49:09 +02:00
mmetc
98c6038fde
Build with libre2 by default, options for wasm and static; add mk/gmsl (#2295) 2023-06-23 14:25:29 +02:00
mmetc
507da49b5a
send metrics immediately if agents are added or removed (#2296) 2023-06-23 14:06:04 +02:00
mmetc
9beb5388cb
errors.Wrap -> fmt.Errorf; clean up imports (#2301) 2023-06-23 14:04:58 +02:00
mmetc
d4c0643122
CI: add fedora-37, -38 to vagrant tests (#2299) 2023-06-23 13:59:24 +02:00
mmetc
e42841cd00
Change api_key encoding to base64 to comply with bcrypt max size (#2302) 2023-06-23 13:54:36 +02:00
mmetc
62caffb102
update leakybucket readme (#2298) 2023-06-22 15:35:01 +02:00
mmetc
fddf597040
errors.Wrap -> fmt.Errorf; clean up imports (#2297) 2023-06-22 15:01:34 +02:00
mmetc
8bfeb7d90d
Update go dependencies (#2293)
- update fatih/color (fix windows issue)
- update mongo-driver (fix build issue)
- go.mod: merge two "require" blocks
- update semver dependency (same version as indirect dep), fix test checks in cscli setup
- remove gotest.tools dependency (use testify, cstest)
- update x/ exp, mod, sys dependencies
2023-06-22 11:31:41 +02:00
Emanuel Seemann
40e6b205bc
Add bayesian bucket type (#2290) 2023-06-21 15:08:27 +02:00
mmetc
da6106bd23
spellcheck/style leakybucket readme (#2294) 2023-06-21 11:47:07 +02:00
mmetc
4c4b545e9b
append vendor.tgz to each release (#2288) 2023-06-21 09:52:33 +02:00
mmetc
f7409d47be
fix error message when failing to parse ip address (#2292)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-06-21 09:22:25 +02:00
Laurence Jones
062f71fb92
CI: vagrant configuration for debian 12 (#2285) 2023-06-19 21:18:29 +02:00
mmetc
89c3c18c19
allow running rootless docker tests (#2281)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-06-19 12:02:59 +02:00
mmetc
c3c2608947
CI: Remove cache entries when closing a PR (#2289)
This should reduce overall cache occupation and thrashing
2023-06-19 11:30:56 +02:00
Laurence Jones
2c8769adf6
Update jsonextract.go (#2287)
Return nil instead of empty string as ParseKV does the same
2023-06-16 18:34:55 +01:00
mmetc
381220daf4
Use go 1.20.5 (#2280)
https://groups.google.com/g/golang-announce/c/q5135a9d924
2023-06-15 23:18:57 +02:00
mmetc
b9a3acb03f
light pkg/parser cleanup (#2279)
* pkg/parser: clean up imports
* remove duplicate import
* simplify boolean expression
* don't check length before range
* if..else if.. -> switch/case
* errors.Wrap -> fmt.Errorf
* typo, lint
* redundant break
2023-06-13 13:16:13 +02:00
mmetc
76429f033a
trim pkg/types: move DataSet/GetData to pkg/cwhub, removed unused Clone function (#2271) 2023-06-08 16:49:51 +02:00
mmetc
cf747d65e0
fix missing import (#2275) 2023-06-08 15:49:37 +02:00
mmetc
25bb23d8b7
minor refactor to pkg/types, cscli machines (#2270)
* cleanup: separate ui and logic
* trim some code from pkg/types
2023-06-08 15:08:51 +02:00
mmetc
6096cb3c9b
Move grok_pattern.go away from pkg/types to trim bouncer dependencies (#2269) 2023-06-08 15:07:30 +02:00
mmetc
4e2c9c185b
Implement "crowdsec -fatal" flag; change help message (#2266)
The -trace...-fatal flags do not change the log destination but only the
verbosity. This change reflects that, and implements "-fatal" which was missing.
2023-06-08 15:06:06 +02:00
mmetc
8da9d5eefd
don't log notification error if not running under systemd (#2274) 2023-06-08 15:04:48 +02:00
mmetc
5b3200173e
don't pre-create log files (not required anymore) (#2267)
The lumberjack package fixed the issue in natefinch/lumberjack#83 (tested with umask 002) and this code is now redundant since we updated the dependency to v2.2.1.
2023-06-07 12:58:35 +02:00
mmetc
edd062522d
build against libre2-dev if found (#2255) 2023-06-06 15:46:25 +02:00
mmetc
3cc6b2c0d0
CI: add tests for metrics configuration (#2251) 2023-06-05 23:17:30 +02:00
mmetc
9ccdddaab1
CI: refactor makefile for plugins and vendor target (#2256) 2023-06-05 23:15:18 +02:00
mmetc
0191faf3a8
update notif threshold test on windows (#2265) 2023-06-05 22:58:13 +02:00
mmetc
2a8e97d558
show option -winsvc only under windows (#2258) 2023-06-05 13:49:31 +02:00
mmetc
7673a20467
CI: make clean -> remove coverage data (#2259) 2023-06-05 13:03:18 +02:00
mmetc
18764eff0e
make: allow using a development version of Go, with a warning (#2260) 2023-06-05 13:02:37 +02:00
mmetc
e3cb4ab2c4
do not send more than group_threshold alerts at once to a notification plugin (#2264)
* do not send more than group_threshold alerts at once to a notification plugin
* Use generic Chunks function, updated tests

---------

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2023-06-05 12:55:03 +02:00
mmetc
26e2bbd709
gitignore: ignore .vagrant directories (#2262) 2023-06-05 10:56:32 +02:00
mmetc
3b1f412e44
default config: simulation off -> false (yaml 1.2) (#2263) 2023-06-05 10:55:27 +02:00
mmetc
a4eee41fd7
log.Warning if a notification is configured twice (#2240) 2023-06-02 14:41:50 +02:00
mmetc
228e4f9acc
cscli: add G (1e9) suffix to metric units (#2254) 2023-06-02 14:38:11 +02:00
mmetc
d757cf8e84
CI: publish dev-debian docker image (amd64 only) (#2252) 2023-06-01 17:41:33 +02:00
mmetc
396dcf8e6e
dependencies: replaced function calls to pkg/types, errors.Wrap (#2235)
we now use a generic pointer function, and slowly remove the deprecated pkg/errors
2023-06-01 16:31:56 +02:00
mmetc
12c32d507c
CI: refactoring pkg/csplugin tests (#2247) 2023-06-01 10:33:08 +02:00
mmetc
f6544962ea
CI: separate stderr in all func tests (#2250) 2023-06-01 09:42:27 +02:00
he2ss
084186c67a
update libsystemd in debian docker image (#2245)
* update libsystemd in debian docker image

* remove update dep in build step
2023-05-31 12:39:40 +02:00
mmetc
92a9d6c321
types.InSlice() -> slices.Contains() (#2246) 2023-05-31 12:39:22 +02:00
mmetc
3c1b957050
CI: use hub cli to upload release tar (#2244) 2023-05-30 10:47:04 +02:00
Laurence Jones
4fbc3402fb
Update KV ignore whitespace before and after = (#2236)
* Update KV ignore whitespace before and after `=`

* Update helpers.go

Don't need whitespace infront of KEY

* Add some tests to ensure edge cases

* Ensure quoted and unquoted values act the same
2023-05-26 15:35:46 +01:00
blotus
6720d89845
fix lock when dumping the parsing state in explain mode (#2234) 2023-05-26 15:23:50 +01:00
blotus
f6924f8c57
generate asserts for evt.Unmarshaled in hubtest (#2214) 2023-05-26 11:44:58 +02:00
mmetc
9167bd107d
decouple bouncer dependencies: use go-cs-lib/pkg/ptr (#2228) 2023-05-25 15:43:39 +02:00
mmetc
b2d3520519
decouple bouncer dependencies: use go-cs-lib in test code (#2229) 2023-05-25 15:37:44 +02:00
mmetc
364b833d67
test cleanup: remove /tmp/crowdsec_tests* directories (#2232) 2023-05-25 15:32:32 +02:00
Laurence Jones
0416a41d58
Log info capi whitelists (#2220)
* add infof command if err was nil

* Fix golint

* Make message more readable and log individual stats

* Missed a d

* Remove '

* simplify if/else logic

---------

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2023-05-25 10:28:08 +01:00
mmetc
1f9f81da70
makefiles: de-duplicate, simplify and remove unused code (#2222) 2023-05-25 10:32:05 +02:00
mmetc
025f14f879
merge system cert pool with own certs (#2226) 2023-05-25 10:10:58 +02:00
mmetc
e5fe74ce77
decouple bouncer dependencies: use go-cs-lib/pkg/ptr in apiclient (#2227) 2023-05-25 10:08:52 +02:00
mmetc
e1400d28f1
support capi_whitelists.yaml (#2224) 2023-05-25 10:02:33 +02:00
mmetc
534328ca30
decouple bouncer dependencies: use go-cs-lib/pkg/* (#2216)
* decouple bouncer dependencies: use go-cs-lib/pkg/trace
* decouple bouncer dependencies: use go-cs-lib/pkg/version
* decouple bouncer dependencies: use go-cs-lib/pkg/yamlpatch
* decouple bouncer dependencies: use go-cs-lib/pkg/csstring
* unused import
2023-05-23 10:52:47 +02:00
mmetc
eddb994c0b
Use go 1.20.4 (#2209) 2023-05-17 11:24:37 +02:00
blotus
6e3ca35941
fallback to master for hub index download if it does not exist (#2210) 2023-05-17 11:20:53 +02:00
blotus
0ea1508ff9
Don't allow to customize the installation directory on windows (#2208) 2023-05-17 10:35:46 +02:00
mmetc
fcf44f7b31
gitignore: allow shipping wasm libs with vendored files (#2207) 2023-05-17 10:34:13 +02:00
blotus
412b4c4b0b
fix incorrect version strip (#2206) 2023-05-17 01:13:55 +02:00
blotus
0ddd42c01f
disable armv6 and 7 for docker debian image temporarily (#2200) 2023-05-16 15:24:31 +02:00
Thibault "bui" Koechlin
77f2968267
fix the behavior of json unmarshal to not return the full map (#2199) 2023-05-16 09:10:38 +02:00
blotus
8aca0ea860
update default windows acquisition configuration (#2195) 2023-05-12 13:47:01 +02:00
dependabot[bot]
abbc130844
Bump github.com/docker/distribution (#2194)
Bumps [github.com/docker/distribution](https://github.com/docker/distribution) from 2.8.0+incompatible to 2.8.2+incompatible.
- [Release notes](https://github.com/docker/distribution/releases)
- [Commits](https://github.com/docker/distribution/compare/v2.8.0...v2.8.2)

---
updated-dependencies:
- dependency-name: github.com/docker/distribution
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-05-12 09:45:08 +02:00
Laurence Jones
424215f228
Add ParseKV helper and rework UnmarshalJSON as a proper helper (#2184) 2023-05-12 09:43:01 +02:00
mmetc
e1f5ed41df
Implement "cscli config show-yaml" (#2191) 2023-05-11 21:01:13 +02:00
Thibault "bui" Koechlin
5ac33aab03
allow batching when importing decisions (#2192) 2023-05-11 14:33:18 +02:00
blotus
4ae41a363d
add Hostname helper in expr and templating (#2193) 2023-05-11 14:25:04 +02:00
blotus
71b7a594bd
add indexes on the FK between alerts and {decisions,metas,events} (#2188) 2023-05-11 13:49:01 +02:00
blotus
2701454f23
defaults to inotify to detect changes in file datasource to avoid too many call to stat() (#2181) 2023-05-09 10:03:55 +02:00
blotus
e1f4a71357
readd KeyExists expr helper (#2180) 2023-05-04 16:55:34 +02:00
blotus
a753ea6981
Add B64decode expr helper (#2183) 2023-05-04 14:15:20 +02:00
Thibault "bui" Koechlin
8f71edaadd
do not error on this filter (#2182) 2023-05-04 13:06:15 +02:00
Thibault "bui" Koechlin
4ff8f498ce
add a LogInfo expr helper (#2179) 2023-05-03 10:07:11 +02:00
AlteredCoder
6bb20fa951
fix issue #2172 (#2177) 2023-04-28 16:32:46 +02:00
dependabot[bot]
88587822c1
Bump github.com/docker/docker (#2159)
Bumps [github.com/docker/docker](https://github.com/docker/docker) from 20.10.2+incompatible to 20.10.24+incompatible.
- [Release notes](https://github.com/docker/docker/releases)
- [Commits](https://github.com/docker/docker/compare/v20.10.2...v20.10.24)

---
updated-dependencies:
- dependency-name: github.com/docker/docker
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2023-04-28 12:02:29 +02:00
AlteredCoder
c0e6c1ac78
Fix chooseHubBranch when latest() doesn't work (#2178)
* Fix chooseHubBranch when latest() doesn't works
2023-04-28 11:24:04 +02:00
mmetc
d286b044e7
Update go-sqlite3 dependency (fix LD_PRELOAD warnings) (#2174) 2023-04-19 12:05:24 +02:00
mmetc
0d1adfc7db
wizard: auto-detect ssh.service correctly on deb distros when auth.log is missing (fix #2175) (#2176) 2023-04-19 11:09:39 +02:00
Thibault "bui" Koechlin
3041023ed8
add an optional flag to disable the fetch (#2169) 2023-04-14 11:39:16 +02:00
Thibault "bui" Koechlin
66dfded0cf
significantly increase the max number of scenarios to be sent (#2170) 2023-04-14 11:39:07 +02:00
mmetc
6b744884b0
Update deps to latest stable: go-systemd, tail, cobra, lumberjack, testify (#2164) 2023-04-12 16:58:11 +02:00
mmetc
774a8cfc00
CI: use Go 1.20.3 (#2163) 2023-04-12 16:57:52 +02:00
mmetc
0c5d233563
Minor cleanup and dead code removal (#2166) 2023-04-12 16:57:38 +02:00
Laurence Jones
9a5a937695
Make it more obvious that parser succeeded but was whitelisted (#2167)
* Make it more obvious that parser succeeded but was whitelisted

* Add more verbose by placing whitelist reason next to why it is ignored
2023-04-12 10:48:42 +01:00
Thibault "bui" Koechlin
7fa469d0b0
timeout of ci jobs (#2160) 2023-04-05 15:15:33 +02:00
blotus
1e018bdaf8
Wait for both api and agent chans if necessary when daemonize is false or running on windows (#2155) 2023-04-04 15:16:48 +02:00
blotus
0279e549bd
check if the acquis tomb is dying while processing logs in replay mode for file/s3/docker (#2152) 2023-04-04 13:57:06 +02:00
mmetc
3132aa54b7
Properly load k8s audit configuration (#2158) 2023-04-03 21:55:31 +02:00
mmetc
38ab6be7c2
Allow feature.yml to change available subcommands (#2156) 2023-04-03 10:11:56 +02:00
mmetc
3fa555fb25
Rename k8s_audit to k8s-audit (easier to type, consistent with labels) (#2153) 2023-04-03 09:53:38 +02:00
mmetc
ea6401ce09
CI: Static builds by default; replace bincover with go -cover from 1.20 (#2150)
* Makefile: build static binaries only
* Replace bincover with go -cover from 1.20
* CI: Fix timing issue between lapi and agent containers
2023-03-30 15:05:09 +02:00
blotus
61bea26486
Add transform configuration option for acquisition (#2144) 2023-03-29 16:04:17 +02:00
blotus
772d5b5c32
Add experimental support for re2 (#2138) 2023-03-28 16:26:47 +02:00
blotus
1095f6c875
use expr.Function for custom functions instead of passing them in the env (#2133) 2023-03-28 10:49:01 +02:00
Thibault "bui" Koechlin
169b844212
fix awkward stacktrace in conditional filter (#2145) 2023-03-27 16:01:42 +02:00
mmetc
f39fbf07fa
Docker: don't re-register local agent if not needed (#2141) 2023-03-27 15:38:38 +02:00
mmetc
d769fff1e8
File acquisition: log "file reopen" events instead of writing to stderr (#2139) 2023-03-24 11:24:36 +01:00
mmetc
68d4bdc1bd
Docker: correct behavior of AGENTS_ALLOWED_OU, BOUNCERS_ALLOWED_OU (#2140) 2023-03-24 11:23:04 +01:00
mmetc
bbfb7d1cfa
Allow running func tests while running containers with crowdsec (#2137)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-03-24 10:19:22 +01:00
mmetc
3884c5f47d
Unit tests: remove leftover files (#2134) 2023-03-22 13:51:37 +01:00
mmetc
80de87ac34
Report docker systems in version and user agents (#2136) 2023-03-22 11:57:29 +01:00
Thibault "bui" Koechlin
a3e5f0a3a0
fix dateparse (#2135) 2023-03-22 08:20:21 +01:00
blotus
91eb39cff6
New PAPI commands: reauth + force_pull (#2129) 2023-03-21 14:06:19 +01:00
blotus
dc38e5ac00
S3 acquisition datasource (#2130) 2023-03-21 13:54:52 +01:00
Thibault "bui" Koechlin
a74e424d53
support ip and cidr based whitelists for capi and 3rd party blocklists (#2132)
* support ip and cidr based whitelists for capi and 3rd party blocklist
2023-03-21 11:50:10 +01:00
Thibault "bui" Koechlin
d87f088b8f
match expr helper (#2126)
* match expr helper
2023-03-21 10:39:17 +01:00
mmetc
86971da274
CI: avoid conflict with pkg/build cache in golangci-lint action (#2123) 2023-03-20 10:41:08 +01:00
Thibault "bui" Koechlin
618be9ff68
properly update the time structure within event (#2122)
* properly update the time structure within event to ensure it works in time-machine

* move LIVE and TIMEMACHINE to pkg/types : less code needs to import leakybucket package, and we avoid duplicating constants
2023-03-16 16:25:50 +01:00
blotus
c77fe16943
actually fix expr-debugger to work with the new version (#2124) 2023-03-16 15:20:48 +01:00
blotus
94c7efdb5b
add ToString() helper (#2100) 2023-03-16 15:20:31 +01:00
blotus
b1f2063a9a
Only support pgx driver for postgresql (#2118) 2023-03-16 11:02:31 +01:00
Thibault "bui" Koechlin
855f9e6f8d
protect map w/ mutex to avoid concurrent map writes with cscli explain when having many concurrent parser routines (#2113) 2023-03-16 11:01:25 +01:00
AlteredCoder
e61a464951
Fix cscli explain when running from testenv (#2114)
* Fix cscli explain when running from testenv
2023-03-15 10:26:40 +01:00
Manuel Sabban
b451d190b7
try to make reproducible build work (#2119)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2023-03-13 17:26:33 +01:00
mmetc
9c90144867
Docker readme: update build instructions, recommend acquis.d and config.yaml.local (#2115) 2023-03-10 17:30:08 +01:00
blotus
6aaf3cd50b
Update expr to 1.12.2 (#2110) 2023-03-09 16:56:11 +01:00
mmetc
0a114ca7d1
Fix docker tests by increasing timeout (again) and move compose test to plugin (#2112)
* Fix docker tests by increasing timeout (again) and move compose test to plugin

* Bump workflow timeout to 30 min

* Test only alpine-slim and debian-full flavors
2023-03-09 12:00:29 +01:00
mmetc
e161507d08
Lint (type inference): remove redundant type declarations (#2111) 2023-03-09 11:56:02 +01:00
mmetc
9faa49c7e8
Load lapi config for config show output (#2097)
This adds URL and login parameters as it was intended.
Also rewrite configShow and displayOneAlert to use an embedded text/template for shorter code.
2023-03-08 22:47:25 +01:00
Thibault "bui" Koechlin
d95b7afe61
Distance support : Impossible travel (#2108)
* add distance helpers
2023-03-08 18:29:42 +01:00
Thibault "bui" Koechlin
9d5aaf5ea2
add --origin to cscli decisions delete (#2109) 2023-03-08 18:29:20 +01:00
Thibault "bui" Koechlin
5b0fe4b7f1
support for regexps result cache (#2104)
* support for regexps result cache : gcache + xxhash

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2023-03-08 16:07:49 +01:00
mmetc
e71d146a2d
Fix docker tests by increasing timeout (#2107) 2023-03-08 14:51:49 +01:00
mmetc
137e7408fd
Run lint after tests instead of separate workflow (#2103) 2023-03-08 14:50:59 +01:00
mmetc
e63a3ab92b
Unit tests: fix authentication to localstack (#2106) 2023-03-08 14:41:16 +01:00
mmetc
c7014dba8f
Build notification plugins with current crowdsec; mod tidy (#2102) 2023-03-07 16:41:13 +01:00
mmetc
0a748d324e
Make: extract "goversion.mk" to reuse it in bouncers (#2101) 2023-03-07 11:46:52 +01:00
blotus
16a3be49e2
do not try to load PAPI is url is not set (#2099) 2023-03-06 15:38:58 +01:00
blotus
e27a0a0e14
display source in alerts list when an alert has multiple decisions (#2098) 2023-03-06 13:51:57 +01:00
blotus
b2c2c5ac59
add papi_url in credentials file when enabling console_management, and remove it when disabling console_management (#2095) 2023-03-03 17:03:21 +01:00
mmetc
a19748ae35
Rename directory "tests" to "test" (#2094)
If you use a ./test/local directory, you need to create it again:
$ make clean bats-build bats-fixture
2023-03-03 15:54:49 +01:00
blotus
85ab9c68a2
Add cscli papi status and cscli papi sync (#2091) 2023-03-03 13:46:28 +01:00
mmetc
f6d6c5bb2b
Add tests and typo fixes (#2092) 2023-03-03 11:06:27 +01:00
dependabot[bot]
ef4e61e05e
Bump golang.org/x/net in /plugins/notifications/slack (#2088)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220418201149-a630d4f3e7a2 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-03 10:13:22 +01:00
dependabot[bot]
54fc5e48dc
Bump golang.org/x/net in /plugins/notifications/splunk (#2086)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220418201149-a630d4f3e7a2 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-02 22:21:00 +01:00
dependabot[bot]
7f04d12333
Bump golang.org/x/net in /plugins/notifications/http (#2087)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220418201149-a630d4f3e7a2 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-02 21:54:26 +01:00
dependabot[bot]
76c84c69c4
Bump golang.org/x/net in /plugins/notifications/email (#2085)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220418201149-a630d4f3e7a2 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-02 21:21:50 +01:00
dependabot[bot]
6888fa2133
Bump golang.org/x/net from 0.0.0-20220722155237-a158d28d115b to 0.7.0 (#2089)
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.0.0-20220722155237-a158d28d115b to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/commits/v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-02 14:46:58 +01:00
mmetc
dd76c07293
CI: limit -dev docker image to amd64 to speed up the pipeline (#2090) 2023-03-02 11:33:36 +01:00
dependabot[bot]
d7119b73ab
Bump golang.org/x/text in /plugins/notifications/http (#2074)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-02 09:41:27 +01:00
mmetc
a6bb2cf5e1
Fix log destination in one-shot mode (#2084) 2023-03-01 17:00:04 +01:00
dependabot[bot]
83db873f5b
Bump golang.org/x/text in /plugins/notifications/email (#2073)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 12:27:26 +01:00
dependabot[bot]
cdd2401ff6
Bump golang.org/x/text in /plugins/notifications/splunk (#2071)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 11:38:44 +01:00
mmetc
83b6c2cfef
Bump bats-core to 1.9 (#2083)
- update bats-core to the last release
- renamed 01_base.bats to 01_cscli.bats
- separate stderr for all the run commands in 01_*.bats, fix out/err check where appropriate
- cache go modules for bats build too
- add configuration file for buildx jobs
2023-03-01 10:56:25 +01:00
mmetc
3962daa3bd
CI: Limit parallel docker builds for performance on small machines (#2082) 2023-03-01 10:27:08 +01:00
dependabot[bot]
9ae99964e6
Bump golang.org/x/text from 0.3.7 to 0.3.8 (#2072)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 09:30:50 +01:00
dependabot[bot]
37c8d4419a
Bump golang.org/x/text in /plugins/notifications/slack (#2070)
Bumps [golang.org/x/text](https://github.com/golang/text) from 0.3.7 to 0.3.8.
- [Release notes](https://github.com/golang/text/releases)
- [Commits](https://github.com/golang/text/compare/v0.3.7...v0.3.8)

---
updated-dependencies:
- dependency-name: golang.org/x/text
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-03-01 09:30:20 +01:00
mmetc
301782ae18
Docker tests: use pytest-cs 0.2 (#2079)
* Use pytest-cs 0.2

* fix pipenv cache key

* Cache docker layers

* Load build images from buildx to docker

* CI: commit Pipfile.lock

* Add full docker tag

* Cache only amd64 docker layers

* Cache layer mode=min
2023-02-28 17:49:32 +01:00
mmetc
ff17a961fc
CI: Cache all built go modules (#2081) 2023-02-28 17:25:09 +01:00
Manuel Sabban
60b3f63851
ugly workaround to fix the tests (#2080)
* ugly workaround to fix the tests

* add comments

---------

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2023-02-28 17:05:11 +01:00
Manuel Sabban
39a4a256fd
fix the way acquisition is stopped (#2069)
* fix the way acquisition is stopped by draining inputLineChan before terminating it.

---------

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2023-02-27 11:21:25 +01:00
AlteredCoder
01ea78c10e
Strip version with ~ instead of - (#2076) 2023-02-25 20:05:48 +01:00
mmetc
40b5bcb918
Fix docker tests (network creation) (#2077) 2023-02-24 17:15:17 +01:00
Laurence Jones
75d8b821ff
Explain successful parsers only (#2063)
* Add option to filter down explain to successful parsers useful for me who has every collection installed

* Altered naming conventions so it makes more sense when reading
2023-02-24 13:49:17 +00:00
Laurence Jones
8acce4637a
Option to disable remote lapi registration (#2010)
* Allow to disable remote lapi registration

* Extract method and make it extendable as a generic middleware

* Change method name so it make sense to read abort remote if <config>

* golint
2023-02-24 13:44:21 +00:00
mmetc
addf60b3ee
Pin pytest-cs to a stable tag, cache virtualenvs, don't install ipython in CI (#2075) 2023-02-24 11:01:45 +01:00
mmetc
20a1bc7d44
chore: simplify pkg/database/alerts (#2062) 2023-02-23 10:25:01 +01:00
mmetc
8e74575c03
email plugin: add "starttls" as accepted encryption_type in the comment (#2068) 2023-02-22 11:11:31 +01:00
mmetc
be18fea136
Propagate taints to top collections (fix #2064) (#2066) 2023-02-21 22:12:08 +01:00
mmetc
76ea3a063f
fix message "empty scenario" 2023-02-21 09:59:56 +01:00
blotus
90c38db9f2
Stream decisions from db (#1927) 2023-02-20 15:26:30 +01:00
mmetc
b7d1e2c483
replace log.Fatal -> fmt.Errorf (#2058) 2023-02-20 15:05:42 +01:00
mmetc
8fce946850
CI: functional docker tests (#2056) 2023-02-20 14:55:56 +01:00
dependabot[bot]
19a01d20dd
Bump github.com/containerd/containerd from 1.6.12 to 1.6.18 (#2060) 2023-02-20 11:01:27 +01:00
dependabot[bot]
65fa2bf8c3
Bump github.com/docker/distribution (#1996) 2023-02-20 10:34:52 +01:00
JDEV
12a4a5fb14
CAPI error code handling tests (#2027)
* Registration mocked error cases

* Authentication mock error cases

* mini facto

* check that getMEtric still has bouncers/machines keys in output even with empty collections

* fixed defer body close(), no need to defer and fprint arg

* fix fatal call

---------

Co-authored-by: jdv <julien@crowdsec.net>
2023-02-17 14:57:46 +01:00
blotus
83c3818504
Do not try to refresh JWT token when doing a login request (#2059) 2023-02-16 16:16:26 +01:00
mmetc
5de500d6da
CI: set GOBIN instead of go install + cp (#2030) 2023-02-15 14:27:47 +01:00
mmetc
5ff6bfba9c
CI: build with/require go 1.20 (#2031) 2023-02-15 14:27:17 +01:00
mmetc
06ddd01c70
test: bats-detect tests for "cscli setup" (#2057) 2023-02-15 14:23:52 +01:00
Laurence Jones
5aca11af70
Show s00 stats instead of "first_parser" (#2055)
* show s00 if verbose is provided

* Clean up code

* Fix failing test
2023-02-14 14:36:08 +00:00
Cristian Nitescu
ecb32d74c6
optimize blocklist fetch (#2039) 2023-02-13 15:06:14 +01:00
Cristian Nitescu
f280505eaa
omtimization - remove useless login call (#2036) 2023-02-13 15:05:58 +01:00
blotus
812b87ab48
Add IsIPV4() and IsIP() helpers (#2050) 2023-02-10 14:44:42 +01:00
Thibault "bui" Koechlin
0f5560b62a
more strings helpers (#2040)
* more strings helpers
2023-02-09 15:23:21 +01:00
blotus
6c15da4ece
strip v prefix in tag name in azure-pipeline (#2048) 2023-02-09 14:17:49 +01:00
blotus
ebd709a4fe
Fix azure pipeline (#2046) 2023-02-09 13:08:57 +01:00
blotus
2820f9b986
fix typo when assigning build_version in azure pipeline (#2044) 2023-02-09 10:50:48 +01:00
blotus
9f911318f3
use the tag name from the predefined variable for azure pipeline (#2041) 2023-02-08 18:41:23 +01:00
Thibault "bui" Koechlin
1d7d377f8b
changes following BL tests (#2038)
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2023-02-08 10:35:21 +01:00
Thibault "bui" Koechlin
a0b264047c
allow user to specify stash's cache strategy (#2037) 2023-02-06 15:42:55 +01:00
Cristian Nitescu
987f119c4b
v3 capi and blocklists links support (#2019)
* v3 model generation

* v3 model generation

* comms

* fixes after master merge

* missing reader close

* use constants defined for types

---------

Co-authored-by: bui <thibault@crowdsec.net>
2023-02-06 14:06:14 +01:00
mmetc
b6be18ca65
cscli setup (#1923)
Detect running services and generate acquisition configuration
2023-02-06 07:33:04 +01:00
AlteredCoder
7e871d2278
rename PAPI base URL (#2033) 2023-02-03 12:10:02 +01:00
mmetc
8f130196f8
CI: bump more actions (#2028) 2023-02-02 09:49:52 +01:00
mmetc
628af6e2d0
CI: update github actions and deprecated commands (#2023) 2023-02-01 16:55:34 +01:00
he2ss
8024693f4f
add dev docker image (based on master) (#2024)
* add dev docker image (based on master)
2023-02-01 14:47:38 +01:00
Thibault "bui" Koechlin
e927717fa0
Polling API Integration (#1715)
Co-authored-by: alteredCoder <kevin@crowdsec.net>
Co-authored-by: he2ss <hamza.essahely@gmail.com>
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2023-01-31 14:47:44 +01:00
mmetc
3bf95e1a83
docker: skip temporary installation of disabled items (#2018) 2023-01-26 17:13:57 +01:00
mmetc
e37d09e5b4
use helpers for shorter tests, add a couple of error cases (#2016) 2023-01-26 17:13:31 +01:00
mmetc
3fb3decf49
error if tls.key_file or cert_file are missing (#2020) 2023-01-26 17:12:59 +01:00
mmetc
b0f370bae2
fix docker support for legacy vars (#2021) 2023-01-26 17:12:40 +01:00
mmetc
6193047c35
remove SYSTEM=docker during build, update dockerignore (#2017) 2023-01-25 10:39:23 +01:00
mmetc
02be5f3618
allow literal $ in plugin configuration (#2015) 2023-01-23 16:28:43 +01:00
mmetc
47cc60bda9
allow use of literal $ in config.yaml (#2012) 2023-01-23 10:29:29 +01:00
he2ss
ce60c7b056
docker: add cri-logs collection by default to support CRI log format (#2005) 2023-01-20 16:02:04 +00:00
mmetc
d369656b26
agent: fix message when -dsn is provided without -type (#2009) 2023-01-20 16:14:26 +01:00
mmetc
e5833699c0
cscli config feature-flags (#2006) 2023-01-20 09:32:10 +01:00
ju_hnny5
83ed8a61aa
Store go module name in var in Makefile (#1989)
Co-authored-by: Julien Briault <jbriault@deezer.com>
2023-01-19 22:24:45 +01:00
mmetc
4bffc0df21
break in smaller functions cscli hub, hubtest, notifications, parsers, scenarios, simulation (#2004) 2023-01-19 13:29:36 +01:00
mmetc
1e4441b6ae
docker: replace BUILD_ENV with --target (#1995) 2023-01-19 11:02:23 +01:00
mmetc
7bb74b9664
refact cscli decisions (#2003) 2023-01-19 11:02:00 +01:00
Thibault "bui" Koechlin
4f29ce2ee7
CTI API Helpers in expr (#1851)
* Add CTI API helpers in expr
* Allow profiles to have an `on_error` option to profiles

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2023-01-19 08:45:50 +01:00
Marco Mariani
0c35d9d43c wip 2023-01-18 15:15:18 +01:00
Marco Mariani
4f25738d6b wip 2023-01-18 15:15:18 +01:00
Marco Mariani
47dbfa770d configure logging earlier 2023-01-18 15:15:18 +01:00
Marco Mariani
91b0f8fee1 load custom configuration paths when agent is disabled 2023-01-18 15:15:18 +01:00
Marco Mariani
2e91a82aa7 load feature.yaml as soon as possible 2023-01-18 15:15:18 +01:00
Thibault "bui" Koechlin
f25fdecc3f
normalize scopes for alerts and decisions (#2001)
* normalize scopes for alerts and decisions
2023-01-18 14:50:03 +01:00
Marco Mariani
b603bdfccc cscli refact: extracted New.*Cmd from alerts, capi, dashboard; removed (some) globals 2023-01-18 11:09:28 +01:00
Ben Scobie
3d8c891699
Fix reference to ghcr.io (#1999) 2023-01-17 16:50:27 +00:00
Yip Rui Fung
ecb5562b57
Fix docker_start.sh not properly handling env vars (#1993)
For example, the COLLECTIONS environment variable is supposed to do a space separated list.
But with the unquoted call to cscli_if_clean without quotes on the $COLLECTIONS environment variable, only the first entry is passed to it.
As a result, only the first entry is installed.

Would likely affect all call sites to cscli_if_clean
2023-01-14 19:56:27 +01:00
mmetc
2142f7bb5c
ci: remove hub dispatch, (msi) take release version from git history (#1949)
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2023-01-13 14:16:17 +01:00
mmetc
51800132cd
improve feature flag logging (#1986)
For cscli: it should provide a terse output, not nag users with configuration details. Although it's usually important that cscli and crowdsec have the same enabled features, having it list them every time the command is invoked can be too much.

For crowdsec: when features are set from the environment, it's too early to log where we should. So we can use log.Debug at activation time, and list them again once logging is configured.

 - wrap some functions in csconfig for convenience and DRY
 - for each enabled feature, log.Debug
 - log all enabled features once as Info (crowdsec) or Debug (cscli)
 - file does not exist -> log.Trace
2023-01-13 13:42:42 +01:00
Cristian Nitescu
73663ff9e7
log the request error even in case of retry (#1988) 2023-01-13 12:58:12 +01:00
dependabot[bot]
942aed1219
Bump github.com/containerd/containerd from 1.6.2 to 1.6.12 (#1978)
Bumps [github.com/containerd/containerd](https://github.com/containerd/containerd) from 1.6.2 to 1.6.12.
- [Release notes](https://github.com/containerd/containerd/releases)
- [Changelog](https://github.com/containerd/containerd/blob/main/RELEASES.md)
- [Commits](https://github.com/containerd/containerd/compare/v1.6.2...v1.6.12)

---
updated-dependencies:
- dependency-name: github.com/containerd/containerd
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
Co-authored-by: blotus <sebastien@crowdsec.net>
2023-01-12 17:25:53 +01:00
mmetc
157589d31e
cscli explain: add crowdsec path option (#1983) 2023-01-12 17:04:28 +01:00
mmetc
ba4396e52c
fix flaky parser unit test (#1985) 2023-01-12 17:03:25 +01:00
Thibault "bui" Koechlin
6fb962a941
Allow parsers to capture data for future enrichment (#1969)
* Allow parsers to capture data in a cache, that can be later accessed via expr helpers (fake multi-line support)
2023-01-11 15:01:02 +01:00
mmetc
cd4dabde0e
silence yaml.local explicitly in cscli, keep in crowdsec/bouncer logs (#1981) 2023-01-11 09:50:46 +01:00
mmetc
c4deaf0994
cscli: avoid initializing the db configuration twice (#1982) 2023-01-11 09:50:12 +01:00
Laurence Jones
ca12432a2a
Change patch to debug, if user has a local overide they will get informed every cscli call (#1980) 2023-01-10 10:05:18 +00:00
mmetc
d986ae0ee5
fix yq behavior with bind-mount config.yaml (#1968)
Co-authored-by: Thibault "bui" Koechlin <thibault@crowdsec.net>
2023-01-09 21:47:25 +01:00
mmetc
943bb58086
docker: add {VERSION}-slim tag to releases (#1977) 2023-01-09 16:44:03 +01:00
mmetc
c49c1cbf2a
fix alert context CI when feature flags are enabled (#1979) 2023-01-09 16:18:06 +01:00
Cristian Nitescu
7284c0a47a
retry with backoff requests to CAPI (#1957)
* backoff on refresh token error

* fix tls communication with lapi and user/pw auth (#1956)

allow self-signed TLS encryption with user/pw auth

docker:
 - remove defaults for certificate file locations
 - new envvar INSECURE_SKIP_VERIFY
 - register agent before TLS settings (cscli machine add removes them
   from the credentials file)

* separate cscli cobra constructors:  lapi, machines, bouncers, postoverflows (#1945)

* use feature toggling to improve testability with http retry backoff

* Add parse unix to dateparse enricher (#1958)

Add parse unix is we do have a strTime but wasnt parsed using convential golang time

* func tests: redirect stderr to filter extra logs (#1961)

* backoff on refresh token error

* use feature toggling to improve testability with http retry backoff

* refactor feature backoff toggle for tests

Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
Co-authored-by: Laurence Jones <laurence.jones@live.co.uk>
2023-01-09 14:49:21 +01:00
blotus
a84e4b6b15
Add conditional bucket (#1962) 2023-01-06 09:26:16 +01:00
mmetc
822e441d3a
bump docker actions to avoid deprecation warnings (#1966) 2023-01-04 16:55:34 +01:00
AlteredCoder
185f9ad541
Alert context (#1895)
Co-authored-by: bui <thibault@crowdsec.net>
2023-01-04 16:50:02 +01:00
mmetc
dfc4126384
Docker config/auth/TLS refactoring from from v1.4.4 (#1967) 2023-01-04 16:43:35 +01:00
mmetc
033082a31e
ParseUnix() test fix: force UTC (#1970) 2023-01-04 16:22:17 +01:00
mmetc
2d81e751a1
fix parser test 2k23 (#1971) 2023-01-04 15:46:16 +01:00
mmetc
899f3e7eb8
func tests: redirect stderr to filter extra logs (#1961) 2022-12-30 15:57:24 +01:00
Laurence Jones
fd1c38811e
Add parse unix to dateparse enricher (#1958)
Add parse unix is we do have a strTime but wasnt parsed using convential golang time
2022-12-30 12:47:14 +00:00
mmetc
59f6610721
separate cscli cobra constructors: lapi, machines, bouncers, postoverflows (#1945) 2022-12-30 10:13:52 +01:00
mmetc
72c1753fb7
fix tls communication with lapi and user/pw auth (#1956)
allow self-signed TLS encryption with user/pw auth

docker:
 - remove defaults for certificate file locations
 - new envvar INSECURE_SKIP_VERIFY
 - register agent before TLS settings (cscli machine add removes them
   from the credentials file)
2022-12-29 22:00:11 +01:00
Laurence Jones
401739b036
Add unix expr helper (#1952)
* Add unix expr helper

* Add original value not parsed error

* return early if cannot parse

* Add tests

* Fix negative value
2022-12-29 14:53:06 +00:00
Thibault "bui" Koechlin
e4463c412b
Improve warnings around lack of evt.StrTime field (#1954)
* fix #1951 : improve error messages

* make hubtest warn you if you're missing evt.StrTime in your logs
2022-12-29 15:03:32 +01:00
mmetc
38b37db55b
systemd: same restart options across deb, rpm, wizard (#1948) 2022-12-28 10:13:05 +01:00
mmetc
6efc2688b1
simplify feature flags (#1947)
Now checking for a feature flag is a one liner,
with no need to control errors.

if fflag.Crowdsec.CscliSetup.IsEnabled() {
   ...
}
2022-12-26 14:23:41 +01:00
mmetc
c022eb1b86
remove ignored flag "-m" in "cscli machines delete" (it takes a positional argument) (#1943) 2022-12-23 17:13:20 +01:00
mmetc
ef3a130d54
Cscli config refactoring (#1934) 2022-12-22 12:22:55 +01:00
mmetc
7d6523db29
ci: authenticate when looking up release information (#1936) 2022-12-21 20:34:11 +01:00
mmetc
5d2c99bb17
runtime feature flag initialization 2022-12-21 17:19:20 +01:00
mmetc
6b71da6b78
require go 1.19, test with 1.20 too (#1935) 2022-12-21 15:40:29 +01:00
mmetc
ff88faf402
updated localstack dependencies, added build cache 2022-12-21 12:20:01 +01:00
mmetc
a32aa96752
feature flags (#1933)
Package fflag provides a simple feature flag system.

 Feature names are lowercase and can only contain letters, numbers, undercores
 and dots.

 good: "foo", "foo_bar", "foo.bar"
 bad: "Foo", "foo-bar"

 A feature flag can be enabled by the user with an environment variable
 or by adding it to {ConfigDir}/feature.yaml

 I.e. CROWDSEC_FEATURE_FOO_BAR=true
 or in feature.yaml:
```
 ---
 - foo_bar
```

 If the variable is set to false, the feature can still be enabled
 in feature.yaml. Features cannot be disabled in the file.

 A feature flag can be deprecated or retired. A deprecated feature flag is
 still accepted but a warning is logged. A retired feature flag is ignored
 and an error is logged.

 A specific deprecation message is used to inform the user of the behavior
 that has been decided when the flag is/was finally retired.
2022-12-20 16:11:51 +01:00
mmetc
f68bc113a7
docker: separate CLIENT_* and LAPI_* variables for tls certificates (#1929) 2022-12-16 20:41:39 +01:00
he2ss
579cecde04
apiclient: fix http roundtrip (clone body also) (#1758)
* apiclient: fix http roundtrip (clone body also)
2022-12-14 16:42:46 +01:00
Laurence Jones
fe23da6e0c
Add postgres socket support, clean some code (#1926) 2022-12-12 16:08:19 +00:00
mmetc
e4ff26d613
docker readme update (#1924) 2022-12-12 10:57:26 +01:00
mmetc
409721414b
docker: fix/improve support for persistent configurations (#1915)
set all defaults in config.yaml and leave environment variables empty. This way when they are set we know that we must override the values in config.yaml.
ignore tainted objects when calling install/upgrade/remove
use_wal is false by default
2022-12-10 22:09:25 +01:00
mmetc
6c19beb937
set cscli log timestamp to 24h (#1917) 2022-12-09 16:48:24 +01:00
Laurence Jones
11965f08db
Add socket support to mysql (#1911) 2022-12-08 09:33:08 +00:00
mmetc
10ee07cea0
docker: correctly extract BOUNCER_KEY_* (fix #1912) (#1913) 2022-12-06 16:03:28 +01:00
mmetc
cc228f1868
Typos, grammar (#1905) 2022-12-06 15:55:27 +01:00
blotus
fdda940ac0
Add Kubernetes audit acquisition (#1767) 2022-12-06 13:47:29 +01:00
mmetc
9131d9d568
docker/README: automatic registration with tls (#1909) 2022-12-06 11:58:32 +01:00
Laurence Jones
311cda31fe
Governance v1 (#1844)
* v1

* Update wording

* The area stuff needs a little work

* add enhancement to pr's

* Update governance and feature request template
2022-12-05 15:58:19 +00:00
Manuel Sabban
3d72ca731a
Suggest bouncers and machines to delete (#1896)
* Suggest bouncers to delete

* Autocomplete machines delete cmd

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Fix lint.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* fix compilation (git merge errors)

* cleanup go.mod unneeded changes

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
Co-authored-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-12-05 15:39:54 +01:00
mmetc
fd3e668fe1
add -error flag to crowdsec binary (#1903) 2022-12-03 08:56:11 +01:00
mmetc
fa0e590778
removed pid_dir (#1906) 2022-12-02 13:42:43 +01:00
Manuel Sabban
7c3dbffcc6
clean up BUILD_GOVERSION which is set at runtime with runtime lib (#1901)
* clean up BUILD_GOVERSION which is set at runtime with runtime lib
* simplify version check

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
Co-authored-by: Marco Mariani <marco@crowdsec.net>
2022-12-02 13:04:00 +01:00
mmetc
4a6a9c4355
acquisition: validate datasources before configuration (static checks) (#1841)
* acquisition: validate datasources before configuration (allow static configuration checks)

* remove comment

* import reviser, format

* error wrap
2022-11-30 17:36:56 +01:00
mmetc
f2528f3e29
add USE_WAL to docker arguments (#1899) 2022-11-30 14:28:33 +01:00
mmetc
d15014f82e
silence harmless "machines delete" error in dockerfile (#1904) 2022-11-30 14:19:20 +01:00
blotus
60f1228030
use a copy of bucket processors in LeakRoutine (#1902) 2022-11-30 10:59:47 +01:00
mmetc
104f5d1fe6
lint: error handling cleanup (#1877) 2022-11-29 09:16:07 +01:00
mmetc
66543493b5
fix nil dereference: check that httpServer is set before shutting down (#1893) 2022-11-28 11:55:08 +01:00
mmetc
aa974d26c6
enable CI workflow for stable branches (#1889) 2022-11-28 10:52:42 +01:00
mmetc
fde9640364
Docker refactoring, tls setup (#1869) 2022-11-28 10:35:12 +01:00
blotus
c5079ac15e
invalidate agent token on 403 as well (#1888) 2022-11-25 14:35:50 +01:00
mmetc
2067ab0427
CI: print stack traces (#1886) 2022-11-25 12:02:38 +01:00
mmetc
5bdd3bbfcb
require at least go 1.18 to build (#1884) 2022-11-24 11:29:54 +01:00
mmetc
3288fad341
set BUILD_VERSION to the correct tag (#1885)
This fixes a regression introduced in 0449ec18 (Windows Support #1159)
where the build system uses the last local tag that has been created
(chonologically) instead of the most recent tag in the current branch.
This problem is not detected while working with stable versions because
they are built on a clean checkout.
2022-11-24 10:34:44 +01:00
mmetc
8b82939d33
fix static release upload (#1883) 2022-11-24 10:29:17 +01:00
Laurence Jones
4ac01ed880
Update perms for group read (#1876) 2022-11-21 09:49:56 +00:00
mmetc
99513f64fd
cscli config show: print host/port/user/dbname when driver=pgx (fix #1866) (#1870) 2022-11-17 11:07:37 +00:00
mmetc
3beb84bcfe
print missing "AS" values as empty strings instead of "0 " (#1867) 2022-11-14 09:55:53 +01:00
mmetc
b0889d7751
docker build flavors: slim, with-plugins, with-geoip, full (#1862) 2022-11-08 12:28:57 +01:00
mmetc
502a3cf841
ci: skip func tests with legacy postgres driver (keep pgx) (#1864) 2022-11-08 12:27:31 +01:00
Thibault "bui" Koechlin
523343b174
notify when community-blocklist starts pull (#1845)
* minor change to notify blocklist pull update, will make eventual troubleshooting easier
2022-11-08 10:44:25 +01:00
Thibault "bui" Koechlin
3b4da7e637
fix #1860 : Only repeat the WAL warning once (#1863)
* fix #1860
2022-11-07 16:36:39 +01:00
mmetc
895691dad1
enabled linters: gocritic, nilerr (#1853) 2022-11-07 10:36:50 +01:00
AlteredCoder
59fc403e32
fix docker_start without using jq (#1855)
* fix docker_start without using jq
2022-11-07 10:07:26 +01:00
mmetc
f860a037b5
randomize metric push time (#1852) 2022-11-04 14:54:03 +01:00
Manuel Sabban
8aca00326d
fix ticker (#1858)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-11-04 13:56:43 +01:00
Laurence Jones
668627f890
Add error checking to lookup host (#1847) 2022-10-31 18:38:01 +00:00
mmetc
344b1dc559
fixed package tests w/wal, gitignore/typos (#1849) 2022-10-31 10:02:51 +01:00
mmetc
df88f4e1e9
randomize pull, push and metric intervals; reload crowdsec only when hub changed (#1846) 2022-10-28 13:55:59 +02:00
mmetc
67e464281f
create hub badges, repository dispatch only on crowdsecurity/crowdsec (#1838) 2022-10-28 10:11:15 +02:00
Thibault "bui" Koechlin
23ffa1e04f
add cscli alerts delete --id (#1843)
* add cscli alerts delete by id

* test added for cscli delete alert --id

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2022-10-27 09:07:53 +02:00
mmetc
02d2eab18c
update golangci-lint to 1.50 and fixes (#1828) 2022-10-26 15:11:37 +02:00
ThinkChaos
22479a289d
Add LookupHost expr lib func (#1775) 2022-10-26 10:17:48 +01:00
mmetc
2088bb1f91
fix for #1839 (#1840) 2022-10-26 11:02:12 +02:00
blotus
b7c4bfd4e3
Use explicit transaction when inserting community blocklist (#1835) 2022-10-26 10:48:17 +02:00
mmetc
e545933923
fix(cscli): correct and test the behavior of "cscli collections delete" (#1824) 2022-10-25 14:10:51 +02:00
mmetc
7b4f300eb2
update codecov action (node 12 is deprecated) (#1830) 2022-10-24 12:48:25 +02:00
Laurence Jones
ac6e0c1b89
fix cron removal (#1829) 2022-10-20 16:43:34 +01:00
Laurence Jones
c1334b9a8b
Test if cscli is installed if so run hub update and reload (#1827) 2022-10-20 12:59:39 +01:00
blotus
03c9216026
Update chocolatey spec file and publish nupkg in github releases (#1826) 2022-10-20 11:12:54 +02:00
blotus
bb2f0e938f
Blocklist: Do not duplicate decisions when pulling (#1796) 2022-10-19 15:51:40 +02:00
Thibault "bui" Koechlin
ae6bf39495
support decisions deletion via scenario + alerts delete via ID (#1798) 2022-10-19 14:37:27 +02:00
Laurence Jones
24b540ecde
Cronjob via packages (#1820)
* Final version
2022-10-18 16:11:48 +01:00
mmetc
487bf4e74a
require go 1.19 for plugins; require crowdsec 1.4.1; go mod tidy (#1823) 2022-10-18 17:01:36 +02:00
mmetc
7866729d3b
func tests: don't return pid of started process unless asked (#1821) 2022-10-18 13:00:35 +02:00
mmetc
6b0097a24b
change warning to debug when directories are missing in hub sync (#1819) 2022-10-18 10:32:54 +02:00
Laurence Jones
04a8fb7f81
Add helo config (#1765)
HELO message always need to send an ip or FQDN, set localhost to be default instead of doing an if statement. (Replicate same default in email client)
2022-10-17 20:42:31 +01:00
Laurence Jones
33383faf9e
Cronjob remove fails due to [[ (#1818)
* Fix

* Fix
2022-10-17 17:09:52 +01:00
mmetc
2b7e3ff1e7
warn if no acquisition files are found, acquisition_test refactoring, tests (#1816) 2022-10-17 17:32:08 +02:00
Laurence Jones
0ecb6dcd4d
Hub auto update cronjob (#1817)
Add hub cron installation to install scripts

Plus remove on uninstall
2022-10-17 16:04:01 +01:00
mmetc
ec0d2a5ed2
refactor broker_test.go, extract cstest/filenotfound*.go (#1815) 2022-10-17 14:17:23 +02:00
mmetc
a96b3e077d
rename pkg/cstest -> pkg/hubtest (#1811)
keep cstest for generic helper functions
this also avoids circular imports in test files
2022-10-17 09:24:07 +02:00
mmetc
2b7f6b2b84
force postgres 14 for func tests (#1813)
the postgres 15 image (released two days ago) has a permission issue. proper fix will follow
2022-10-17 09:21:55 +02:00
mmetc
8fecc2c00b
enable staticcheck linter; fixes (#1806)
- explicitly ignore returned parameters
 - replace Walk with faster WalkDir
 - log path error during hub dir sync
 - colorize static unit tests
 - removed duplicate import in crowdsec/main.go
 - typos
 - func tests: default datasource in tests/var/log instead of /tmp
 - action setup-go v3
2022-10-14 16:12:21 +02:00
mmetc
708fa8280a
add test and fix for configuration reload (#1808)
fix reload issue by returning new configuration to the signal loop

example: run crowdsec, disable agent in the config file, reload config.
Now there is no agent but the signal loop believes there is, so
triggering a reload configuration again will make the process hang
forever.
This commit updates the configuration in the signal loop with the one
returned by the signal handler.
2022-10-14 15:48:41 +02:00
blotus
7144dca68a
Fix missing metrics cscli (#1809) 2022-10-13 15:49:41 +02:00
Manuel Sabban
7359586f1c
fix ticker mix up (#1807)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-10-13 14:30:27 +02:00
mmetc
4b3c9c2806
print cscli usage in color, fix windows terminal detection (#1801) 2022-10-13 12:28:24 +02:00
mmetc
7674f907c4
replace log.Fatal with t.Fatal (#1805)
This is required to run deferred teardown functions
2022-10-13 10:42:46 +02:00
mmetc
f78270188f
don't install jq to build windows, docker (not required anymore) (#1800) 2022-10-11 13:32:23 +02:00
mmetc
1d9f861f28
unit tests: always capture testcase variable -> allow parallel testing (#1797) 2022-10-10 10:48:26 +02:00
Stephane de Labrusse
daae241ff9
fix #1794 (TLS is forced even when -e USE_TLS="false") 2022-10-07 16:31:03 +02:00
mmetc
a50a3362bd
bats helper fixes (#1792) 2022-10-07 16:17:36 +02:00
mmetc
ec8a1ecec1
updated windows/README.md (#1785) 2022-10-07 13:39:29 +02:00
Shivam Sandbhor
74659a82ab
Fast bulk alert delete (#1791) 2022-10-07 12:40:30 +02:00
mmetc
ddd75eae9a
cscli: new tables, --color yes|no|auto option (#1763) 2022-10-07 11:05:35 +02:00
AlteredCoder
b95a67751e
Update ent and grokky package (#1772)
* Update ent and grokky package
2022-10-06 14:55:42 +02:00
Manuel Sabban
83841d801c
fork dlog to ease debian packaging on official repos (#1790)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-10-06 13:40:31 +02:00
Shivam Sandbhor
65c0b9ebcf
Simplify one shot tests (#1786) 2022-10-06 11:57:26 +02:00
blotus
3ba67bad3d
remove a wrong warning when pulling list content from CAPI (#1789) 2022-10-06 11:48:06 +02:00
mmetc
9b3be5c2e8
Bulk delete alert optimization (#1782) 2022-10-05 17:07:44 +02:00
Shivam Sandbhor
b203b3f444
Fix flakey test in file_tests (#1783)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-10-05 16:40:09 +02:00
mmetc
af30ba0e3b
tests/bin cleanup (#1760) 2022-10-04 15:58:10 +02:00
mmetc
c920a301e0
make: accept BUILD_VENDOR_FLAGS variable (#1771) 2022-10-04 09:51:35 +02:00
mmetc
44525e235a
renamed security.MD -> SECURITY.md, typos (#1774) 2022-10-04 09:50:18 +02:00
mmetc
6120571421
fix & cleanup cloudwatch_test.go (#1780) 2022-10-04 09:48:59 +02:00
mmetc
edced6818a
cleanup + fix flaky tests in file_test.go, apic_test.go (#1773) 2022-09-30 16:01:42 +02:00
mmetc
6798dd7ba5
"make localstack": added zookeper+kafka services (#1770) 2022-09-29 09:24:00 +02:00
blotus
bfbe180101
Tighten windows sqlite database permissions (#1769) 2022-09-28 16:18:00 +02:00
Shivam Sandbhor
52447f6999
Don't suggest an item which user already mentioned. (#1702) 2022-09-28 13:26:47 +02:00
Sean Kelly
568eb1d4e0
Fix misspelling of instantiate participles (#1759) 2022-09-27 17:13:43 +02:00
mmetc
d4a7288826
spf13/cobra v1.5.0; antonmedv/expr v1.9.0 (#1756) 2022-09-27 16:28:07 +02:00
Laurence Jones
21e5b0d6d0
Improvement: Docker one shot error message (#1666)
* In one shot, user would only specify one container?
2022-09-27 16:20:30 +02:00
blotus
0708073a0c
Tighten permissions for creds and notification configuration files on windows (#1757) 2022-09-16 09:23:08 +02:00
blotus
1ba6c67ff2
rename ROOT var to CS_ROOT (#1755) 2022-09-15 17:12:29 +02:00
Manuel Sabban
1f06f242cc
fix https://github.com/crowdsecurity/crowdsec/issues/1746 (#1749)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-09-14 15:26:26 +02:00
blotus
9b3ff82542
add WAL support for sqlite (#1752) 2022-09-14 15:09:54 +02:00
Shivam Sandbhor
87239c62c1
Replace shodan with crowdsec cti (#1741)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-09-14 15:06:27 +02:00
mmetc
03b5184837
restrict permissions for plugin configurations (#1745) 2022-09-14 14:23:18 +02:00
mmetc
52fbda1a5e
simpler makefiles for static targets (#1744) 2022-09-14 14:22:57 +02:00
mmetc
110272484d
use ansible roles from crowdsecurity.testing collection (#1743) 2022-09-12 16:07:14 +02:00
AlteredCoder
7d97729eea
Add config option to enable or not local API and agent (#1730)
* Add flag to enable or not local API and agent
2022-09-12 14:38:29 +02:00
AlteredCoder
b06167a3fa
Allow plugins to load environment variable (#1727)
* Allow plugins to load environment variable
2022-09-08 11:41:28 +02:00
Manuel Sabban
f3317f78d5
acually postoverflow _before_ reprocessing (#1739)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-09-07 14:16:47 +02:00
Manuel Sabban
b2130b1593
Fix 1737 (#1738)
* add GetMeta to *types.Event

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-09-07 10:11:39 +02:00
Thibault "bui" Koechlin
9d199fd4a9
fix #1733 : add support for exclusion regexps (#1735)
* allow to specify a list of regular expressions to skip some specific files
2022-09-06 14:58:37 +02:00
mmetc
414282a2c9
golangci-lint 1.49 and related fixes (#1736) 2022-09-06 13:55:03 +02:00
mmetc
faf3670e7f
Ansible changed_when fix; ansible/vagrant lint (#1734) 2022-09-06 11:33:50 +02:00
Laurence Jones
e674537d0b
Update sprig to v3 (#1722)
* Update sprig to v3
2022-09-05 09:05:50 +02:00
mmetc
c4652d60a7
hardcode db password in CI to allow tests from third parties (#1729) 2022-09-01 16:49:12 +02:00
he2ss
ea40ffd655
Datasource/kafka (#1698)
* add Kafka datasource
2022-08-30 17:03:45 +02:00
Manuel Sabban
7d0f89df29
Implement reinject command to send notifications of alerts (#1638)
* implement reinject command to send notifications of alerts using a profile

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-08-30 15:45:52 +02:00
Manuel Sabban
21255b6391
fix #1724 (#1725)
* fix #1724

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-08-30 12:38:28 +02:00
Manuel Sabban
64e0832b85
fix the ssltls by actually doing ssltls. (#1672)
BEWARE: THIS IS A BREAKING CHANGE

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-08-26 16:49:31 +02:00
Thibault "bui" Koechlin
bacea50485
allow user to disable decision deduplication (#1687)
* allow user to disable decision deduplication
2022-08-26 14:17:46 +02:00
blotus
1f5224b74b
switch to go 1.19 (#1709) 2022-08-26 13:31:49 +02:00
Manuel Sabban
bd2757c63d
typo for func tests (#1718)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-08-25 16:52:00 +02:00
blotus
e46ca38cbb
add cscli support dump (#1634) 2022-08-18 11:54:01 +02:00
Manuel Sabban
27194a9f9c
fix logging for email plugin (#1670)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-08-16 18:07:00 +02:00
mmetc
1aac5d78d9
replace wizard patch for .deb & .rpm packages with an envvar check (#1630) 2022-08-16 14:59:59 +02:00
mmetc
6b18674960
func tests: enable capi only when needed (#1710) 2022-08-16 10:17:21 +02:00
mmetc
eea07b7a1a
golangci-lint v1.48 and fixes for "usestdlibvars" (#1711) 2022-08-16 09:46:10 +02:00
mmetc
15a9e16530
functional tests: json, stderr helpers (#1704) 2022-08-05 10:54:49 +02:00
mmetc
bd3722f075
Ansible testing improvements (#1700) 2022-08-04 11:25:34 +02:00
AlteredCoder
fe5f9bfc28
add suggestion on cscli install items (#1686) 2022-08-04 10:09:56 +02:00
blotus
dacf6ebc64
Fix cscli notifications list crash (#1697) 2022-08-02 20:44:19 +02:00
mmetc
c742242094
Ansible testing (#1691) 2022-07-29 10:34:03 +02:00
AlteredCoder
1002affc16
cscli machines delete: return an error if machines doesn't exist (#1689)
* cscli machines delete: return an error if machines doesn't exist
2022-07-28 17:32:12 +02:00
AlteredCoder
16b1ab06a9
Add -a options in cscli alerts list (#1690)
* Add -a options in cscli alerts list
2022-07-28 17:31:53 +02:00
Thibault "bui" Koechlin
866c200c31
Generic dateparse approach (#1669)
* Allow any parser to suggest a format string for the date to be parsed.

* allow the enricher functions to get the parser's logger so they can inherit the level
2022-07-28 16:41:41 +02:00
blotus
1fc29d094f
Don't run azure pipeline on freeBSD tags (#1684) 2022-07-26 16:40:16 +02:00
mmetc
39f57f1487
functional tests instrumented by ansible/vagrant (#1682) 2022-07-26 13:09:13 +02:00
mmetc
804b6f4c5d
adjust test timing for slow boxes (#1681) 2022-07-26 09:47:56 +02:00
mmetc
e13867f7c9
fix --column-statistics handling in mysql tests (#1680) 2022-07-25 16:25:57 +02:00
mmetc
e1954adc32
test machines_tls: remove all existing machines in setup (#1678) 2022-07-22 14:21:05 +02:00
Thibault "bui" Koechlin
0eea20fa7c
revert decision dedup behavior to 1.3.4 (#1675)
* revert decision dedup behavior to 1.3.4
2022-07-22 11:20:10 +02:00
blotus
3adb90e7b7
do not hide unit test failure (#1677) 2022-07-22 10:59:23 +02:00
mmetc
496dacb7ff
tls tests with bundle.pem (#1671) 2022-07-21 13:03:46 +02:00
blotus
865ff5c88d
windows: log fatal and panic errors to event log (#1667) 2022-07-19 09:48:02 +02:00
mmetc
85e5a7e8ed
Makefile does not require go to run tests (#1663) 2022-07-18 12:54:03 +02:00
AlteredCoder
24b1a99c42
Run cscli hubtest without being root (#1658) 2022-07-13 12:00:26 +02:00
blotus
8decbe7670
Properly handle service shutdown on windows (#1662) 2022-07-13 11:54:12 +02:00
AlteredCoder
5c8e2a8510
Fix 1652 (#1654) 2022-07-13 10:57:07 +02:00
Thibault "bui" Koechlin
bd91ddaf52
logging consistency for .local files (#1655) 2022-07-13 10:56:03 +02:00
blotus
7b8cd63b04
do not set the UDP read buffer size in syslog datasource (#1657) 2022-07-13 10:18:03 +02:00
mmetc
fa35e8c0ba
removed: realpath -s (does not exist on freebsd) (#1656) 2022-07-13 10:10:08 +02:00
Manuel Sabban
9fac14488a
fix perms for config.yaml installation (#1661)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-07-12 16:05:27 +02:00
AlteredCoder
39da36361c
Get geoip Country from other objects if not present (#1659) 2022-07-12 15:26:34 +02:00
Thibault "bui" Koechlin
73f336363a
bump log level when overloading config file with .local (#1646)
* bump log level

Co-authored-by: Marco Mariani <marco@crowdsec.net>
2022-07-08 09:29:23 +02:00
mmetc
37ada58f3a
func tests: fix database fixture for config-global (#1647) 2022-07-07 17:12:16 +02:00
mmetc
607b7d4b6f
config-global: don't remove init data; receive community pull (#1644) 2022-07-07 16:11:27 +02:00
Thibault "bui" Koechlin
920f3d2a7d
fix #1643 : deal with null heartbeat (#1645) 2022-07-07 15:29:30 +02:00
blotus
5c1c941851
close response body in heartbeat (#1637) 2022-07-06 14:50:54 +02:00
mmetc
2c0c7225f5
typos 2022-07-06 14:43:14 +02:00
Thibault "bui" Koechlin
0a372d83b9
fix again (#1641) 2022-07-06 14:34:39 +02:00
Thibault "bui" Koechlin
5e80bf3043
up (#1640) 2022-07-06 14:04:33 +02:00
Thibault "bui" Koechlin
9739de61b0
rename (#1639) 2022-07-06 13:58:03 +02:00
Thibault "bui" Koechlin
134ac2e68c
Issues templates improvements (#1629)
* add security.md
* add metrics and config show
2022-07-06 13:53:30 +02:00
mmetc
e05515f79d
disable capi for tests by default (#1633) 2022-07-04 11:26:39 +02:00
mmetc
e868adee2f
config_get, config_set test helpers (#1632) 2022-07-01 22:45:55 +02:00
AlteredCoder
5f62d738fc
Add no-capi flag and review some logs (#1628)
* Add no-capi flag and review some logs
2022-07-01 16:56:13 +02:00
mmetc
492e0dfeb1
hardcode tests/local path (#1631) 2022-07-01 15:21:28 +02:00
mmetc
b1cbf2e2e5
fix build/test badge (#1626) 2022-07-01 12:19:21 +02:00
mmetc
14dd6b9026
disable tls tests in pipeline (#1625)
and removing obsolete $FILE
2022-07-01 11:03:40 +02:00
mmetc
69dd8d2892
fix some tests in pipeline (#1622) 2022-07-01 10:16:45 +02:00
Thibault "bui" Koechlin
ca4cd6d559
attempt to fix ticker leak (#1620) 2022-06-30 17:36:01 +02:00
AlteredCoder
02e0f3c095
Fix event.timestamp pointer usage (#1621)
* Fix event.timestamp pointer usage

* avoid returning an error when creating alerts if something goes wrong during the parsing

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2022-06-30 17:35:42 +02:00
blotus
863facaa33
Properly handle expired decisions with different scopes (#1616) 2022-06-29 16:13:04 +02:00
Thibault "bui" Koechlin
15902dcba6
fix #1615 : cleanup based on heartbeat instead (#1617) 2022-06-29 13:21:58 +02:00
mmetc
8e7e799304
[wip] serve metrics only after agent and/or lapi are ready; fixed some func tests (#1613) 2022-06-24 15:55:21 +02:00
mazzma12
dbdc7529b3
Add docker and discord badges in README.md and fix invite link (#1612)
* Add Discord and Docker badges

* Update invite link for Discord in README.md
2022-06-24 14:39:16 +02:00
Marco Mariani
4be884824f Revert "fixed tls tests"
This reverts commit 520e40db37.
2022-06-24 13:57:44 +02:00
Marco Mariani
520e40db37 fixed tls tests 2022-06-24 13:55:58 +02:00
blotus
46f20193f9
windows: fix asset path for artifact upload (#1609) 2022-06-23 15:34:19 +02:00
blotus
33ff938504
windows build: remove rc suffix from build version (#1607) 2022-06-23 15:09:29 +02:00
he2ss
7fafb483ad
Pkg/database/fix count decisions since by value (#1606)
* fix CountDecisionsSinceByValue to have also expired decisions
2022-06-23 12:04:07 +02:00
Laurence Jones
342e7f5272
Cscli Explain Stdin (#1597)
Allow `cscli explain` to rely on stdin
2022-06-23 11:51:43 +02:00
AlteredCoder
a4f4eabf0a
support yml file (#1605) 2022-06-22 17:01:27 +02:00
mmetc
628d7be1d8
simplify err.Error() to err when used in printf context (#1603) 2022-06-22 15:53:53 +02:00
he2ss
3c6834fc18
docker_start: improve start script (#1599) 2022-06-22 11:31:55 +02:00
he2ss
3d6f015211
Add duration expr to add duration formula (#1556)
* add duration expr to add duration formula
2022-06-22 11:29:52 +02:00
Thibault "bui" Koechlin
a6ed08b239
Add alerts and decisions metrics, LAPI and agent timing prom metrics (#1546) 2022-06-22 11:14:34 +02:00
AlteredCoder
0a39066f9d
Fix #1552 (#1569) 2022-06-22 10:29:02 +02:00
Laurence Jones
a1d5a02646
Cscli explain use temp dir (#1598)
* Write to temp dir instead of CWD
2022-06-22 10:27:43 +02:00
mmetc
b91fcb8e9b
Fixed bats tests for freebsd (#1600) 2022-06-22 10:00:51 +02:00
mmetc
d71279f023
added flag crowdsec --warning (#1461) 2022-06-22 09:38:23 +02:00
mmetc
c78c833400
CI: colored test output, colored crowdsec and crowdsec-api logs, full final db dump for mysql and sqlite (#1596)
* github-ci: color unit test output and logs
* new config option: force_color_logs (useful in CI)
* bats: show sqlite/mysql dump at the end
* removed "-v" (print package names) from "go build"
* general workflow cleanup
2022-06-17 16:12:49 +02:00
mmetc
a2d91119d4
make localstack-stop target (#1593) 2022-06-16 16:13:48 +02:00
mmetc
10585bfecc
enabled linters and fixes for: misspell, predeclared, unconvert, ineffassign, gosimple, govet (#1595) 2022-06-16 14:41:54 +02:00
mmetc
b572f64dc6
removed bats warnings (#1592) 2022-06-15 15:36:36 +02:00
Thibault "bui" Koechlin
ff72a3c1c7
avoid create a new name generator at each bucket instanciation, it's not that cheap (#1591) 2022-06-15 10:02:00 +02:00
mmetc
67841d54ee
updated bats to 1.7.0; shellcheck fixes and moved cfssl dir under testdata/ (#1584) 2022-06-13 21:54:47 +02:00
blotus
9c1b78395a
reduce verbosity of TLS auth and FlushAgentsAndBouncers (#1588) 2022-06-13 16:08:00 +02:00
Thibault "bui" Koechlin
581ddf78fc
Performance improvements (#1583)
* fix concurrent map write on distinct cache

* cache compiled expressions for groupby and cancel_on filters

* limit objects copy when it's going to lock a shared goroutine
2022-06-13 14:41:05 +02:00
Thibault "bui" Koechlin
567e0ab7d1
fix concurrent map write on distinct cache (#1582) 2022-06-10 09:39:23 +02:00
Thibault "bui" Koechlin
1c0fe09576
Add support for certificate authentication for agents and bouncers (#1428) 2022-06-08 16:05:52 +02:00
blotus
bdda8691ff
New syslog parser for syslog datasource (#1554) 2022-06-08 15:16:58 +02:00
blotus
4b311684ab
Add more JSON expr helpers (#1576) 2022-06-08 12:15:29 +02:00
blotus
b7f1c5455f
do not rely on /proc/sys/kernel/random/uuid as fallback as it does not exists everywhere (#1575) 2022-06-06 18:20:10 +02:00
mmetc
799cc82bb5
functional tests, minor refactoring and lint/cleanup (#1570)
* cmd/crowdsec: removed log.Fatal()s, added tests and print error for unrecognized argument
* updated golangci-lint to v1.46
* lint/deadcode: fix existing issues
* tests: cscli config backup/restore
* tests: cscli completion powershell/fish
* err check: pflags MarkHidden()
* empty .dockerignore (and explain the reason)
* tests, errors.Wrap
* test for CS_LAPI_SECRET and minor refactoring
* minor style changes
* log cleanup
2022-06-06 15:24:48 +02:00
mmetc
df7c51f34e
fixed coverage reporting for functional tests; added cscli (#1568) 2022-05-31 10:01:30 +02:00
mmetc
88a4801d6a
allow run-tests with -f "<test-name>" (#1564) 2022-05-28 22:10:27 +02:00
he2ss
e88e9946f9
Crowdsec/decisions_stream bug fix (#1517)
* Fix bug when stream interval is greater or equal to 60s

Co-authored-by: alteredCoder <kevin@crowdsec.net>
2022-05-27 15:23:59 +02:00
mmetc
1fc9587919
fix #1283: update and enable error reports from golangci (#1523) 2022-05-25 22:27:50 +02:00
mmetc
29573682ec
codecov badge (#1562) 2022-05-25 10:08:52 +02:00
mmetc
d199223be0
update codeql actions (v1 is going to be deprecated) (#1563) 2022-05-25 10:06:22 +02:00
mmetc
8ea9e83798
Codecov (#1561)
* fix coverage report (#1553)

* codecov
2022-05-24 17:22:08 +02:00
mmetc
1a293a2a27
cwhub: export SetHubBranch (#1559) 2022-05-24 15:46:48 +02:00
mmetc
f1cfcfe7cc
fix coverage report (#1553) 2022-05-23 09:50:35 +02:00
mmetc
357899b83e
fixed uid/gid bound check regression (#1555) 2022-05-23 09:46:39 +02:00
mmetc
a7c7ea5712
increase lint timeout for windows (#1543) 2022-05-23 09:45:32 +02:00
Thibault "bui" Koechlin
0483b9c641
do not spew.Sdump() the invalid node on error. It leads to huge memory usage, especially if the parsers refers ie. datafile (#1550) 2022-05-20 13:29:47 +02:00
blotus
5009e9e483
windows: Use consistent GUID for harvested files (#1548) 2022-05-20 09:00:48 +02:00
AlteredCoder
1e1741aa45
Allow to set static to a pointer and add IsIPV6 helper (#1540)
* Allow to set static to a pointer and add IsIPV6 helper
2022-05-19 16:28:25 +02:00
Thibault "bui" Koechlin
fe09737d80
Add support for machine heartbeat (#1541)
* add the last_heartbeat field

* add heartbeat controller

* add endpoint of heartbeat

* heartbeat integration

* add last_heartbeat to cscli machines list
2022-05-19 15:47:27 +02:00
mmetc
4b843d145a
cscli: avoid double output (error + log fatal) and automatic --help after each error (#1536) 2022-05-19 13:42:44 +02:00
mmetc
cdab206d05
tests for misconfigured plugins (#1534) 2022-05-19 13:27:24 +02:00
mmetc
9c1c4093a3
func test: replaced one-shot bin/nc with a loop (#1542) 2022-05-19 10:51:45 +02:00
mmetc
131ed1b0a7
error reporting (#1501)
* unified error reporting, removed redundancy, tests
2022-05-19 10:48:08 +02:00
mmetc
bf3ea71630
add bats-mock to mock external commands in functional tests (#1529) 2022-05-19 09:58:13 +02:00
mmetc
e6a2a7386c
changed option 'alerts-tainted' (which does not exist) to 'tainted' (#1538) 2022-05-19 09:55:49 +02:00
mmetc
7c7fe70cb2
test multiple notification events with the same plugin (#1539) 2022-05-19 09:54:26 +02:00
Manuel Sabban
18030e6c58
add notifications command (#1537)
* add notifications command

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-05-18 16:13:33 +02:00
Shivam Sandbhor
220bbe5862
Document LAPI filters (#1535)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-05-18 11:45:12 +02:00
Laurence Jones
6d6d82b3af
Memory check for cscli dashboard setup (#1513)
* Add 1gb recmem variable and use memory module

Since checking the RAM is not required to get the container up and running we can change this to a warn level
2022-05-18 11:05:01 +02:00
mmetc
98f2ac5e7c
fix #1385: .yaml.local (#1497)
Added support for .yaml.local files to override values in .yaml
2022-05-18 10:08:37 +02:00
blotus
635e633520
update machineid to 1.0.2 (#1533) 2022-05-17 18:59:53 +02:00
blotus
39f7e38444
retry to send alert to plugin channel if it fails (#1530) 2022-05-17 16:57:15 +02:00
Laurence Jones
c2b298c93a
Add single quotes (#1527) 2022-05-17 16:57:04 +02:00
mmetc
b8547da4c3
"make localstack" target, link to docs/contributing (#1522) 2022-05-17 15:54:52 +02:00
mmetc
fae1f96856
install config.yaml with chmod 600 (#1518) 2022-05-17 12:50:18 +02:00
mmetc
afbdcd520b
update docker docs: filter on github.repository_owner == 'crowdsecurity' (#1511) 2022-05-17 12:49:25 +02:00
Thibault "bui" Koechlin
fbcb2ed7fd
Improve distinct/uniq behaviour (#1478)
* make uniq/distinct use a cache that is independant of the bucket's cache_size

* add testing specifically for cache_size
2022-05-17 12:45:53 +02:00
blotus
0449ec1868
Windows Support (#1159) 2022-05-17 12:14:59 +02:00
Cristian Nitescu
a49b023a28
GetExprEnv usage optimization (#1515)
* avoid multiples calls to GetExprEnv

* cache ExprEnv in node process

* use global expression env

* remove block profile rate
2022-05-17 10:50:37 +02:00
Manuel Sabban
f1dbe8c9dd
add the ability to build on fc36 (#1524)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-05-13 18:36:10 +02:00
mazzma12
5fcf47c79f
Add link to Console in READNE.md (#1509) 2022-05-09 10:19:09 +02:00
blotus
8f111680bf
Allow to override statics in hubtest. (#1495) 2022-04-29 14:24:41 +02:00
blotus
64369b5c2b
add expr XML helpers (#1493) 2022-04-29 13:52:23 +02:00
blotus
392708a804
Fix docker flaky test (#1494) 2022-04-29 12:16:49 +02:00
Thibault "bui" Koechlin
ddfe95e45d
user lumberjack rotate instead (#1492) 2022-04-28 17:19:03 +02:00
mmetc
2dcce2ae72
fix pipeline alert tests (#1491) 2022-04-28 14:42:42 +02:00
AlteredCoder
f22e4eb24e
Improve MySQL performance (#1477)
* Improve MySQL performance
2022-04-28 12:53:14 +02:00
Manuel Sabban
2e37d5ce97
update machineid lib (#1489)
* update machineid lib

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-04-28 12:18:16 +02:00
AlteredCoder
be977d1cc4
Fix cwhub collections uninstall dependencies (#1486)
* Fix cwhub collections uninstall dependencies
2022-04-27 18:28:03 +02:00
Manuel Sabban
589a30cd5f
[fix issue 1484] Allow to send email without auth again (#1485)
* We can now send email with plain auth
* better defaults for email plugin

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-04-27 12:07:54 +02:00
AlteredCoder
a645c928d4
Fix decisions list with --no-simu flag (#1482)
* Fix decisions list with --no-simu flag
2022-04-27 11:05:40 +02:00
Greg Myers
0f4ab71f01
Fix typos in docs, comments, code (#1483) 2022-04-27 11:04:12 +02:00
AlteredCoder
44b11c2e5b
Fix hub items installation (#1481) 2022-04-26 17:37:07 +02:00
blotus
1bd8cc79c8
Kill the whole docker acquis in tests (#1475) 2022-04-22 16:56:22 +02:00
Manuel Sabban
c17c651458
add logrotate file for debian (#1474)
* add logrotate file for debian

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-04-22 15:42:28 +02:00
AlteredCoder
8074a233e8
Fix typo in cscli metrics and debug message (#1473)
* Fix typo in cscli metrics and debug message
2022-04-22 11:29:55 +02:00
blotus
8909fbdb22
cleanup container state if the reader tomb dies by itself (#1470) 2022-04-22 10:52:44 +02:00
Thibault "bui" Koechlin
242706a475
fix journalctl deadlock on shutdown (#1468)
* avoid being locked sending termination error while the reading routine - on the chan - died
2022-04-21 14:02:25 +02:00
he2ss
2169dc674f
publish docker image to ghcr also (#1467) 2022-04-20 16:02:20 +02:00
AlteredCoder
4273a0f243
cscli: add autocompletions for hubitems (#1465)
* Add autocompletion for hub items in cscli
2022-04-20 15:44:48 +02:00
mmetc
6de175ad8a
support yq prior to 4.18.1 (#1466) 2022-04-20 15:05:34 +02:00
he2ss
ec4e193cbb
docker: add enroll on startup (#1463)
* docker: add enroll on startup
2022-04-20 13:35:22 +02:00
he2ss
615895da9d
cscli: add force enroll feature (#1430)
* cscli: add force enroll feature
2022-04-20 13:34:17 +02:00
Thibault "bui" Koechlin
ef20183ecb
go mod update for 1.3.3 (#1462) 2022-04-20 12:57:05 +02:00
mmetc
d7a269a6e4
wizard: removed jq dependency (#1460) 2022-04-20 09:45:23 +02:00
Manuel Sabban
d9f111c4ca
fix a bug in tests (#1458)
* is_db_sqlite is not accessible

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-04-19 20:00:48 +02:00
Thibault "bui" Koechlin
e6a35e8714
Improve plugins grouping (alternative to #1424) (#1437)
* Fix races in test (#1446)

Co-authored-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
Co-authored-by: alteredCoder <kevin@crowdsec.net>
Co-authored-by: AlteredCoder <64792091+AlteredCoder@users.noreply.github.com>
2022-04-19 19:12:23 +02:00
mmetc
0f7f21a7db
fix clean/create in pgdump/restore (#1457) 2022-04-19 15:49:37 +02:00
mmetc
4771d04a9d
Tests readme (#1456) 2022-04-19 15:01:46 +02:00
mmetc
2044a0677e
bats: ignore pre-installed hub objects like whitelist etc. (#1455) 2022-04-19 14:22:59 +02:00
AlteredCoder
526a4dbd08
Reduce the query unescape helper verbosity (#1447) 2022-04-19 12:31:29 +02:00
Shivam Sandbhor
8060f54f27
Cwhub testing (#1438)
* Add tests in cwhub and fix collection upgrade(#1431)

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com

Co-authored-by: bui <thibault@crowdsec.net>
Co-authored-by: Thibault "bui" Koechlin <orixxx@gmail.com>
2022-04-19 12:07:35 +02:00
mmetc
d6d9bdd2ec
db tests CI: skip jobs by default; fix pg dump; check client requirements (#1454) 2022-04-19 11:41:50 +02:00
mmetc
4b9a0c4ef7
typos (#1453) 2022-04-19 11:25:27 +02:00
Manuel Sabban
37756e8082
improve test packaging (#1443)
* improve tests for packaging

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2022-04-15 15:39:17 +02:00
Shivam Sandbhor
4a3ec85686
Update bouncer pull in rupture mode (#1445)
* Update bouncer pull in rupture mode

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-04-15 12:24:01 +02:00
mmetc
b3786961de
removed RELEASE.json, embed codename in makefile (#1442) 2022-04-14 13:51:25 +02:00
AlteredCoder
71165bcd30
Send all installed scenario to LAPI (#1277) 2022-04-13 17:48:29 +02:00
mmetc
5f2797c83c
more func test coverage; capture exit code for bincover (#1425) 2022-04-13 15:44:23 +02:00
mmetc
17ed27052c
save fixture with community data (#1440) 2022-04-13 15:17:49 +02:00
mmetc
0190614342
show crowdsec logs after the tests (#1439) 2022-04-13 15:03:37 +02:00
AlteredCoder
099469c5d2
Fix hub loader to support '.yml' files (#1433) 2022-04-11 16:13:20 +02:00
Shivam Sandbhor
a8089c8ddb
Add origins param in decision stream service (#1429)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-04-07 12:40:27 +02:00
blotus
a0a5776e51
remove trailing from cp in make release (#1416) 2022-04-07 10:49:55 +02:00
mmetc
bf4bc0c9fc
single workflow for all tests, with bats coverage (#1413) 2022-04-05 11:00:11 +02:00
blotus
9cf2d5ab5c
handle containers with TTY in docker acquis (#1422) 2022-04-05 10:31:36 +02:00
mmetc
1e63727064
int64 for metric units (#1419) 2022-04-04 21:50:19 +02:00
mmetc
7e36432bf5
use golangci-lint 1.45.2 (#1420) 2022-04-04 21:16:18 +02:00
Adam
33ef6eaea6
Register bouncers on container init (#1341)
* Register bounces on init
2022-04-04 10:18:44 +02:00
Thibault "bui" Koechlin
ba7f4fcec0
make this info level (#1409)
* make this info level
2022-04-01 15:31:33 +02:00
mmetc
c54c9f2951
skip broken tests (w/ postgres and test coverage) (#1410) 2022-04-01 15:03:17 +02:00
mmetc
058237c9dd
install *.cover binaries in $BIN_DIR; minor workflow changes (#1408) 2022-04-01 14:12:03 +02:00
mmetc
dad22a6aba
instrument main() for tests (#1399) 2022-04-01 11:17:45 +02:00
mmetc
b202e387cf
fix "cscli" without arguments (#1406) 2022-03-31 16:50:38 +02:00
Thibault "bui" Koechlin
cea793fc3a
cleanup mess (#1401) 2022-03-30 16:11:27 +02:00
Thibault "bui" Koechlin
ec5587a734
Merge branch 'master' into master 2022-03-30 16:05:32 +02:00
Manuel Sabban
b076f1d582
allow DB_BACKEND to be expanded (#1400)
* allow DB_BACKEND to be expanded

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-03-30 11:33:26 +02:00
Manuel Sabban
16b9fd82f0
Update bats tests to work with systemd (#1394)
* update for making it work with systemd
* take DB_BACKEND from file name; reduce duplicated code; configure db_type=sqlite
* define PACKAGE_TESTING

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
Co-authored-by: mmetc <92726601+mmetc@users.noreply.github.com>
2022-03-29 17:06:49 +02:00
Thibault "bui" Koechlin
d8dc01cd94
Revamp unit tests (#1368)
* Revamp unit tests
* Increase coverage
* Use go-acc to get cross packages coverage

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-03-29 14:20:26 +02:00
mmetc
3f24bcdbcf
pg tests: pass now, waiting for fix (#1393)
* PG* variable names
* take DB_BACKEND from file name; reduce duplicated code; configure db_type=sqlite
2022-03-28 10:41:32 +02:00
mmetc
2f18808d68
print db logs after tests (#1390) 2022-03-25 12:17:28 +01:00
mmetc
7329a9d4b2
mysql test: delays in strem test (#1387) 2022-03-24 14:50:52 +01:00
mmetc
aef62f74f8
remove make warning "building for linux" (#1389) 2022-03-24 14:23:51 +01:00
Manuel Sabban
2c4edac28b
update rpm patch to allow build again (#1388)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-03-24 12:42:40 +01:00
mmetc
caf1dc71fb
allow capi register in functional tests (#1384) 2022-03-24 11:07:54 +01:00
mmetc
7ff67c2311
mysql tests: silence password warnings (#1386) 2022-03-24 09:22:11 +01:00
mmetc
7baa5d623b
pgx driver tests (#1379) 2022-03-23 11:13:23 +01:00
Manuel Sabban
6491100ef1
update license (#1382)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-03-23 11:09:15 +01:00
mmetc
8df58df757
use secret for db passwords in tests (#1381) 2022-03-23 09:40:23 +01:00
Håvard Moen
42ff269bc8
add back dialect to handle pgx correctly (#1376) 2022-03-23 09:29:22 +01:00
mmetc
9d337bfb0e
fake machine-id in CI (#1380) 2022-03-22 12:33:36 +01:00
mmetc
0667552132
bats: postgres tests (#1377)
* split CI/bats in sqlite+mysql+mariadb+hub
* renamed db and user 'crowdsec' to 'crowdsec-test'; moved backend-specific scripts to lib/db, etc.
* postgres tests
* force delay between ipv6 tests (for myisam)
* force delay after pg_restore to ensure data is written
2022-03-21 15:51:05 +01:00
AlteredCoder
411baa4dcf
Improve cscli metrics units (#1374)
* Improve cscli metrics units
2022-03-21 12:13:36 +01:00
Manuel Sabban
b792c45921
Mysql enabled tests (#1372)
* add msyql backend test

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-03-18 17:36:51 +01:00
mmetc
c2708ab6c0
Bats: "reformat" script for shfmt, longer timeout for crowdsec (#1373) 2022-03-18 14:46:05 +01:00
mmetc
af8c55330d
[wip] bats changes for modular fixtures (#1371)
* target: tests/.environment.sh
* don't pass BIN_DIR around
* manage db backup/restore separately
* don't export CONFIG_DIR, DATA_DIR (derive path locations from
CONFIG_YAML); redirect stdout, stderr to &3 by default in setup_file,
teardown_file
2022-03-18 10:13:12 +01:00
Shivam Sandbhor
c5566e92f3
Fix 1262 pgsql conflict resolve (#1363)
* Fix api for all dbs (#1310)
* DB agnostic lapi sanitize

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Update ent

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Fix go dep mess.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-03-17 14:12:13 +01:00
mmetc
f7f4ca9541
use yq instead of envsubst (#1366) 2022-03-17 12:28:45 +01:00
mmetc
9a6a254a90
test decision list -m (#1365) 2022-03-17 12:20:08 +01:00
AlteredCoder
e4cc5fc997
Add -m flag for decisions list to display the machine (#1361)
* Add -m flag for decisions list to display the machine
2022-03-16 17:29:31 +01:00
Shivam Sandbhor
023ac9e138
Add trusted IPs which have admin API access (#1352)
* Add trusted IPs which have admin API access
2022-03-16 17:28:34 +01:00
AlteredCoder
b57eb92bbc
Allow to ignore errors when installing multiple configuration items (#1359)
* Allow to ignore errors when installing multiple configuration items
2022-03-16 17:27:30 +01:00
AlteredCoder
24797c1534
Allow cscli remove to remove with --all (#1360) 2022-03-16 17:26:31 +01:00
Shivam Sandbhor
42a1bc0260
Add query param to filter decisions by scenarios and origin (#1294)
* Add query param to filter decisions by scenarios
2022-03-16 14:37:42 +01:00
Shivam Sandbhor
bb30a3f966
Don't omit fields of bouncer in json (#1354)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-03-16 09:40:34 +01:00
Thibault "bui" Koechlin
a74a41dac5
fix #1357 (#1358) 2022-03-16 09:40:00 +01:00
mmetc
81793fe8bf
dummy plugin (#1342) 2022-03-16 09:30:04 +01:00
Shivam Sandbhor
76e97303a5
Deprecate pid_file config (#1346)
* Deprecate pid_file config

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Fix unit test

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Impl review suggestions.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-03-16 09:23:49 +01:00
Thibault "bui" Koechlin
548b0b5518
bit of doc + tests for lapi stream mode (#1356)
* bit of doc + tests for lapi stream mode
2022-03-15 17:16:33 +01:00
mmetc
b09339ae91
bats: check for yq version (#1355) 2022-03-15 15:03:56 +01:00
mmetc
6d42a8c8be
deduplicate make package, package_static (#1344) 2022-03-15 11:19:35 +01:00
mmetc
b050d27e20
bats changes to allow bouncer testing (#1345) 2022-03-15 10:40:01 +01:00
AlteredCoder
0dd37240a5
Display acquisition dir in cscli config show (#1349) 2022-03-14 18:28:31 +01:00
j-k
2cd3248431
refactor: use runtime rather than ldflags for go details (#1302) 2022-03-14 11:29:34 +01:00
Thibault "bui" Koechlin
6f68f4056e
fix #1316 : add html body (#1339)
* fix #1316 : add html body
2022-03-10 16:44:21 +01:00
mmetc
b6aca81ebd
allow "cscli completion..." without configuration file (#1340) 2022-03-10 14:57:14 +01:00
mmetc
8120fe7d5d
fix for /usr/bin/wc on freebsd (#1338)
* fix for /usr/bin/wc on freebsd
* check for python3 in bats-test
2022-03-10 13:59:10 +01:00
Manuel Sabban
bec231c1e6
Fix 1314 (#1320)
* fix https://github.com/crowdsecurity/crowdsec/issues/1314
* fix postinst logic
* fix in rpm as well

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-03-10 13:57:04 +01:00
mmetc
e7de05d6c9
don't set logger default level twice (#1336) 2022-03-10 13:56:46 +01:00
mmetc
aca37a38e7
return 1 with incomplete command line; always check error when calling cmd.Help (#1335) 2022-03-10 13:55:25 +01:00
mmetc
4e6b9597f8
fix for https://staticcheck.io/docs/checks#SA2002 (#1334) 2022-03-10 13:53:33 +01:00
Thibault "bui" Koechlin
52132ce398
fix #1157 (#1327) 2022-03-10 13:23:21 +01:00
mmetc
0c35263c29
fix bats-test for freebsd (#1333) 2022-03-10 12:19:02 +01:00
mmetc
c077668511
restore test_env.sh (#1332)
* restore test_env.sh, test 'make package' in CI
2022-03-10 09:28:42 +01:00
mmetc
7c0593c659
noop code removal, typos and lint fixes (#1329) 2022-03-09 16:15:18 +01:00
mmetc
59ad91a8ca
functional tests with bats-core (#1266) 2022-03-09 14:45:36 +01:00
mmetc
10ce45c054
allow notification plugins to work on freebsd and non-root functional tests (#1253)
* random uuid for all platforms
* check group writable and setgid; don't check group ownership
* allow user to run plugins without changing desired user/group (set them to "")
2022-03-09 12:09:50 +01:00
Thibault "bui" Koechlin
5a15f9b39b
bailout on incompatible duration format (#1326) 2022-03-08 18:18:36 +01:00
Chad Jones
19817083d1
Docker prestage - correct database directory (#1312) 2022-03-07 10:35:32 +01:00
Christophe Jauffret
a77b3e2690
Email notification plugin add sender_name option (#1297)
* add sender_name option

* default config and validation
2022-03-07 10:18:12 +01:00
mmetc
e35efc5b2d
fix check uid, gid values (#1309) 2022-03-07 10:16:34 +01:00
Thibault "bui" Koechlin
b66366c28c
Revert "Handle decisions with varying expiry for same IP (#1262)" (#1308)
This reverts commit e4f6cdfc14.
2022-03-04 10:17:31 +01:00
mmetc
c5dda0ffba
fix: deny copy folder to itself or subpath (#1299) 2022-03-02 11:30:04 +01:00
Shivam Sandbhor
c3dbe0080c
Exit syslog acquis only after server is dead (#1288) 2022-03-01 11:32:28 +01:00
Thibault "bui" Koechlin
a300d5818f
fix #1295 : deploy email plugin on RPMs (#1296)
* fix #1295 : deploy email plugin on RPMs
2022-02-28 14:59:33 +01:00
Shivam Sandbhor
0f5e922851
Warn when log file in explain command is large. (#1293)
* Warn when log file in explain command is large.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-02-28 14:57:59 +01:00
he2ss
45c1075ae0
docker image: add multi arch platforms (#1270)
* docker image: add multi arch platforms
2022-02-28 12:04:31 +01:00
Shivam Sandbhor
1928d385b0
Fix typo in explain help (#1290) 2022-02-24 13:32:18 +01:00
Thibault "bui" Koechlin
9a42190e13
fix #1274 (#1285) 2022-02-24 10:24:04 +01:00
Manuel Sabban
2763366309
switch to make build for packaging (#1279)
* switch to make build for packaging
* build as first target

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-02-18 18:09:19 +01:00
Andreas Krüger
75ba0e2bfc
Specify journalctl support (#1272)
Journalctl is only supported from the debian container.
2022-02-18 17:11:41 +01:00
blotus
fb74b2fda7
Improve LAPI performance when under high load (#1273) 2022-02-17 17:52:04 +01:00
Shivam Sandbhor
e4f6cdfc14
Handle decisions with varying expiry for same IP (#1262)
* Upgrade ent and add sql/modifier in codegen

* update db wrappers to sanitize LAPI

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-02-16 15:19:14 +01:00
Andreas Krüger
d18620858e
Create debian docker package including journalctl/systemd (#1233)
* Create debian docker package with journalctl

Co-authored-by: he2ss <hamza.essahely@gmail.com>
2022-02-15 17:10:15 +01:00
mmetc
9bc7e6ffcf
Refactor unit tests to reduce line count (#1264) 2022-02-15 12:50:33 +01:00
Manuel Sabban
afe1704aa6
fix upgrade when somthing is already listening on 8080 (#1258)
* this should fix issue #1245
* change cmdline for getting port

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-02-15 11:20:52 +01:00
mmetc
1d156ab19d
git tag detection fix (#1265) 2022-02-15 11:09:58 +01:00
mmetc
556892cf86
make test (#1249) 2022-02-14 22:21:19 +01:00
Shivam Sandbhor
43d5690432
Detect missing plugin binary wrt profiles (#1252)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-02-14 17:45:03 +01:00
mmetc
5817fa4147
configuration comments (#1255) 2022-02-14 17:09:31 +01:00
AlteredCoder
8b90f4b2b2
Upgrade download datafiles if doesn't exist (#1254) 2022-02-14 16:51:06 +01:00
AlteredCoder
5a0843852a
add IpToRange helpers and allows to have an expression with scope Range (#1260)
* add IpToRange helpers and allows to have an expression with scope Range
2022-02-14 16:50:52 +01:00
mmetc
40ab8fa738
Atoi() -> ParseInt() (#1256) 2022-02-14 14:00:42 +01:00
mmetc
ef4bf6a8ab
grammar (#1257) 2022-02-14 13:47:15 +01:00
Shivam Sandbhor
76e3612088
Check log level before dumping resp (#1243)
* Check log level before dumping resp
* Sleep longer in func tests

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-02-08 15:40:01 +01:00
mmetc
5c7c12c62d
define cwversion.System (Platform) in "make static" too; show it with --version (#1238) 2022-02-04 13:02:45 +01:00
Thibault "bui" Koechlin
dd53d19777
Make whitelist by expr debug level (#1236)
* fix #616 : simply make it at debug level, so that the user can set his node to debug level if he really wants to see this. Otherwise it can be too spammy
2022-02-03 17:04:18 +01:00
Andreas Krüger
02765a74fa
Add LOCAL_API_URL to register auto an agent (#1231) 2022-02-03 12:26:20 +01:00
Andreas Krüger
8c878b0669
Add TLS functionality from env variables (#1227)
* Add TLS functionality settings from env variables
2022-02-02 13:20:12 +01:00
Andreas Krüger
ead0a06f0c
Set custom hostname for local agent credentials (#1229)
* Set custom hostname for local agent credentials
2022-02-02 10:12:54 +01:00
Kerma Gérald
052ec6e632
email-plugin: fix install in debian package (#1219)
fix some small typo
add the email plugins to debian package

Signed-off-by: Kerma Gérald <gandalf@gk2.net>
2022-02-02 10:08:32 +01:00
Thibault "bui" Koechlin
4fc7335112
fix help message (#1228) 2022-02-02 10:06:08 +01:00
mmetc
ad28a979e9
local control flow cleanup (#1215)
removed redundant/unreachable returns, else branches, type declarations, unused variables
2022-02-01 22:08:06 +01:00
Andreas Krüger
d5f17ee377
Set LOCAL_API_URL on regeneration of local agent (#1226)
The local agent credentials file contains the URL for the local API endpoint. If you set it through the environment variable, it is not honored when regenerating the URL for the localhost machine.

This PR will set the LOCAL_API_URL on the regeneration of credentials if it's defined.
2022-02-01 17:45:04 +01:00
Kerma Gérald
6d1adb1784
Makefile: add ENV VARIABLES to override /etc/crowdsec and /var/lib/crowdsec/data (#1224)
to enhance:
35eea39db7

- add ENV VARIABLES to help defaults settings from script build (without hardcoded patch need)
- add override also in static build

Signed-off-by: Kerma Gérald <gandalf@gk2.net>
2022-02-01 17:16:17 +01:00
Adam
d2bd01d009
Prestage files and copy on init to fix bind mount issues (#1216) 2022-02-01 12:35:57 +01:00
mmetc
35eea39db7
allow Makefile to override /etc/crowdsec and /var/lib/crowdsec/data (#1221) 2022-02-01 10:34:53 +01:00
mmetc
9c9639d19b
string comparison fix (#1220) 2022-02-01 09:55:28 +01:00
mmetc
383eebf2b6
Makefile cleanup (#1211)
* rm -f => $(RM)
* PHONY targets
* remove email plugin binary on cleanup
* unused make variables
2022-02-01 09:22:47 +01:00
he2ss
5f2d7f6a65
wizard: install matched collections only (#1212) 2022-01-28 09:08:25 +01:00
Manuel Sabban
840939d489
Use override possibility in systemd file management in functional tests (#1208)
* change systemd behaviour for func tests

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-01-26 18:22:16 +01:00
Manuel Sabban
01ee09c547
Merge branch 'master' into master 2022-01-25 20:32:46 +01:00
Manuel Sabban
715c32ef9c
clean up hub dir on rpm remove (#1205)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-01-24 18:16:51 +01:00
Thibault "bui" Koechlin
dbde90d24c
fix #1200 (#1203) 2022-01-24 17:22:16 +01:00
Manuel Sabban
0814a7b19d
fix fc35 package (#1198)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-01-24 11:33:28 +01:00
mmetc
8310c10ce3
console_config.yaml -> console.yaml (#1195) 2022-01-21 11:52:23 +01:00
mmetc
240e5ad3ab
remove trailing carriage return (#1194) 2022-01-21 11:35:21 +01:00
Manuel Sabban
894388ec6c
update deps for fc35 (#1193)
* update to fc35

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-01-21 09:06:53 +01:00
blotus
19323ba4aa
fix crash on upgrade with nil last push field (#1191) 2022-01-20 18:10:40 +01:00
Manuel Sabban
363abafe4b
make console_config.yaml known to rpm system (#1190)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2022-01-20 14:31:44 +01:00
Cristian Nitescu
64a672216d
revamp docker documentation (#1189) 2022-01-20 12:29:19 +01:00
AlteredCoder
9b3db6b6bb
update notifications template (#1188)
* update notifications template
2022-01-20 11:44:26 +01:00
AlteredCoder
b93b8d9a2e
Support PGX (#1186)
* Support PGX

* support sslmode
2022-01-20 11:17:21 +01:00
Thibault "bui" Koechlin
3b04bd3b5b
upgrade grokky following https://github.com/crowdsecurity/grokky/pull/2 (#1187) 2022-01-20 10:51:29 +01:00
Shivam Sandbhor
59a537514f
Check for errors before modifying proc attrs (#1181)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-01-19 15:34:09 +01:00
Thibault "bui" Koechlin
cc1ab8c50d
switch to utc time everywhere (#1167)
* switch to utc time everywhere


Co-authored-by: alteredCoder <kevin@crowdsec.net>
2022-01-19 14:56:05 +01:00
AlteredCoder
b1a7ffb92f
fix postgreSQL count fail (#1184) 2022-01-19 14:50:53 +01:00
Thibault "bui" Koechlin
c81fc87d4e
fix #1168 (#1179)
* fix #1168
2022-01-19 11:34:40 +01:00
Thibault "bui" Koechlin
a88848009a
fix default perms for log file (#1177)
* fix default perms
2022-01-18 16:54:02 +01:00
Thibault "bui" Koechlin
a17f150e5d
fix #1170 : display full message in debug mode when syslog cannot parse (#1176)
* fix #1170 : display full message in debug mode when syslog cannot parse
2022-01-18 09:54:01 +01:00
Thibault "bui" Koechlin
9d133ea2b5
fix #1172 (#1175) 2022-01-18 08:35:49 +01:00
Thibault "bui" Koechlin
40ed810c0b
Gin upgrade (#1174)
* upgrade gin / gin-jwt, and add a new 'trusted_proxies' option to provide trusted CIDRs
2022-01-17 17:18:12 +01:00
Thibault "bui" Koechlin
6e92da76ad
lapi to capi : allow push of tainted/custom/manual decisions (#1154)
* add console command to control signal sharing
* modify metrics endpoint to add lastpush

Co-authored-by: alteredCoder <kevin@crowdsec.net>
2022-01-13 16:46:16 +01:00
mazzma12
50fb1e3df1
Replace link to Gitter with Discord in README.md (#1161) 2022-01-13 14:18:32 +01:00
Manuel Sabban
7b798c1f6d
Merge branch 'crowdsecurity:master' into master 2022-01-12 08:40:09 +01:00
blotus
cc72800f50
Update LAPI swagger (#1155) 2022-01-11 16:45:34 +01:00
Thibault "bui" Koechlin
3bca25fd6d
lists support from central api (#1074)
* lists support from central api

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2022-01-11 14:31:51 +01:00
blotus
4a11060930
Kinesis datasource (#1147) 2022-01-11 14:19:43 +01:00
Shivam Sandbhor
c109e0e7dd
Add option to print machine creds (#1149)
* Add option to print machine creds

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-01-07 16:53:56 +01:00
Shivam Sandbhor
a6e405422c
Add email notification plugin. (#1013)
* Add email notification plugin.
* Add plugin binary to gitignore

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-01-06 11:20:59 +01:00
Thibault "bui" Koechlin
6c676c4869
fix #1131 : complain when validating unknown machine (#1146) 2022-01-05 13:50:04 +01:00
Shivam Sandbhor
ba71c55492
Fix cscli inpsect json output (#1145)
* Fix cscli inpsect json output
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-01-05 10:42:27 +01:00
Thibault "bui" Koechlin
8e3004ebb3
fix race condition on repetitive trigger buckets creation (#1144) 2022-01-04 14:02:07 +01:00
Shivam Sandbhor
6c4ec64ca9
Fix json output of cscli hub list (#1143)
* Fix json output of cscli hub list
* Fix functional tests.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2022-01-04 11:49:23 +01:00
mmetc
cf175ab07e
fixed "help collections list" message (#1142)
* fixed "help collections list" message

* corrected usage of "as well"
2022-01-03 17:09:07 +01:00
Manuel Sabban
f46f0ae553
add the ability for the wizard to work on raspbian (#1136)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-12-30 14:47:51 +01:00
blotus
f86ec1c389
Docker api version negotiation (#1135) 2021-12-30 12:21:49 +01:00
he2ss
ed38ca3a73
cscli: raise error on unknown collection remove (#1133) 2021-12-30 11:32:05 +01:00
AlteredCoder
9c8ca5c73a
Alert inspect improvement / Use correct CSV output when listing in raw format (#1127) 2021-12-29 14:08:47 +01:00
Manuel Sabban
ced64cd2f5
Merge pull request #4 from crowdsecurity/fix_wizard_armhf
add the ability for the wizard to work on raspbian
2021-12-29 11:55:52 +01:00
sabban
efa06870c0 add the ability for the wizard to work on raspbian 2021-12-29 11:53:44 +01:00
Manuel Sabban
970f374b31
Merge branch 'crowdsecurity:master' into master 2021-12-29 11:51:27 +01:00
blotus
3105897f37
Allow to configure log rotation (#1130) 2021-12-28 11:59:03 +01:00
mmetc
7126f8f0ff
replaced &nbsp; (#1129) 2021-12-28 10:32:46 +01:00
Manuel Sabban
25a8ab6163
Merge branch 'crowdsecurity:master' into master 2021-12-23 15:42:37 +01:00
Thibault "bui" Koechlin
6b13d73fca
fix #1057 (#1120) 2021-12-22 15:45:41 +01:00
mmetc
64d8c0357b
added debian/README.md 2021-12-22 14:17:32 +01:00
AlteredCoder
f86e0c0a5a
don't send decisions with negative duration to bouncers (#1117) 2021-12-21 10:23:30 +01:00
mmetc
6b3e22e99a
add LD_OPTS to "go test" (#1115) 2021-12-21 10:21:34 +01:00
Manuel Sabban
755f2103be
Merge branch 'crowdsecurity:master' into master 2021-12-19 09:44:29 +01:00
Sykursen
6a3adcff0e
Upgrade metabase to v41.5 (#1109) 2021-12-17 10:29:48 +01:00
he2ss
002268b32f
wizard: add openresty logs location (#1108) 2021-12-17 10:29:00 +01:00
Thibault "bui" Koechlin
106254f020
support for cancel_on (#1105)
* cancel_on filter

* tests
2021-12-17 09:56:02 +01:00
AlteredCoder
d913ac160e
fix create alert bulk for decisions insertion (#1107)
* fix create alert bulk for decisions insertion
2021-12-16 18:26:19 +01:00
blotus
ec53fbfdab
require go 1.17 (#1104) 2021-12-16 14:39:58 +01:00
Manuel Sabban
51824d3bb8
add arg to hub func test (#1103)
* add arg to hub func test

* switch to go 1.17


Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-12-16 11:06:31 +01:00
Manuel Sabban
e6dca618a6
Merge branch 'crowdsecurity:master' into master 2021-12-15 23:10:40 +01:00
AlteredCoder
88d06260d7
add cscli decisions import (#1038)
* add cscli decisions import

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
Co-authored-by: bui <thibault@crowdsec.net>
2021-12-15 11:39:37 +01:00
Thibault "bui" Koechlin
6e272d3f88
fix links in wizard (#1098) 2021-12-15 11:31:32 +01:00
AlteredCoder
ab93cec736
return an error if we can't add a bouncer (#1085) 2021-12-14 11:09:57 +01:00
AlteredCoder
01130a5e17
add headers when using raw output (#1087)
* add headers when output raw with cscli
2021-12-14 11:09:26 +01:00
AlteredCoder
4c306187a6
fix hubtest --no-clean when failure (#1088) 2021-12-14 11:08:06 +01:00
AlteredCoder
458dcd1979
add more helpers (#1091)
* add more exprhelpers
2021-12-14 11:07:40 +01:00
Peter Dave Hello
121dcd79ba
Remove additional apk update, in Dockerfile (#1079) 2021-12-14 10:58:22 +01:00
Shivam Sandbhor
44d701a9dd
Fix null point error if server cfg is empty while doing cscli explain (#1096)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-12-14 10:31:22 +01:00
Thibault "bui" Koechlin
3c2462fbc5
Fix #1070 (#1092)
* fix #1070
2021-12-13 19:31:43 +01:00
Thibault "bui" Koechlin
e5204bc1b1
fix #1083 : do not update/overwrite 'not installed' collections sub-items on 'cscli XX upgrade' (#1089)
* fix #1083 : do not update/overwrite 'not installed' collections sub-items on 'cscli XX upgrade'
2021-12-13 19:31:16 +01:00
Manuel Sabban
fa1ee2a856
Merge pull request #3 from crowdsecurity/test_debian_install
update to use debian/install files
2021-12-13 17:42:11 +01:00
sabban
c8ec37ea4e add debian/install file 2021-12-13 17:41:25 +01:00
Manuel Sabban
9c133ee3d0
Merge branch 'crowdsecurity:master' into master 2021-12-13 17:38:57 +01:00
sabban
2e146ea3fc update to use debian/install files 2021-12-13 17:37:37 +01:00
mmetc
c7fb6a1428
enabled -> enabling (#1090) 2021-12-13 13:14:29 +01:00
mmetc
ca67be8fca
fatal if cannot add bouncer: fix for #1066 (#1067) 2021-12-13 10:30:55 +01:00
Manuel Sabban
4e6f6fe3a2
log4j vuln fix for metabase (#1082)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-12-13 10:19:20 +01:00
mmetc
7dee103b6e
typos of various nature (#1072) 2021-12-06 17:29:23 +01:00
mmetc
2a1a96c1a7
allow BUILD_TAG to be overridden when building outside a git tree (#1058) 2021-12-06 10:08:31 +01:00
AlteredCoder
4917aa23c9
Docker datasource (#1064)
* add docker datasource
2021-12-02 15:55:50 +01:00
Shivam Sandbhor
f7ad11e18e
Fix typo in README (#1063) 2021-11-30 10:09:59 +01:00
mmetc
e6c3100d69
gitignore the files generated while building the debian package (#1059) 2021-11-30 10:09:20 +01:00
mmetc
96df5d6410
Shell fixes (#1056)
* broken test

* don't expand filenames into options

* fix for ./test_env.sh -h => ./test_env.sh: line 15: usage: command not found
2021-11-30 10:08:59 +01:00
blotus
dd03d07355
optimize the flush function by deleting alerts based on their id (#1054) 2021-11-17 10:15:38 +01:00
he2ss
0652e9ed08
feature cscli|crowdsec add additional labels on crowdsec dsn run (#1053)
* feature cscli|crowdsec add additional labels on crowdsec dsn run
2021-11-17 10:08:46 +01:00
Thibault "bui" Koechlin
3c768490ba
fix #873 without breaking backward (#1052) 2021-11-15 14:16:18 +01:00
Kerma Gérald
37c2a10e21
Use math.MaxInt32 instead of math.MaxUint32 (#980)
To fix 32 bits compilation in v1.2.0
https://github.com/crowdsecurity/crowdsec/issues/979

Signed-off-by: Kerma Gérald <gandalf@gk2.net>
2021-11-15 12:14:04 +01:00
Kavin
0ffbbbec61
Add ARM docker images. (#1051) 2021-11-15 12:09:19 +01:00
Thibault "bui" Koechlin
7362828a3b
add --failures to explain feature : only display failed lines (#1048)
* add --failures to explain feature : only display failed lines

* no error no problem
2021-11-08 18:01:43 +01:00
mmetc
a4998913d8
install coreutils under alpine; do not copy notification configuration (#1044)
under Docker; assume systemctl is not running if it does not exist
2021-11-03 16:56:44 +01:00
Thibault "bui" Koechlin
8b0527bf9d
add evt. (#1045) 2021-11-03 15:17:48 +01:00
mmetc
7ca3625706
removed legacy cron script (#1040) 2021-11-02 17:00:03 +01:00
AlteredCoder
fb54388e93
Fix issue 1033 (#1034)
* Fix issue 1033
2021-11-02 12:16:33 +01:00
Thibault "bui" Koechlin
d1ce543440
Improve explain (#1039)
* improve explain feature

* nicer display for details, --verbose in favor of --debug for details
2021-11-02 12:06:01 +01:00
Shivam Sandbhor
cbada3d435
Allow using cloudwatch using iam role instead of hardcoded tokens (#1035) 2021-11-02 10:25:35 +01:00
Shivam Sandbhor
4bf996a716
Make docker start executable (#1031)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-11-02 10:24:30 +01:00
mmetc
f10187bd6d
typos (#1036) 2021-11-02 09:19:22 +01:00
mmetc
4708b509e6
.gitignore plugin binaries (#1037) 2021-11-02 09:19:10 +01:00
Shivam Sandbhor
9034bb7919
Allow user to specify key for bouncers. (#1026)
* Allow user to specify key for bouncers.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-11-02 08:37:51 +01:00
Thibault "bui" Koechlin
2b2a11fec7
Extra syslog debug (#1030)
* extra logging
2021-11-01 20:55:03 +01:00
Thibault "bui" Koechlin
02886140a7
add a --key to cscli config show (#1029)
* add a --key to cscli config show
2021-10-28 09:32:59 +02:00
AlteredCoder
cf57c89177
add name and alias in cscli console enroll (#950)
* add name and alias in cscli console enroll
2021-10-26 15:33:17 +02:00
blotus
0d46890d6b
add --limit parameter to cscli decisions list (#1025) 2021-10-26 13:33:59 +02:00
blotus
25a2d528b0
Alerts flush: Optimization of the flush mechanism (batch and limit to one job) + add cscli alerts flush command (#1024)
- Don't allow running more than one alert flush job at a time to prevent runaway CPU usage in some case. (fix High CPU after Upgrade to 1.2.0 #1022)
 - Add a cscli alerts flush command to manually flush the alerts in the database (fixes Improvement/Manual flush mechanism #1023 ).
 - Enable cascading deletion on alerts as we upgraded ent: Deleting an alert in the database will automatically delete all related decisions, events and meta
 - Add an index on alerts.id to try to improve flush performance with very big sqlite database.
- Flush alert now operates in batch
2021-10-26 13:33:45 +02:00
Thibault "bui" Koechlin
76a80380e7
don't wait on tomb if no datasources were started (#1019) 2021-10-24 11:07:45 +02:00
Thibault "bui" Koechlin
3f99330b3d
Entgo 0.9 (#1018)
* update entgo & sqlite to latest version

* schema update
2021-10-22 16:15:57 +02:00
blotus
66919924d3
don't attempt to start crowdsec if LAPI has been disabled with debconf (#1016) 2021-10-22 10:49:44 +02:00
Shivam Sandbhor
a7b1c02bd5
Fix bugs in cloudwatch acq (#991)
* Fix bugs in cloudwatch acq

- Fix concurrent writes to map streamIndexes
- Fix multiple cases of modifying while iterating on slice.
- Fix order of fetching cloudwatch events.
- Remove `startup` hack.

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Fix cloudwatch tests

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-10-22 10:35:05 +02:00
Manuel Sabban
0d075f32cd
fix perms in package installation (#1012)
* fix perms

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-10-22 10:14:15 +02:00
mmetc
b6bce96350
remove plugins with "make clean" (#1015) 2021-10-22 10:12:27 +02:00
Manuel Sabban
f8e52f1a91
Merge pull request #2 from crowdsecurity/perms
typo
2021-10-18 17:16:51 +02:00
sabban
c41234e6e1 typo 2021-10-18 17:15:28 +02:00
Manuel Sabban
0f4b2881b6
Merge pull request #1 from crowdsecurity/perms
fix perms
2021-10-18 16:09:06 +02:00
sabban
b576fd7c66 fix perms 2021-10-18 15:58:07 +02:00
he2ss
4d4d6d802c
fix #1008 + regenerate localhost credentials on start (#1009) 2021-10-14 17:02:38 +02:00
Thibault "bui" Koechlin
3bb2128bf4
fix sort :/ (#1007) 2021-10-12 19:16:24 +02:00
Thibault "bui" Koechlin
1bd6b8f7b9
Multiple fixes (#1006)
* fix #1005 : timestamp in trigger timemachine buckets

* attempt at consistent bucket order for hubtest
2021-10-12 14:09:17 +02:00
Thibault "bui" Koechlin
2961a0ed02
ensure machineID is included early enough into the alert (#1004) 2021-10-11 15:02:16 +02:00
AlteredCoder
203be9bfbf
fix typo in cscli help command (#1001)
* fix typo in cscli help command

* Update hubtest.go
2021-10-08 16:53:02 +02:00
blotus
2bc9f33e12
add ParseUri() expr helper (#994) 2021-10-08 16:50:31 +02:00
alteredCoder
6bd80dbb86 update hubtest workflow 2021-10-07 16:45:28 +02:00
AlteredCoder
cc653ce0d7
Update README.md 2021-10-07 15:04:53 +02:00
AlteredCoder
3b4c773890
fix hubtest CI (#1000) 2021-10-05 12:13:57 +02:00
AlteredCoder
0ccc69696b
Break on success when alert already has decision (#997) (#999)
* Break on success when alert already has decision (#997)

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-10-05 11:30:34 +02:00
alteredCoder
079172568a fix the CI coverage generation 2021-10-05 10:19:19 +02:00
alteredCoder
5c7f873e18 fix the coverage badge generation 2021-10-05 10:15:12 +02:00
alteredCoder
1e200d99d8 fix hubtest CI for coverage 2021-10-05 10:02:59 +02:00
alteredCoder
285351f4f9 fix hubtest CI for coverage 2021-10-05 09:56:18 +02:00
AlteredCoder
37eedce72e
add functionnal test for hubtest (#996)
* add hubtest in functionnal test
2021-10-05 09:52:55 +02:00
alteredCoder
de87d0d951 fix badge coverage generation 2021-10-04 18:07:36 +02:00
Thibault "bui" Koechlin
af4bb350c0
hubtests revamp + cscli explain (#988)
* New hubtest CI for scenarios/parsers from the hub
 * New `cscli explain` command to visualize parsers/scenarios pipeline

Co-authored-by: alteredCoder <kevin@crowdsec.net>
Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
Co-authored-by: he2ss <hamza.essahely@gmail.com>
Co-authored-by: Cristian Nitescu <cristian@crowdsec.net>
2021-10-04 17:14:52 +02:00
Thibault "bui" Koechlin
c2fd173d1e
fix node success logic (#993)
* fix node success logic : only fail node on child failure if mother node has no successfull grok
2021-09-28 17:58:07 +02:00
he2ss
fb308d5596
fix plugins logging in right level (#990) 2021-09-28 14:44:21 +02:00
he2ss
db5ffb0040
Update test env (#987)
* update test_env
2021-09-24 18:06:30 +02:00
Cristian Nitescu
9d2cd58f31
#975 Mysql default parser: parse also lines with using password NO (#976) 2021-09-24 10:49:49 +02:00
blotus
f0db3742de
fix usage of regex.Match in cloudwatch module (#986) 2021-09-23 13:52:05 +02:00
blotus
bd5c119f85
update golang.org/x/sys dep (#983) 2021-09-21 17:06:40 +02:00
blotus
e92862213e
allow coveralls job to fail, as it is down :( (#984) 2021-09-21 12:45:38 +02:00
he2ss
990599a0b5
update docker entrypoint script (#982) 2021-09-21 10:54:05 +02:00
Shivam Sandbhor
d10b5e2aa2
Update README.md (#974) 2021-09-15 15:43:01 +02:00
blotus
0ecfe75687
default to current GOOS in makefile (#973) 2021-09-14 15:42:34 +02:00
Thibault "bui" Koechlin
f5e54083c7
fix static build (#971)
* fix static build
2021-09-14 15:32:35 +02:00
Manuel Sabban
6b5f272c0a
Func tests (#970)
* stabilize func tests
* fix cold logs func tests
* add wait condition on mock server

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-13 17:33:47 +02:00
he2ss
ff400c9bca
fix docker image + install whitelists on build (#968)
* fix docker image + install whitelists on build
2021-09-13 10:48:48 +02:00
Manuel Sabban
e929ba16de
add sleep (#969)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-10 17:42:46 +02:00
he2ss
88846ac115
update docker image documentation + docker start script (#965)
* update docker image documentation  + docker start script
2021-09-10 14:59:22 +02:00
Shivam Sandbhor
cca76da2d6
Fix crash if plugin config is broken (#964)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-09-10 14:25:34 +02:00
blotus
dd41c30fba
log more information if server returns non 200 status code (#966) 2021-09-10 14:24:17 +02:00
he2ss
e651379964
add jsonExtractUnescape Helper (#962)
* add jsonExtractUnescape Helper
2021-09-10 12:43:11 +02:00
Manuel Sabban
e67fad06d3
fix error (#960)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-10 11:06:25 +02:00
blotus
652b75ee68
do no set hub_branch to master in docker (#956) 2021-09-10 09:44:06 +02:00
Manuel Sabban
e6afafa4d8
fix (#958)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-10 09:32:01 +02:00
Thibault "bui" Koechlin
21dfc784b1
remove config.patch on master (#957)
* remove config.patch on master

* fix functional tests for plugins : replace group by nobody's actual group

* fix mock http server
2021-09-09 19:12:44 +02:00
Thibault "bui" Koechlin
055a0f08cb
up drafter fix typo (#955) 2021-09-09 16:40:22 +02:00
AlteredCoder
5ae69aa293
fix stacktrace when mmdb file are not present (#935)
* fix stacktrace when mmdb file are not present
2021-09-09 16:27:30 +02:00
Manuel Sabban
9b5cb6abc9
fucntional tests fix (#952)
* add patch for the user used for starting plugins
* fix postinst
* fix fucn tests to make it work with ansible
* group_wait to 5s
* small fixes

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-09 16:24:59 +02:00
blotus
9b680ae455
refuse to start if plugins are enabled and their config is missing (#954) 2021-09-09 16:07:33 +02:00
blotus
90e354650b
add notification plugins in docker image (#951) 2021-09-09 16:05:21 +02:00
blotus
7a1b955ad1
use our fork of grokky (#953) 2021-09-09 14:46:16 +02:00
Shivam Sandbhor
e89543f725
Add functional tests for plugins (#941)
* Add functional tests for plugins

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
(cherry picked from commit 1a11c87296454aac1ebbc95c06b813ae67c91819)

* Update plugin dir in functional tests

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Update plugin process config in func tests

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>

* Robust config replacement

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-09-08 15:22:34 +02:00
AlteredCoder
078c994159
don't install all items from hub when upgrade --force (#948) 2021-09-08 11:58:51 +02:00
Manuel Sabban
21dd4851f1
make crowdsec own /etc/crowdsec/* (#947)
* make debian packages own /etc/crowdsec/*

* make package owns /etc/crowdsec/*

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-08 11:36:59 +02:00
Shivam Sandbhor
b8e24a1e0b
Make plugin runner configurable and run only registered plugins (#944)
* Make plugin runner configurable and run only registered plugins
2021-09-08 11:36:42 +02:00
Manuel Sabban
1d955f4258
fix plugins directories (#942)
* use usr over var for plugins
* add patch for debian directory
* patch rpm conf as well
* update directory structure
* modify config at build time
* use macros

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-07 17:18:55 +02:00
Thibault "bui" Koechlin
c0f14f34be
fix readme gif images (#939)
* fix readme gif images
2021-09-06 14:22:02 +02:00
Manuel Sabban
a42d99529b
fix wizard patch (#934)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-03 14:12:14 +02:00
blotus
2f937cb53a
update doc generation (#926) 2021-09-03 12:56:17 +02:00
Shivam Sandbhor
899b2abae7
Avoid code duplication for protobuf in plugins (#918)
* Avoid code duplication for protobuf in plugins

Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-09-03 12:24:59 +02:00
Thibault "bui" Koechlin
0ad6165ed2
fix release drafter + readme + remove dead readme for acquis (#933) 2021-09-03 09:07:24 +02:00
Manuel Sabban
d7d591ff84
update to use cdn for hub (#920)
* update to use cdn for hub
* add cdn for version
* fix unit tests accodingly with new cdn

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-09-02 15:17:37 +02:00
Thibault "bui" Koechlin
bed90a832e
fix #919 : display error message (#929)
* fix #919

* fix tests
2021-09-02 12:46:32 +02:00
blotus
ea640dfb6d
fix datasource prometheus metrics not being registered (#927) 2021-09-02 12:35:12 +02:00
Thibault "bui" Koechlin
589cb72d41
enforce a bit more parsing for resillience (#928) 2021-09-02 12:34:20 +02:00
AlteredCoder
4aca9941cb
allow deleting multiple machines (#930)
* allow deleting multiple machines

* allow multiple bouncers deletion

Co-authored-by: AlteredCoder <AlteredCoder>
2021-09-02 12:23:06 +02:00
blotus
e54b5beb8d
Update cscli doc for docusaurus (#924) 2021-08-31 15:03:47 +02:00
Shivam Sandbhor
b40fd36607
Add plugin interface code in protobufs package (#921)
Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
2021-08-31 14:40:17 +02:00
Thibault "bui" Koechlin
68c11dd827
don't try to send/don't notify if plugin chan is nil (#923) 2021-08-31 14:39:32 +02:00
blotus
b5d0d56a11
add support for --since in journalctl DSN (#917) 2021-08-31 12:40:22 +02:00
Manuel Sabban
ff0fb50032
Rpm fixes (#914)
* create directory

* conf file

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-26 14:48:12 +02:00
Manuel Sabban
2018f9c800
create directory (#913)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-26 14:13:00 +02:00
Manuel Sabban
c5d7509782
Rpm fixes (#912)
* remove golang dependency, as it's taken care of with golang source

* * add rpm files entry
* use more rpm macros
* fix plugins destination

* typo

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-26 13:54:39 +02:00
Manuel Sabban
5af620469a
Rpm fixes (#911)
* remove golang dependency, as it's taken care of with golang source

* * add rpm files entry
* use more rpm macros
* fix plugins destination

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-26 13:37:58 +02:00
Manuel Sabban
f1f77762b3
remove golang dependency, as it's taken care of with golang source (#909)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-26 08:50:59 +02:00
ThinkChaos
448a227079
Minor changes to specific logs (#900)
- Minor changes to specific logs
- Fix LAPI to not push signals to CAPI when disabled #907
2021-08-25 18:30:05 +02:00
blotus
488f28e3a3
Makefile: default GOARCH to the arch we are running on (#908) 2021-08-25 15:06:27 +02:00
Thibault "bui" Koechlin
c188d401a3
Improve CAPI pull management (#871)
* prepare for new consensus : thousands of ips

Co-authored-by: Sebastien Blot <sebastien@crowdsec.net>
2021-08-25 11:45:29 +02:00
Thibault "bui" Koechlin
950759f6d6
Output plugins (#878)
* Add plugin system for notifications (#857)
2021-08-25 11:43:29 +02:00
Manuel Sabban
4dbbd4b3c4
Download datafile (#895)
* add the ability to download datafile on cscli hub upgrade on files are missing
* fix stuff + lint
* fix error management

Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-08-19 09:08:20 +02:00
Shivam Sandbhor
f64f20fd53
Document scope parameter for stream API (#897)
Signed-off-by: Shivam Sandbhor <shivam@crowdsec.net>
2021-08-18 16:05:56 +02:00
blotus
1a605f33da
import debian & rpm sources (#898) 2021-08-18 13:57:06 +02:00
Nanik
b0746fbc4d
fix: add /health endpoint (#881)
* fix: add /health endpoint
2021-08-18 09:06:01 +02:00
Thibault "bui" Koechlin
05ac3ca402
if profile is in debug, log debug even if it matched the profile (#894) 2021-08-17 16:50:16 +02:00
Thibault "bui" Koechlin
25ed1c265d
fix #885 : remove dead dependencies for plugin (#891) 2021-08-17 10:32:15 +02:00
blotus
53f9837e6a
set hubBranch to master if not provided in the configuration and if crowdsec has been built without version information (#884) 2021-08-11 14:55:51 +02:00
Thibault "bui" Koechlin
2a6369658a
add a hook on fatal/panic to ensure we're logging to stderr as well (#879) 2021-08-05 08:50:08 +02:00
Thibault "bui" Koechlin
fc7369c4ea
Fix big serialized entries (#877)
* bump serialized to 8k

* handle oversized serialized entry : progressively strip its size down
2021-08-03 15:46:10 +02:00
Thibault "bui" Koechlin
01028d0a09
Goroutine leak hunt (#874)
* close the writers of gin loggers + kill the tomb of httpServer

* body close defer
2021-07-30 11:41:17 +02:00
blotus
cedfca07c2
don't wait for acquis tomb if we have no sources (#868) 2021-07-28 08:58:44 +02:00
Thibault "bui" Koechlin
34a4371dde
check if api:client is present (#867) 2021-07-23 15:10:43 +02:00
Manuel Sabban
535f0353df
should fix the unit tests (#858)
Co-authored-by: sabban <15465465+sabban@users.noreply.github.com>
2021-07-23 13:44:30 +02:00
Thibault "bui" Koechlin
657b765021
simplify, and only kill/wait on tomb when relevant (#866) 2021-07-23 11:09:56 +02:00
blotus
c56581903c
allow to override GOARCH and GOOS when building with the Makefile (#862) 2021-07-23 11:02:16 +02:00
Sofian Brabez
d657a68299
Update README for FreeBSD (#859)
Add installation instructions to use the official FreeBSD package and
remove the WIP status

Issue #651
2021-07-23 10:59:01 +02:00
Thibault "bui" Koechlin
3ecbb5a662
Create codeql-analysis.yml 2021-07-03 11:18:30 +02:00
1018 changed files with 113774 additions and 27499 deletions

6
.dockerignore Normal file
View file

@ -0,0 +1,6 @@
# We include .git in the build context because excluding it would break the
# "make release" target, which uses git to retrieve the build version and tag.
#.git
/tests
/crowdsec-v*

View file

@ -1,33 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: Bug/
labels: bug
assignees: ''
---
Please, start your issue name (after `Bug`) with the component name impacted by this feature request and a small description of the Bug. Example: `Bug/cscli: issue with ....` and remove this line :)
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Technical Information (please complete the following information):**
- OS: [e.g. Ubuntu, Redhat ..]
- Version [e.g. v0.2.0, v0.1.5 ..]
**Additional context**
Add any other context about the problem here, for example `/var/log/crowdsec.log` or error messages.

136
.github/ISSUE_TEMPLATE/bug_report.yaml vendored Normal file
View file

@ -0,0 +1,136 @@
name: Bug report
description: Report a bug encountered while operating crowdsec
labels: kind/bug
body:
- type: textarea
id: problem
attributes:
label: What happened?
description: |
Please provide as much info as possible. Not doing so may result in your bug not being addressed in a timely manner.
If this matter is security related, please disclose it privately to security@crowdsec.net
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect to happen?
validations:
required: true
- type: textarea
id: repro
attributes:
label: How can we reproduce it (as minimally and precisely as possible)?
validations:
required: true
- type: textarea
id: additional
attributes:
label: Anything else we need to know?
- type: textarea
id: Version
attributes:
label: Crowdsec version
value: |
<details>
```console
$ cscli version
# paste output here
```
</details>
validations:
required: true
- type: textarea
id: osVersion
attributes:
label: OS version
value: |
<details>
```console
# On Linux:
$ cat /etc/os-release
# paste output here
$ uname -a
# paste output here
# On Windows:
C:\> wmic os get Caption, Version, BuildNumber, OSArchitecture
# paste output here
```
</details>
- type: textarea
id: collections
attributes:
label: Enabled collections and parsers
value: |
<details>
```console
$ cscli hub list -o raw
# paste output here
```
</details>
- type: textarea
id: acquis
attributes:
label: Acquisition config
value: |
<details>
```console
# On Linux:
$ cat /etc/crowdsec/acquis.yaml /etc/crowdsec/acquis.d/*
# paste output here
# On Windows:
C:\> Get-Content C:\ProgramData\CrowdSec\config\acquis.yaml
# paste output here
</details>
- type: textarea
id: config
attributes:
label: Config show
value: |
<details>
```console
$ cscli config show
# paste output here
```
</details>
- type: textarea
id: metrics
attributes:
label: Prometheus metrics
value: |
<details>
```console
$ cscli metrics
# paste output here
```
</details>
- type: textarea
id: customizations
attributes:
label: "Related custom configs versions (if applicable) : notification plugins, custom scenarios, parsers etc."
value: |
<details>
</details>

4
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View file

@ -0,0 +1,4 @@
contact_links:
- name: Support Request
url: https://discourse.crowdsec.net
about: Support request or question relating to Crowdsec

View file

@ -1,25 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: Improvement/
labels: enhancement
assignees: ''
---
Please, start your issue name (after `improvement`) with the component name impacted by this feature request and a small description of the FR. Example: `Improvement/cscli: add this feature ....` and remove this line :)
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered** (Optional)
A clear and concise description of any alternative solutions or features you've considered.
**Example of what you imagine**
If applicable, add an example of what you would expect from this feature request.
**Additional context**
Add any other context or screenshots about the feature request here.

View file

@ -0,0 +1,27 @@
name: Feature request
description: Suggest an improvement or a new feature
body:
- type: textarea
id: feature
attributes:
label: What would you like to be added?
description: |
Significant feature requests are unlikely to make progress as issues. Please consider engaging on discord (discord.gg/crowdsec) and forums (https://discourse.crowdsec.net), instead.
value: |
For feature request please pick a kind label by removing `<!-- -->` that wrap the example lines below
<!-- /kind feature -->
<!-- Completely new feature not currently available -->
<!-- /kind enhancement -->
<!-- Feature is available but this extends or adds extra functionality -->
validations:
required: true
- type: textarea
id: rationale
attributes:
label: Why is this needed?
validations:
required: true

2
.github/buildkit.toml vendored Normal file
View file

@ -0,0 +1,2 @@
[worker.oci]
# max-parallelism = 2

10
.github/codecov.yml vendored Normal file
View file

@ -0,0 +1,10 @@
# we measure coverage but don't enforce it
# https://docs.codecov.com/docs/codecov-yaml
coverage:
status:
patch:
default:
target: 0%
project:
default:
target: 0%

104
.github/governance.yml vendored Normal file
View file

@ -0,0 +1,104 @@
version: v1
issue:
captures:
- regex: 'version: v*(.+)-[rc*]?'
github_release: true
ignore_case: true
label: 'version/$CAPTURED'
- regex: 'Platform: *(windows?|ms|wins?|microsoft).*'
label: 'os/win'
ignore_case: true
- regex: 'Platform: *(freebsd|bsd).*'
label: 'os/freebsd'
ignore_case: true
- regex: 'Platform: *(linux|linus|lin).*'
label: 'os/linux'
ignore_case: true
- regex: 'Platform: *(macos|mac|apple|macintosh|macbook).*'
label: 'os/mac'
ignore_case: true
labels:
- prefix: triage
list: ['accepted']
multiple: false
author_association:
collaborator: true
member: true
owner: true
needs:
comment: |
@$AUTHOR: Thanks for opening an issue, it is currently awaiting triage.
In the meantime, you can:
1. Check [Crowdsec Documentation](https://docs.crowdsec.net/) to see if your issue can be self resolved.
2. You can also join our [Discord](https://discord.gg/crowdsec).
3. Check [Releases](https://github.com/crowdsecurity/crowdsec/releases/latest) to make sure your agent is on the latest version.
- prefix: kind
list: ['feature', 'bug', 'packaging', 'enhancement', 'refactoring']
multiple: false
author_association:
author: true
collaborator: true
member: true
owner: true
needs:
comment: |
@$AUTHOR: There are no 'kind' label on this issue. You need a 'kind' label to start the triage process.
* `/kind feature`
* `/kind enhancement`
* `/kind refactoring`
* `/kind bug`
* `/kind packaging`
- prefix: os
list: ['mac', 'win', 'linux', 'freebsd']
multiple: true
pull_request:
labels:
- prefix: kind
multiple: false
list: [ 'feature', 'enhancement', 'fix', 'chore', 'dependencies', 'refactoring']
needs:
comment: |
@$AUTHOR: There are no 'kind' label on this PR. You need a 'kind' label to generate the release automatically.
* `/kind feature`
* `/kind enhancement`
* `/kind refactoring`
* `/kind fix`
* `/kind chore`
* `/kind dependencies`
status:
context: 'Kind Label'
description:
success: Ready for review & merge.
failure: Missing kind label to generate release automatically.
- prefix: area
list: [ "agent", "local-api", "cscli", "security", "configuration", "appsec"]
multiple: true
needs:
comment: |
@$AUTHOR: There are no area labels on this PR. You can add as many areas as you see fit.
* `/area agent`
* `/area local-api`
* `/area cscli`
* `/area appsec`
* `/area security`
* `/area configuration`
- prefix: priority
multiple: false
list: [ 'urgent', 'important' ]
author_association:
collaborator: true
member: true
owner: true

View file

@ -2,12 +2,15 @@ categories:
- title: 'New Features'
labels:
- 'new feature'
- 'kind/feature'
- title: 'Improvements'
labels:
- 'kind/enhancement'
- 'enhancement'
- 'improvement'
- title: 'Bug Fixes'
labels:
- 'kind/fix'
- 'fix'
- 'bugfix'
- 'bug'
@ -15,6 +18,10 @@ categories:
labels:
- 'documentation'
- 'doc'
- title: 'Chore / Deps'
labels:
- 'kind/dependencies'
- 'kind/chore'
tag-template: "- $TITLE @$AUTHOR (#$NUMBER)"
template: |
## Changes
@ -25,7 +32,7 @@ template: |
This product includes GeoLite2 data created by MaxMind, available from <a href="https://www.maxmind.com">https://www.maxmind.com</a>.
## Upgrading installation
## Installation
Take a look at the [upgrade instructions](https://doc.crowdsec.net/Crowdsec/v1/getting_started/upgrades/) or [installation instructions](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/).
Take a look at the [installation instructions](https://doc.crowdsec.net/docs/getting_started/install_crowdsec).

1
.github/workflows/.yamllint vendored Symbolic link
View file

@ -0,0 +1 @@
../../.yamllint

75
.github/workflows/bats-hub.yml vendored Normal file
View file

@ -0,0 +1,75 @@
name: (sub) Bats / Hub
on:
workflow_call:
secrets:
GIST_BADGES_SECRET:
required: true
GIST_BADGES_ID:
required: true
jobs:
build:
strategy:
matrix:
test-file: ["hub-1.bats", "hub-2.bats", "hub-3.bats"]
name: "Functional tests"
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: "Check out CrowdSec repository"
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: "Install bats dependencies"
env:
GOBIN: /usr/local/bin
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential daemonize jq libre2-dev
- name: "Build crowdsec and fixture"
run: make bats-clean bats-build bats-fixture BUILD_STATIC=1
- name: "Run hub tests"
run: |
./test/bin/generate-hub-tests
./test/run-tests ./test/dyn-bats/${{ matrix.test-file }} --formatter $(pwd)/test/lib/color-formatter
- name: "Collect hub coverage"
run: ./test/bin/collect-hub-coverage >> $GITHUB_ENV
- name: "Create Parsers badge"
uses: schneegans/dynamic-badges-action@v1.7.0
if: ${{ github.ref == 'refs/heads/master' && github.repository_owner == 'crowdsecurity' }}
with:
auth: ${{ secrets.GIST_BADGES_SECRET }}
gistID: ${{ secrets.GIST_BADGES_ID }}
filename: crowdsec_parsers_badge.json
label: Hub Parsers
message: ${{ env.PARSERS_COV }}
color: ${{ env.SCENARIO_BADGE_COLOR }}
- name: "Create Scenarios badge"
uses: schneegans/dynamic-badges-action@v1.7.0
if: ${{ github.ref == 'refs/heads/master' && github.repository_owner == 'crowdsecurity' }}
with:
auth: ${{ secrets.GIST_BADGES_SECRET }}
gistID: ${{ secrets.GIST_BADGES_ID }}
filename: crowdsec_scenarios_badge.json
label: Hub Scenarios
message: ${{ env.SCENARIOS_COV }}
color: ${{ env.SCENARIO_BADGE_COLOR }}

92
.github/workflows/bats-mysql.yml vendored Normal file
View file

@ -0,0 +1,92 @@
name: (sub) Bats / MySQL
on:
workflow_call:
inputs:
database_image:
required: true
type: string
jobs:
build:
name: "Functional tests"
runs-on: ubuntu-latest
timeout-minutes: 30
services:
database:
image: ${{ inputs.database_image }}
env:
MYSQL_ROOT_PASSWORD: "secret"
ports:
- 3306:3306
steps:
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: "Check out CrowdSec repository"
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: "Install bats dependencies"
env:
GOBIN: /usr/local/bin
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential daemonize jq libre2-dev
- name: "Build crowdsec and fixture"
run: |
make clean bats-build bats-fixture BUILD_STATIC=1
env:
DB_BACKEND: mysql
MYSQL_HOST: 127.0.0.1
MYSQL_PORT: 3306
MYSQL_PASSWORD: "secret"
MYSQL_USER: root
- name: "Run tests"
run: ./test/run-tests ./test/bats --formatter $(pwd)/test/lib/color-formatter
env:
DB_BACKEND: mysql
MYSQL_HOST: 127.0.0.1
MYSQL_PORT: 3306
MYSQL_PASSWORD: "secret"
MYSQL_USER: root
#
# In case you need to inspect the database status after the failure of a given test
#
# - name: "Run specified tests"
# run: ./test/run-tests test/bats/<filename>.bats -f "<test name>"
- name: Show database dump
run: ./test/instance-db dump /dev/fd/1
env:
DB_BACKEND: mysql
MYSQL_HOST: 127.0.0.1
MYSQL_PORT: 3306
MYSQL_PASSWORD: "secret"
MYSQL_USER: root
if: ${{ always() }}
- name: "Show stack traces"
run: for file in $(find /tmp/crowdsec-crash.*.txt); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: "Show crowdsec logs"
run: for file in $(find ./test/local/var/log -type f); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: "Show database logs"
run: docker logs "${{ job.services.database.id }}"
if: ${{ always() }}

85
.github/workflows/bats-postgres.yml vendored Normal file
View file

@ -0,0 +1,85 @@
name: (sub) Bats / Postgres
on:
workflow_call:
jobs:
build:
name: "Functional tests"
runs-on: ubuntu-latest
timeout-minutes: 30
services:
database:
image: postgres:16
env:
POSTGRES_PASSWORD: "secret"
ports:
- 5432:5432
options: >-
--health-cmd pg_isready -u postgres
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: "Install pg_dump v16"
# we can remove this when it's released on ubuntu-latest
run: |
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget -qO- https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo tee /etc/apt/trusted.gpg.d/pgdg.asc &>/dev/null
sudo apt update
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install postgresql-client-16
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: "Check out CrowdSec repository"
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: "Install bats dependencies"
env:
GOBIN: /usr/local/bin
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential daemonize jq libre2-dev
- name: "Build crowdsec and fixture (DB_BACKEND: pgx)"
run: |
make clean bats-build bats-fixture BUILD_STATIC=1
env:
DB_BACKEND: pgx
PGHOST: 127.0.0.1
PGPORT: 5432
PGPASSWORD: "secret"
PGUSER: postgres
- name: "Run tests (DB_BACKEND: pgx)"
run: ./test/run-tests ./test/bats --formatter $(pwd)/test/lib/color-formatter
env:
DB_BACKEND: pgx
PGHOST: 127.0.0.1
PGPORT: 5432
PGPASSWORD: "secret"
PGUSER: postgres
- name: "Show stack traces"
run: for file in $(find /tmp/crowdsec-crash.*.txt); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: "Show crowdsec logs"
run: for file in $(find ./test/local/var/log -type f); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: "Show database logs"
run: docker logs "${{ job.services.database.id }}"
if: ${{ always() }}

View file

@ -0,0 +1,84 @@
name: (sub) Bats / sqlite + coverage
on:
workflow_call:
env:
TEST_COVERAGE: true
jobs:
build:
name: "Functional tests"
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: "Check out CrowdSec repository"
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: true
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: "Install bats dependencies"
env:
GOBIN: /usr/local/bin
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential daemonize jq libre2-dev
- name: "Build crowdsec and fixture"
run: |
make clean bats-build bats-fixture BUILD_STATIC=1
- name: "Run tests"
run: ./test/run-tests ./test/bats --formatter $(pwd)/test/lib/color-formatter
- name: "Collect coverage data"
run: |
go tool covdata textfmt -i test/coverage -o coverage-bats-raw.out
# filter out unwanted packages, should match the argument to "go-acc --ignore"
grep -v \
-e '/pkg/database' \
-e '/plugins/notifications' \
-e '/pkg/protobufs' \
-e '/pkg/cwversions' \
-e '/pkg/models' \
< coverage-bats-raw.out \
> coverage-bats.out
#
# In case you need to inspect the database status after the failure of a given test
#
# - name: "Run specified tests"
# run: ./test/run-tests test/bats/<filename>.bats -f "<test name>"
- name: "Show database dump"
run: |
./test/instance-crowdsec stop
sqlite3 ./test/local/var/lib/crowdsec/data/crowdsec.db '.dump'
if: ${{ always() }}
- name: "Show stack traces"
run: for file in $(find /tmp/crowdsec-crash.*.txt); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: "Show crowdsec logs"
run: for file in $(find ./test/local/var/log -type f); do echo ">>>>> $file"; cat $file; echo; done
if: ${{ always() }}
- name: Upload crowdsec coverage to codecov
uses: codecov/codecov-action@v4
with:
files: ./coverage-bats.out
flags: bats
token: ${{ secrets.CODECOV_TOKEN }}

53
.github/workflows/bats.yml vendored Normal file
View file

@ -0,0 +1,53 @@
---
# This workflow is actually running
# only functional tests, but the
# name is used for the badge in README.md
name: Tests
# Main workflow for functional tests, it calls all the others through parallel jobs.
#
# https://docs.github.com/en/actions/using-workflows/reusing-workflows
#
# There is no need to merge coverage output because codecov.io should take care of that.
on:
push:
branches:
- master
- releases/**
paths-ignore:
- "README.md"
pull_request:
branches:
- master
- releases/**
paths-ignore:
- "README.md"
jobs:
sqlite:
uses: ./.github/workflows/bats-sqlite-coverage.yml
# Jobs for Postgres (and sometimes MySQL) can have failing tests on GitHub
# CI, but they pass when run on devs' machines or in the release checks. We
# disable them here by default. Remove if...false to enable them.
mariadb:
uses: ./.github/workflows/bats-mysql.yml
with:
database_image: mariadb:latest
mysql:
uses: ./.github/workflows/bats-mysql.yml
with:
database_image: mysql:latest
postgres:
uses: ./.github/workflows/bats-postgres.yml
hub:
uses: ./.github/workflows/bats-hub.yml
secrets:
GIST_BADGES_ID: ${{ secrets.GIST_BADGES_ID }}
GIST_BADGES_SECRET: ${{ secrets.GIST_BADGES_SECRET }}

35
.github/workflows/cache-cleanup.yaml vendored Normal file
View file

@ -0,0 +1,35 @@
# https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#managing-caches
name: cleanup caches by a branch
on:
pull_request:
types:
- closed
jobs:
cleanup:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Cleanup
run: |
gh extension install actions/gh-actions-cache
REPO=${{ github.repository }}
BRANCH="refs/pull/${{ github.event.pull_request.number }}/merge"
echo "Fetching list of cache key"
cacheKeysForPR=$(gh actions-cache list -R $REPO -B $BRANCH | cut -f 1 )
## Setting this to not fail the workflow while deleting cache keys.
set +e
echo "Deleting caches..."
for cacheKey in $cacheKeysForPR
do
gh actions-cache delete $cacheKey -R $REPO -B $BRANCH --confirm
done
echo "Done"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -0,0 +1,46 @@
name: build-msi (windows)
on:
release:
types:
- prereleased
push:
branches:
- master
- releases/**
paths:
- windows/installer/*.wxs
- .github/workflows/ci-windows-build-msi.yml
pull_request:
branches:
- master
- releases/**
paths:
- windows/installer/*.wxs
- .github/workflows/ci-windows-build-msi.yml
jobs:
build:
name: Build
runs-on: windows-2019
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: false
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: Build
run: make windows_installer BUILD_RE2_WASM=1
- name: Upload MSI
uses: actions/upload-artifact@v4
with:
path: crowdsec*msi
name: crowdsec.msi

View file

@ -1,80 +0,0 @@
name: Functional tests
on:
push:
branches:
- master
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
pull_request:
branches:
- master
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
jobs:
build:
name: Install generated release and perform functional tests
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- id: keydb
uses: pozetroninc/github-action-get-latest-release@master
with:
owner: crowdsecurity
repo: crowdsec
excludes: draft
- name: Build release
run: BUILD_VERSION=${{ steps.keydb.outputs.release }} make release
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: Install release
run: |
cd crowdsec-${{ steps.keydb.outputs.release }}
sudo ./wizard.sh --unattended
- name: "Test post-install base"
run: |
cd scripts/func_tests/
./tests_post-install_0base.sh
- name: "Test post-install bouncer"
run: |
cd scripts/func_tests/
./tests_post-install_1bouncers.sh
- name: "Test post-install bouncer"
run: |
cd scripts/func_tests/
./tests_post-install_2collections.sh
- name: "Test post-install bouncer"
run: |
cd scripts/func_tests/
./tests_post-install_3machines.sh
- name: "Test post-install ip management"
run: |
cd scripts/func_tests/
./tests_post-install_99ip_mgmt.sh
- name: "Test cold logs"
run: |
cd scripts/func_tests/
./tests_post-install_4cold-logs.sh
- name: "Test simulation"
run: |
cd scripts/func_tests/
./tests_post-install_5simulation.sh
- name: "Uninstall"
run: sudo ./wizard.sh --uninstall
- name: "Test post remove"
run: |
cd scripts/func_tests/
bash -x ./tests_post-remove_0base.sh

View file

@ -1,75 +0,0 @@
name: tests
#those env variables are for localstack, so we can emulate aws services
env:
AWS_HOST: localstack
SERVICES: cloudwatch,logs
#those are to mimic aws config
AWS_ACCESS_KEY_ID: AKIAIOSFODNN7EXAMPLE
AWS_SECRET_ACCESS_KEY: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
AWS_REGION: us-east-1
#and to override our endpoint in aws sdk
AWS_ENDPOINT_FORCE: http://localhost:4566
on:
push:
branches: [ master ]
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
pull_request:
branches: [ master ]
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
jobs:
build:
name: Build
runs-on: ubuntu-latest
services:
localstack:
image: localstack/localstack:0.12.11
ports:
- 4566:4566 # Localstack exposes all services on same port
env:
SERVICES: ${{ env.SERVICES }}
DEBUG: ""
DATA_DIR: ""
LAMBDA_EXECUTOR: ""
KINESIS_ERROR_PROBABILITY: ""
DOCKER_HOST: unix:///var/run/docker.sock
HOST_TMP_FOLDER: "/tmp"
HOSTNAME_EXTERNAL: ${{ env.AWS_HOST }} # Required so that resource urls are provided properly
# e.g sqs url will get localhost if we don't set this env to map our service
options: >-
--name=localstack
--health-cmd="curl -sS 127.0.0.1:4566 || exit 1"
--health-interval=10s
--health-timeout=5s
--health-retries=3
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Build
run: make build && go get -u github.com/jandelgado/gcov2lcov
- name: All tests
run: go test -coverprofile=coverage.out -covermode=atomic ./...
- name: gcov2lcov
uses: jandelgado/gcov2lcov-action@v1.0.2
with:
infile: coverage.out
outfile: coverage.txt
- name: Coveralls
uses: coverallsapp/github-action@master
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
path-to-lcov: coverage.txt

View file

@ -1,32 +0,0 @@
name: golangci-lint
on:
push:
tags:
- v*
branches:
- master
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
pull_request:
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
jobs:
golangci:
name: lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: golangci-lint
uses: golangci/golangci-lint-action@v2
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.29
# Optional: golangci-lint command line arguments.
args: --issues-exit-code=0 --timeout 5m
only-new-issues: true

View file

@ -1,51 +0,0 @@
name: Hub-CI
on:
push:
branches: [ master ]
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
pull_request:
branches: [ master ]
paths-ignore:
- 'docs/**'
- 'mkdocs.yml'
- 'README.md'
jobs:
build:
name: Hub Parser/Scenario tests
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Build release
run: make release
- name: clone and build hub CI tool
run: |
git clone https://github.com/crowdsecurity/hub-tests.git
cd hub-tests
make
- id: keydb
uses: pozetroninc/github-action-get-latest-release@master
with:
owner: crowdsecurity
repo: crowdsec
excludes: draft
- name: Create crowdsec test env with all parsers from the release
run: |
cd crowdsec-${{ steps.keydb.outputs.release }}
./test_env.sh
cd tests
for i in `./cscli -c dev.yaml parsers list -a -o json | jq -r ".[].name" ` ; do
./cscli -c dev.yaml parsers install $i ;
done

View file

@ -5,17 +5,17 @@ on:
# branches to consider in the event; optional, defaults to all
branches:
- master
- releases/**
jobs:
update_release_draft:
runs-on: ubuntu-latest
steps:
# Drafts your next Release notes as Pull Requests are merged into "master"
- uses: release-drafter/release-drafter@v5
- uses: release-drafter/release-drafter@v6
with:
config-name: release-drafter.yml
# (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml
# config-name: my-config.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View file

@ -1,3 +1,4 @@
# yamllint disable rule:comments
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
@ -13,10 +14,14 @@ name: "CodeQL"
on:
push:
branches: [ master ]
branches:
- master
- releases/**
pull_request:
# The branches below must be a subset of the branches above
branches: [ master ]
branches:
- master
- releases/**
schedule:
- cron: '15 16 * * 2'
@ -39,11 +44,20 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
uses: actions/checkout@v4
with:
# required to pick up tags for BUILD_VERSION
fetch-depth: 0
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
cache-dependency-path: "**/go.sum"
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@ -53,8 +67,8 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# - name: Autobuild
# uses: github/codeql-action/autobuild@v3
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@ -63,9 +77,8 @@ jobs:
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- run: |
make clean build BUILD_RE2_WASM=1
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1
uses: github/codeql-action/analyze@v3

View file

@ -1,20 +0,0 @@
name: Dispatch to hub when creating pre-release
on:
push:
# branches to consider in the event; optional, defaults to all
branches:
- master
jobs:
dispatch:
name: dispatch to hub-tests
runs-on: ubuntu-latest
steps:
- name: Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DISPATCH_TOKEN }}
event-type: trigger_ci_hub
repository: crowdsecurity/hub
client-payload: '{"version": "${{ steps.keydb.outputs.release }}"}'

View file

@ -1,24 +0,0 @@
name: Dispatch to hub when creating pre-release
on:
release:
types: prereleased
jobs:
dispatch:
name: dispatch to hub-tests
runs-on: ubuntu-latest
steps:
- id: keydb
uses: pozetroninc/github-action-get-latest-release@master
with:
owner: crowdsecurity
repo: crowdsec
excludes: prerelease, draft
- name: Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DISPATCH_TOKEN }}
event-type: create_branch
repository: crowdsecurity/hub
client-payload: '{"version": "${{ steps.keydb.outputs.release }}"}'

View file

@ -1,24 +0,0 @@
name: Dispatch to hub-tests when creating pre-release
on:
release:
types: prereleased
jobs:
dispatch:
name: dispatch to hub-tests
runs-on: ubuntu-latest
steps:
- id: keydb
uses: pozetroninc/github-action-get-latest-release@master
with:
owner: crowdsecurity
repo: crowdsec
excludes: prerelease, draft
- name: Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DISPATCH_TOKEN }}
event-type: create_tag
repository: crowdsecurity/hub-tests
client-payload: '{"version": "${{ steps.keydb.outputs.release }}"}'

View file

@ -1,24 +0,0 @@
name: Dispatch to hub when deleting pre-release
on:
release:
types: deleted
jobs:
dispatch:
name: dispatch to hub-tests
runs-on: ubuntu-latest
steps:
- id: keydb
uses: pozetroninc/github-action-get-latest-release@master
with:
owner: crowdsecurity
repo: crowdsec
excludes: prerelease, draft
- name: Repository Dispatch
uses: peter-evans/repository-dispatch@v1
with:
token: ${{ secrets.DISPATCH_TOKEN }}
event-type: delete_branch
repository: crowdsecurity/hub
client-payload: '{"version": "${{ steps.keydb.outputs.release }}"}'

87
.github/workflows/docker-tests.yml vendored Normal file
View file

@ -0,0 +1,87 @@
name: Test Docker images
on:
push:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
pull_request:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
jobs:
test_flavor:
strategy:
# we could test all the flavors in a single pytest job,
# but let's split them (and the image build) in multiple runners for performance
matrix:
# can be slim, full or debian (no debian slim).
flavor: ["slim", "debian"]
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Check out the repo
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
config: .github/buildkit.toml
- name: "Build image"
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile${{ matrix.flavor == 'debian' && '.debian' || '' }}
tags: crowdsecurity/crowdsec:test${{ matrix.flavor == 'full' && '' || '-' }}${{ matrix.flavor == 'full' && '' || matrix.flavor }}
target: ${{ matrix.flavor == 'debian' && 'full' || matrix.flavor }}
platforms: linux/amd64
load: true
cache-from: type=gha
cache-to: type=gha,mode=min
- name: "Setup Python"
uses: actions/setup-python@v5
with:
python-version: "3.x"
- name: "Install pipenv"
run: |
cd docker/test
python -m pip install --upgrade pipenv wheel
#- name: "Cache virtualenvs"
# id: cache-pipenv
# uses: actions/cache@v4
# with:
# path: ~/.local/share/virtualenvs
# key: ${{ runner.os }}-pipenv-${{ hashFiles('**/Pipfile.lock') }}
- name: "Install dependencies"
#if: steps.cache-pipenv.outputs.cache-hit != 'true'
run: |
cd docker/test
pipenv install --deploy
- name: "Create Docker network"
run: docker network create net-test
- name: "Run tests"
env:
CROWDSEC_TEST_VERSION: test
CROWDSEC_TEST_FLAVORS: ${{ matrix.flavor }}
CROWDSEC_TEST_NETWORK: net-test
CROWDSEC_TEST_TIMEOUT: 90
# running serially to reduce test flakiness
run: |
cd docker/test
pipenv run pytest -n 1 --durations=0 --color=yes

66
.github/workflows/go-tests-windows.yml vendored Normal file
View file

@ -0,0 +1,66 @@
name: Go tests (windows)
on:
push:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
pull_request:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
env:
RICHGO_FORCE_COLOR: 1
CROWDSEC_FEATURE_DISABLE_HTTP_RETRY_BACKOFF: true
jobs:
build:
name: "Build + tests"
runs-on: windows-2022
steps:
- name: Check out CrowdSec repository
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: false
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: Build
run: |
make build BUILD_RE2_WASM=1
- name: Run tests
run: |
go install github.com/kyoh86/richgo@v0.3.10
go test -coverprofile coverage.out -covermode=atomic ./... > out.txt
if(!$?) { cat out.txt | sed 's/ *coverage:.*of statements in.*//' | richgo testfilter; Exit 1 }
cat out.txt | sed 's/ *coverage:.*of statements in.*//' | richgo testfilter
- name: Upload unit coverage to Codecov
uses: codecov/codecov-action@v4
with:
files: coverage.out
flags: unit-windows
token: ${{ secrets.CODECOV_TOKEN }}
- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
version: v1.57
args: --issues-exit-code=1 --timeout 10m
only-new-issues: false
# the cache is already managed above, enabling it here
# gives errors when extracting
skip-pkg-cache: true
skip-build-cache: true

167
.github/workflows/go-tests.yml vendored Normal file
View file

@ -0,0 +1,167 @@
---
# This workflow is actually running
# tests (with localstack) but the
# name is used for the badge in README.md
name: Build
on:
push:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
pull_request:
branches:
- master
- releases/**
paths-ignore:
- 'README.md'
# these env variables are for localstack, so we can emulate aws services
env:
RICHGO_FORCE_COLOR: 1
AWS_HOST: localstack
# these are to mimic aws config
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
AWS_REGION: us-east-1
CROWDSEC_FEATURE_DISABLE_HTTP_RETRY_BACKOFF: true
jobs:
build:
name: "Build + tests"
runs-on: ubuntu-latest
services:
localstack:
image: localstack/localstack:3.0
ports:
- 4566:4566 # Localstack exposes all services on the same port
env:
DEBUG: ""
LAMBDA_EXECUTOR: ""
KINESIS_ERROR_PROBABILITY: ""
DOCKER_HOST: unix:///var/run/docker.sock
KINESIS_INITIALIZE_STREAMS: ${{ env.KINESIS_INITIALIZE_STREAMS }}
LOCALSTACK_HOST: ${{ env.AWS_HOST }} # Required so that resource urls are provided properly
# e.g sqs url will get localhost if we don't set this env to map our service
options: >-
--name=localstack
--health-cmd="curl -sS 127.0.0.1:4566 || exit 1"
--health-interval=10s
--health-timeout=5s
--health-retries=3
zoo1:
image: confluentinc/cp-zookeeper:7.4.3
ports:
- "2181:2181"
env:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_SERVER_ID: 1
ZOOKEEPER_SERVERS: zoo1:2888:3888
options: >-
--name=zoo1
--health-cmd "jps -l | grep zookeeper"
--health-interval 10s
--health-timeout 5s
--health-retries 5
kafka1:
image: crowdsecurity/kafka-ssl
ports:
- "9093:9093"
- "9092:9092"
- "9999:9999"
env:
KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://127.0.0.1:19092,LISTENER_DOCKER_EXTERNAL://127.0.0.1:9092,LISTENER_DOCKER_EXTERNAL_SSL://127.0.0.1:9093
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL:PLAINTEXT,LISTENER_DOCKER_EXTERNAL_SSL:SSL
KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL
KAFKA_ZOOKEEPER_CONNECT: "zoo1:2181"
KAFKA_BROKER_ID: 1
KAFKA_LOG4J_LOGGERS: "kafka.controller=INFO,kafka.producer.async.DefaultEventHandler=INFO,state.change.logger=INFO"
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
KAFKA_JMX_PORT: 9999
KAFKA_JMX_HOSTNAME: "127.0.0.1"
KAFKA_AUTHORIZER_CLASS_NAME: kafka.security.authorizer.AclAuthorizer
KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND: "true"
KAFKA_SSL_KEYSTORE_FILENAME: kafka.kafka1.keystore.jks
KAFKA_SSL_KEYSTORE_CREDENTIALS: kafka1_keystore_creds
KAFKA_SSL_KEY_CREDENTIALS: kafka1_sslkey_creds
KAFKA_SSL_TRUSTSTORE_FILENAME: kafka.kafka1.truststore.jks
KAFKA_SSL_TRUSTSTORE_CREDENTIALS: kafka1_truststore_creds
KAFKA_SSL_ENABLED_PROTOCOLS: TLSv1.2
KAFKA_SSL_PROTOCOL: TLSv1.2
KAFKA_SSL_CLIENT_AUTH: none
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
options: >-
--name=kafka1
--health-cmd "kafka-broker-api-versions --version"
--health-interval 10s
--health-timeout 10s
--health-retries 5
loki:
image: grafana/loki:2.9.1
ports:
- "3100:3100"
options: >-
--name=loki1
--health-cmd "wget -q -O - http://localhost:3100/ready | grep 'ready'"
--health-interval 30s
--health-timeout 10s
--health-retries 5
--health-start-period 30s
steps:
- name: Check out CrowdSec repository
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: false
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: Create localstack streams
run: |
aws --endpoint-url=http://127.0.0.1:4566 --region us-east-1 kinesis create-stream --stream-name stream-1-shard --shard-count 1
aws --endpoint-url=http://127.0.0.1:4566 --region us-east-1 kinesis create-stream --stream-name stream-2-shards --shard-count 2
- name: Build and run tests, static
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential libre2-dev
go install github.com/ory/go-acc@v0.2.8
go install github.com/kyoh86/richgo@v0.3.10
set -o pipefail
make build BUILD_STATIC=1
make go-acc | sed 's/ *coverage:.*of statements in.*//' | richgo testfilter
- name: Run tests again, dynamic
run: |
make clean build
set -o pipefail
make go-acc | sed 's/ *coverage:.*of statements in.*//' | richgo testfilter
- name: Upload unit coverage to Codecov
uses: codecov/codecov-action@v4
with:
files: coverage.out
flags: unit-linux
token: ${{ secrets.CODECOV_TOKEN }}
- name: golangci-lint
uses: golangci/golangci-lint-action@v4
with:
version: v1.57
args: --issues-exit-code=1 --timeout 10m
only-new-issues: false
# the cache is already managed above, enabling it here
# gives errors when extracting
skip-pkg-cache: true
skip-build-cache: true

30
.github/workflows/governance-bot.yaml vendored Normal file
View file

@ -0,0 +1,30 @@
# .github/workflow/governance.yml
on:
pull_request_target:
types: [ synchronize, opened, labeled, unlabeled ]
issues:
types: [ opened, labeled, unlabeled ]
issue_comment:
types: [ created ]
# You can use permissions to modify the default permissions granted to the GITHUB_TOKEN,
# adding or removing access as required, so that you only allow the minimum required access.
permissions:
contents: read
issues: write
pull-requests: write
statuses: write
checks: write
jobs:
governance:
name: Governance
runs-on: ubuntu-latest
steps:
# Semantic versioning, lock to different version: v2, v2.0 or a commit hash.
- uses: BirthdayResearch/oss-governance-bot@v4
with:
# You can use a PAT to post a comment/label/status so that it shows up as a user instead of github-actions
github-token: ${{secrets.GITHUB_TOKEN}} # optional, default to '${{ github.token }}'
config-path: .github/governance.yml # optional, default to '.github/governance.yml'

View file

@ -0,0 +1,47 @@
name: (push-master) Publish latest Docker images
on:
push:
branches: [ master ]
paths:
- 'pkg/**'
- 'cmd/**'
- 'mk/**'
- 'docker/docker_start.sh'
- 'docker/config.yaml'
- '.github/workflows/publish-docker-master.yml'
- '.github/workflows/publish-docker.yml'
- 'Dockerfile'
- 'Dockerfile.debian'
- 'go.mod'
- 'go.sum'
- 'Makefile'
jobs:
dev-alpine:
uses: ./.github/workflows/publish-docker.yml
with:
platform: linux/amd64
crowdsec_version: ""
image_version: dev
latest: false
push: true
slim: false
debian: false
secrets:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
dev-debian:
uses: ./.github/workflows/publish-docker.yml
with:
platform: linux/amd64
crowdsec_version: ""
image_version: dev
latest: false
push: true
slim: false
debian: true
secrets:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}

View file

@ -0,0 +1,48 @@
name: (manual) Publish Docker images
on:
workflow_dispatch:
inputs:
image_version:
description: Docker Image version (base tag, i.e. v1.6.0-2)
required: true
crowdsec_version:
description: Crowdsec version (BUILD_VERSION)
required: true
latest:
description: Overwrite latest (and slim) tags?
default: false
required: true
push:
description: Really push?
default: false
required: true
jobs:
alpine:
uses: ./.github/workflows/publish-docker.yml
secrets:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
with:
image_version: ${{ github.event.inputs.image_version }}
crowdsec_version: ${{ github.event.inputs.crowdsec_version }}
latest: ${{ github.event.inputs.latest == 'true' }}
push: ${{ github.event.inputs.push == 'true' }}
slim: true
debian: false
platform: "linux/amd64,linux/386,linux/arm64,linux/arm/v7,linux/arm/v6"
debian:
uses: ./.github/workflows/publish-docker.yml
secrets:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
with:
image_version: ${{ github.event.inputs.image_version }}
crowdsec_version: ${{ github.event.inputs.crowdsec_version }}
latest: ${{ github.event.inputs.latest == 'true' }}
push: ${{ github.event.inputs.push == 'true' }}
slim: false
debian: true
platform: "linux/amd64,linux/386,linux/arm64"

125
.github/workflows/publish-docker.yml vendored Normal file
View file

@ -0,0 +1,125 @@
name: (sub) Publish Docker images
on:
workflow_call:
secrets:
DOCKER_USERNAME:
required: true
DOCKER_PASSWORD:
required: true
inputs:
platform:
required: true
type: string
image_version:
required: true
type: string
crowdsec_version:
required: true
type: string
latest:
required: true
type: boolean
push:
required: true
type: boolean
slim:
required: true
type: boolean
debian:
required: true
type: boolean
jobs:
push_to_registry:
name: Push Docker image to registries
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
with:
config: .github/buildkit.toml
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Login to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.repository_owner }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Prepare (slim)
if: ${{ inputs.slim }}
id: slim
run: |
DOCKERHUB_IMAGE=${{ secrets.DOCKER_USERNAME }}/crowdsec
GHCR_IMAGE=ghcr.io/${{ github.repository_owner }}/crowdsec
VERSION=${{ inputs.image_version }}
DEBIAN=${{ inputs.debian && '-debian' || '' }}
TAGS="${DOCKERHUB_IMAGE}:${VERSION}-slim${DEBIAN},${GHCR_IMAGE}:${VERSION}-slim${DEBIAN}"
if [[ ${{ inputs.latest }} == true ]]; then
TAGS=$TAGS,${DOCKERHUB_IMAGE}:slim${DEBIAN},${GHCR_IMAGE}:slim${DEBIAN}
fi
echo "tags=${TAGS}" >> $GITHUB_OUTPUT
echo "created=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
- name: Prepare (full)
id: full
run: |
DOCKERHUB_IMAGE=${{ secrets.DOCKER_USERNAME }}/crowdsec
GHCR_IMAGE=ghcr.io/${{ github.repository_owner }}/crowdsec
VERSION=${{ inputs.image_version }}
DEBIAN=${{ inputs.debian && '-debian' || '' }}
TAGS="${DOCKERHUB_IMAGE}:${VERSION}${DEBIAN},${GHCR_IMAGE}:${VERSION}${DEBIAN}"
if [[ ${{ inputs.latest }} == true ]]; then
TAGS=$TAGS,${DOCKERHUB_IMAGE}:latest${DEBIAN},${GHCR_IMAGE}:latest${DEBIAN}
fi
echo "tags=${TAGS}" >> $GITHUB_OUTPUT
echo "created=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
- name: Build and push image (slim)
if: ${{ inputs.slim }}
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile${{ inputs.debian && '.debian' || '' }}
push: ${{ inputs.push }}
tags: ${{ steps.slim.outputs.tags }}
target: slim
platforms: ${{ inputs.platform }}
labels: |
org.opencontainers.image.source=${{ github.event.repository.html_url }}
org.opencontainers.image.created=${{ steps.slim.outputs.created }}
org.opencontainers.image.revision=${{ github.sha }}
build-args: |
BUILD_VERSION=${{ inputs.crowdsec_version }}
- name: Build and push image (full)
uses: docker/build-push-action@v5
with:
context: .
file: ./Dockerfile${{ inputs.debian && '.debian' || '' }}
push: ${{ inputs.push }}
tags: ${{ steps.full.outputs.tags }}
target: full
platforms: ${{ inputs.platform }}
labels: |
org.opencontainers.image.source=${{ github.event.repository.html_url }}
org.opencontainers.image.created=${{ steps.full.outputs.created }}
org.opencontainers.image.revision=${{ github.sha }}
build-args: |
BUILD_VERSION=${{ inputs.crowdsec_version }}

View file

@ -0,0 +1,40 @@
# .github/workflows/build-docker-image.yml
name: Release
on:
release:
types:
- prereleased
permissions:
# Use write for: hub release edit
contents: write
jobs:
build:
name: Build and upload binary package
runs-on: ubuntu-latest
steps:
- name: Check out code into the Go module directory
uses: actions/checkout@v4
with:
fetch-depth: 0
submodules: false
- name: "Set up Go"
uses: actions/setup-go@v5
with:
go-version: "1.22.2"
- name: Build the binaries
run: |
sudo apt -qq -y -o=Dpkg::Use-Pty=0 install build-essential libre2-dev
make vendor release BUILD_STATIC=1
- name: Upload to release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
tag_name="${GITHUB_REF##*/}"
gh release upload "$tag_name" crowdsec-release.tgz vendor.tgz *-vendor.tar.xz

View file

@ -1,103 +0,0 @@
# .github/workflows/build-docker-image.yml
name: build
on:
release:
types: prereleased
jobs:
build:
name: Build and upload binary package
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Build the binaries
run: make release
- name: Upload to release
uses: JasonEtco/upload-to-release@master
with:
args: crowdsec-release.tgz application/x-gzip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
build_static:
name: Build and upload binary package
runs-on: ubuntu-latest
steps:
- name: Set up Go 1.13
uses: actions/setup-go@v1
with:
go-version: 1.13
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Build the binaries
run: make release_static
- name: Upload to release
uses: JasonEtco/upload-to-release@master
with:
args: crowdsec-release-static.tgz application/x-gzip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
test_tarball:
strategy:
matrix:
tarball:
- name: crowdsec-release
- name: crowdsec-release-static
name: Download tarball and run functional tests
runs-on: ubuntu-20.04
needs: [build, build_static]
steps:
- id: fetch_prerelease_version
uses: pozetroninc/github-action-get-latest-release@master
with:
repository: crowdsecurity/crowdsec
excludes: draft
- name: download tarball
run: wget -qO - https://github.com/crowdsecurity/crowdsec/releases/download/${{ steps.fetch_prerelease_version.outputs.release }}/${{ matrix.tarball.name }}.tgz | tar xvzf -
- name: "Force machineid"
run: |
sudo chmod +w /etc/machine-id
echo githubciXXXXXXXXXXXXXXXXXXXXXXXX | sudo tee /etc/machine-id
- name: Install release
run: |
cd crowdsec-${{ steps.fetch_prerelease_version.outputs.release }}
sudo ./wizard.sh --unattended
- name: Check out code to get functional tests scripts
uses: actions/checkout@v2
- name: "Test post-install base"
run: |
cd scripts/func_tests/
./tests_post-install_0base.sh
- name: "Test post-install bouncer"
run: |
cd scripts/func_tests/
./tests_post-install_1bouncers.sh
- name: "Test post-install collections"
run: |
cd scripts/func_tests/
./tests_post-install_2collections.sh
- name: "Test post-install macines"
run: |
cd scripts/func_tests/
./tests_post-install_3machines.sh
- name: "Test post-install ip management"
run: |
cd scripts/func_tests/
./tests_post-install_99ip_mgmt.sh
- name: "Test cold logs"
run: |
cd scripts/func_tests/
./tests_post-install_4cold-logs.sh
- name: "Uninstall"
run: sudo ./wizard.sh --uninstall
- name: "Test post remove"
run: |
cd scripts/func_tests/
bash -x ./tests_post-remove_0base.sh

View file

@ -1,56 +0,0 @@
name: Publish Docker image
on:
release:
types:
- released
- prereleased
jobs:
push_to_registry:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
-
name: Check out the repo
uses: actions/checkout@v2
-
name: Prepare
id: prep
run: |
DOCKER_IMAGE=crowdsecurity/crowdsec
VERSION=edge
if [[ $GITHUB_REF == refs/tags/* ]]; then
VERSION=${GITHUB_REF#refs/tags/}
elif [[ $GITHUB_REF == refs/heads/* ]]; then
VERSION=$(echo ${GITHUB_REF#refs/heads/} | sed -E 's#/+#-#g')
elif [[ $GITHUB_REF == refs/pull/* ]]; then
VERSION=pr-${{ github.event.number }}
fi
TAGS="${DOCKER_IMAGE}:${VERSION}"
if [[ ${{ github.event.action }} == released ]]; then
TAGS=$TAGS,${DOCKER_IMAGE}:latest
fi
echo ::set-output name=version::${VERSION}
echo ::set-output name=tags::${TAGS}
echo ::set-output name=created::$(date -u +'%Y-%m-%dT%H:%M:%SZ')
-
name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
-
name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
-
name: Build and push
uses: docker/build-push-action@v2
with:
context: .
file: ./Dockerfile
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.prep.outputs.tags }}
platforms: linux/amd64
labels: |
org.opencontainers.image.source=${{ github.event.repository.html_url }}
org.opencontainers.image.created=${{ steps.prep.outputs.created }}
org.opencontainers.image.revision=${{ github.sha }}

View file

@ -1,6 +1,6 @@
name: Update Docker Hub README
name: (push-master) Update Docker Hub README
on:
on:
push:
branches:
- master
@ -11,14 +11,16 @@ jobs:
update-docker-hub-readme:
runs-on: ubuntu-latest
steps:
-
-
name: Check out the repo
uses: actions/checkout@v2
uses: actions/checkout@v4
if: ${{ github.repository_owner == 'crowdsecurity' }}
-
name: Update docker hub README
uses: ms-jpq/sync-dockerhub-readme@v1
if: ${{ github.repository_owner == 'crowdsecurity' }}
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
repository: crowdsecurity/crowdsec
readme: "./docker/README.md"
readme: "./docker/README.md"

52
.gitignore vendored
View file

@ -4,17 +4,59 @@
*.dll
*.so
*.dylib
*~
.pc
# Test binary, built with `go test -c`
# IDEs
.vscode
.idea
# If vendor is included, allow prebuilt (wasm?) libraries.
!vendor/**/*.so
# Test binaries, built with `go test -c`
*.test
*.cover
# Output of the go coverage tool, specifically when used with LiteIDE
# Test dependencies
test/tools/*
# VMs used for dev/test
.vagrant
# Test binaries, built from *_test.go
pkg/csplugin/tests/cs_plugin_test*
# Output of go-acc, go -cover
*.out
test/coverage/*
# Dependency directories (remove the comment below to include it)
# vendor/
# Development artifacts, backups, etc
*.swp
*.swo
# Dependencies are not vendored by default, but a tarball is created by "make vendor"
# and provided in the release. Used by gentoo, etc.
vendor/
vendor.tgz
# crowdsec binaries
cmd/crowdsec-cli/cscli
cmd/crowdsec/crowdsec
cmd/crowdsec/crowdsec
cmd/notification-*/notification-*
# Test cache (downloaded files)
.cache
# Release stuff
crowdsec-v*
msi
*.msi
**/*.nupkg
*.tgz
# Python
__pycache__
*.py[cod]
*.egg-info

16
.gitmodules vendored Normal file
View file

@ -0,0 +1,16 @@
[submodule "tests/lib/bats-core"]
path = test/lib/bats-core
url = https://github.com/crowdsecurity/bats-core.git
branch = v1.7.0
[submodule "tests/lib/bats-file"]
path = test/lib/bats-file
url = https://github.com/crowdsecurity/bats-file.git
[submodule "tests/lib/bats-assert"]
path = test/lib/bats-assert
url = https://github.com/crowdsecurity/bats-assert.git
[submodule "tests/lib/bats-support"]
path = test/lib/bats-support
url = https://github.com/crowdsecurity/bats-support.git
[submodule "tests/lib/bats-mock"]
path = test/lib/bats-mock
url = https://github.com/crowdsecurity/bats-mock.git

382
.golangci.yml Normal file
View file

@ -0,0 +1,382 @@
# https://github.com/golangci/golangci-lint/blob/master/.golangci.reference.yml
linters-settings:
cyclop:
# lower this after refactoring
max-complexity: 48
gci:
sections:
- standard
- default
- prefix(github.com/crowdsecurity)
- prefix(github.com/crowdsecurity/crowdsec)
gomoddirectives:
replace-allow-list:
- golang.org/x/time/rate
gocognit:
# lower this after refactoring
min-complexity: 145
gocyclo:
# lower this after refactoring
min-complexity: 48
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
# lower this after refactoring
lines: 437
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
# lower this after refactoring
statements: 122
govet:
enable-all: true
disable:
- reflectvaluecompare
- fieldalignment
lll:
# lower this after refactoring
line-length: 2607
maintidx:
# raise this after refactoring
under: 11
misspell:
locale: US
nestif:
# lower this after refactoring
min-complexity: 28
nlreturn:
block-size: 5
nolintlint:
allow-unused: false # report any unused nolint directives
require-explanation: false # don't require an explanation for nolint directives
require-specific: false # don't require nolint directives to be specific about which linter is being skipped
interfacebloat:
max: 12
depguard:
rules:
wrap:
deny:
- pkg: "github.com/pkg/errors"
desc: "errors.Wrap() is deprecated in favor of fmt.Errorf()"
files:
- "!**/pkg/database/*.go"
- "!**/pkg/exprhelpers/*.go"
- "!**/pkg/acquisition/modules/appsec/appsec.go"
- "!**/pkg/acquisition/modules/loki/internal/lokiclient/loki_client.go"
- "!**/pkg/apiserver/controllers/v1/errors.go"
yaml:
files:
- "!**/pkg/acquisition/acquisition.go"
- "!**/pkg/acquisition/acquisition_test.go"
- "!**/pkg/acquisition/modules/appsec/appsec.go"
- "!**/pkg/acquisition/modules/cloudwatch/cloudwatch.go"
- "!**/pkg/acquisition/modules/docker/docker.go"
- "!**/pkg/acquisition/modules/file/file.go"
- "!**/pkg/acquisition/modules/journalctl/journalctl.go"
- "!**/pkg/acquisition/modules/kafka/kafka.go"
- "!**/pkg/acquisition/modules/kinesis/kinesis.go"
- "!**/pkg/acquisition/modules/kubernetesaudit/k8s_audit.go"
- "!**/pkg/acquisition/modules/loki/loki.go"
- "!**/pkg/acquisition/modules/loki/timestamp_test.go"
- "!**/pkg/acquisition/modules/s3/s3.go"
- "!**/pkg/acquisition/modules/syslog/syslog.go"
- "!**/pkg/acquisition/modules/wineventlog/wineventlog_windows.go"
- "!**/pkg/appsec/appsec.go"
- "!**/pkg/appsec/loader.go"
- "!**/pkg/csplugin/broker.go"
- "!**/pkg/csplugin/broker_test.go"
- "!**/pkg/dumps/bucket_dump.go"
- "!**/pkg/dumps/parser_dump.go"
- "!**/pkg/hubtest/coverage.go"
- "!**/pkg/hubtest/hubtest_item.go"
- "!**/pkg/hubtest/parser_assert.go"
- "!**/pkg/hubtest/scenario_assert.go"
- "!**/pkg/leakybucket/buckets_test.go"
- "!**/pkg/leakybucket/manager_load.go"
- "!**/pkg/metabase/metabase.go"
- "!**/pkg/parser/node.go"
- "!**/pkg/parser/node_test.go"
- "!**/pkg/parser/parsing_test.go"
- "!**/pkg/parser/stage.go"
deny:
- pkg: "gopkg.in/yaml.v2"
desc: "yaml.v2 is deprecated for new code in favor of yaml.v3"
wsl:
# Allow blocks to end with comments
allow-trailing-comment: true
linters:
enable-all: true
disable:
#
# DEPRECATED by golangi-lint
#
- deadcode
- exhaustivestruct
- golint
- ifshort
- interfacer
- maligned
- nosnakecase
- scopelint
- structcheck
- varcheck
#
# Disabled until fixed for go 1.22
#
- copyloopvar # copyloopvar is a linter detects places where loop variables are copied
- intrange # intrange is a linter to find places where for loops could make use of an integer range.
#
# Enabled
#
# - asasalint # check for pass []any as any in variadic func(...any)
# - asciicheck # checks that all code identifiers does not have non-ASCII symbols in the name
# - bidichk # Checks for dangerous unicode character sequences
# - bodyclose # checks whether HTTP response body is closed successfully
# - cyclop # checks function and package cyclomatic complexity
# - decorder # check declaration order and count of types, constants, variables and functions
# - depguard # Go linter that checks if package imports are in a list of acceptable packages
# - dupword # checks for duplicate words in the source code
# - durationcheck # check for two durations multiplied together
# - errcheck # errcheck is a program for checking for unchecked errors in Go code. These unchecked errors can be critical bugs in some cases
# - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
# - execinquery # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
# - exportloopref # checks for pointers to enclosing loop variables
# - funlen # Tool for detection of long functions
# - ginkgolinter # enforces standards of using ginkgo and gomega
# - gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid.
# - gochecknoinits # Checks that no init functions are present in Go code
# - gochecksumtype # Run exhaustiveness checks on Go "sum types"
# - gocognit # Computes and checks the cognitive complexity of functions
# - gocritic # Provides diagnostics that check for bugs, performance and style issues.
# - gocyclo # Computes and checks the cyclomatic complexity of functions
# - goheader # Checks is file header matches to pattern
# - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
# - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
# - goprintffuncname # Checks that printf-like functions are named with `f` at the end
# - gosimple # (megacheck): Linter for Go source code that specializes in simplifying code
# - gosmopolitan # Report certain i18n/l10n anti-patterns in your Go codebase
# - govet # (vet, vetshadow): Vet examines Go source code and reports suspicious constructs. It is roughly the same as 'go vet' and uses its passes.
# - grouper # Analyze expression groups.
# - importas # Enforces consistent import aliases
# - ineffassign # Detects when assignments to existing variables are not used
# - interfacebloat # A linter that checks the number of methods inside an interface.
# - lll # Reports long lines
# - loggercheck # (logrlint): Checks key value pairs for common logger libraries (kitlog,klog,logr,zap).
# - logrlint # Check logr arguments.
# - maintidx # maintidx measures the maintainability index of each function.
# - makezero # Finds slice declarations with non-zero initial length
# - mirror # reports wrong mirror patterns of bytes/strings usage
# - misspell # Finds commonly misspelled English words
# - nakedret # Checks that functions with naked returns are not longer than a maximum size (can be zero).
# - nestif # Reports deeply nested if statements
# - nilerr # Finds the code that returns nil even if it checks that the error is not nil.
# - nolintlint # Reports ill-formed or insufficient nolint directives
# - nonamedreturns # Reports all named returns
# - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL.
# - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative.
# - predeclared # find code that shadows one of Go's predeclared identifiers
# - reassign # Checks that package variables are not reassigned
# - rowserrcheck # checks whether Rows.Err of rows is checked successfully
# - sloglint # ensure consistent code style when using log/slog
# - spancheck # Checks for mistakes with OpenTelemetry/Census spans.
# - sqlclosecheck # Checks that sql.Rows, sql.Stmt, sqlx.NamedStmt, pgx.Query are closed.
# - staticcheck # (megacheck): It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint.
# - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
# - testableexamples # linter checks if examples are testable (have an expected output)
# - testifylint # Checks usage of github.com/stretchr/testify.
# - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
# - unconvert # Remove unnecessary type conversions
# - unused # (megacheck): Checks Go code for unused constants, variables, functions and types
# - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library.
# - wastedassign # Finds wasted assignment statements
# - zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg`
#
# Recommended? (easy)
#
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and reports occations, where the check for the returned error can be omitted.
- exhaustive # check exhaustiveness of enum switch statements
- gci # Gci control golang package import order and make it always deterministic.
- godot # Check if comments end in a period
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- goimports # Check import statements are formatted according to the 'goimport' command. Reformat imports in autofix mode.
- gosec # (gas): Inspects source code for security problems
- inamedparam # reports interfaces with unnamed method parameters
- musttag # enforce field tags in (un)marshaled structs
- promlinter # Check Prometheus metrics naming via promlint
- protogetter # Reports direct reads from proto message fields when getters should be used
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
- tagalign # check that struct tags are well aligned
- thelper # thelper detects tests helpers which is not start with t.Helper() method.
- wrapcheck # Checks that errors returned from external packages are wrapped
#
# Recommended? (requires some work)
#
- containedctx # containedctx is a linter that detects struct contained context.Context field
- contextcheck # check whether the function uses a non-inherited context
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- gomnd # An analyzer to detect magic numbers.
- ireturn # Accept Interfaces, Return Concrete Types
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # Finds sending http request without context.Context
- unparam # Reports unused function parameters
#
# Formatting only, useful in IDE but should not be forced on CI?
#
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- whitespace # Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc.
- wsl # add or remove empty lines
#
# Well intended, but not ready for this
#
- dupl # Tool for code clone detection
- forcetypeassert # finds forced type assertions
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goerr113 # Go linter to check the errors handling expressions
- paralleltest # Detects missing usage of t.Parallel() method in your Go test
- testpackage # linter that makes you use a separate _test package
#
# Too strict / too many false positives (for now?)
#
- exhaustruct # Checks if all structure fields are initialized
- forbidigo # Forbids identifiers
- gochecknoglobals # Check that no global variables exist.
- goconst # Finds repeated strings that could be replaced by a constant
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- varnamelen # checks that the length of a variable's name matches its scope
#
# Under evaluation
#
- prealloc # Finds slice declarations that could potentially be preallocated
issues:
# “Look, thats why theres rules, understand? So that you think before you
# break em.” ― Terry Pratchett
exclude-dirs:
- pkg/time/rate
exclude-files:
- pkg/yamlpatch/merge.go
- pkg/yamlpatch/merge_test.go
exclude-generated-strict: true
max-issues-per-linter: 0
max-same-issues: 0
exclude-rules:
# Won't fix:
# `err` is often shadowed, we may continue to do it
- linters:
- govet
text: "shadow: declaration of \"err\" shadows declaration"
- linters:
- errcheck
text: "Error return value of `.*` is not checked"
- linters:
- gocritic
text: "ifElseChain: rewrite if-else to switch statement"
- linters:
- gocritic
text: "captLocal: `.*' should not be capitalized"
- linters:
- gocritic
text: "appendAssign: append result not assigned to the same slice"
- linters:
- gocritic
text: "commentFormatting: put a space between `//` and comment text"
# Will fix, trivial - just beware of merge conflicts
- linters:
- perfsprint
text: "fmt.Sprintf can be replaced .*"
- linters:
- perfsprint
text: "fmt.Errorf can be replaced with errors.New"
#
# Will fix, easy but some neurons required
#
- linters:
- errorlint
text: "non-wrapping format verb for fmt.Errorf. Use `%w` to format errors"
- linters:
- errorlint
text: "type assertion on error will fail on wrapped errors. Use errors.As to check for specific errors"
- linters:
- errorlint
text: "type switch on error will fail on wrapped errors. Use errors.As to check for specific errors"
- linters:
- errorlint
text: "type assertion on error will fail on wrapped errors. Use errors.Is to check for specific errors"
- linters:
- errorlint
text: "comparing with .* will fail on wrapped errors. Use errors.Is to check for a specific error"
- linters:
- errorlint
text: "switch on an error will fail on wrapped errors. Use errors.Is to check for specific errors"
- linters:
- nosprintfhostport
text: "host:port in url should be constructed with net.JoinHostPort and not directly with fmt.Sprintf"
# https://github.com/timakin/bodyclose
- linters:
- bodyclose
text: "response body must be closed"
# named/naked returns are evil, with a single exception
# https://go.dev/wiki/CodeReviewComments#named-result-parameters
- linters:
- nonamedreturns
text: "named return .* with type .* found"

43
.yamllint Normal file
View file

@ -0,0 +1,43 @@
---
rules:
braces:
min-spaces-inside: 0
max-spaces-inside: 1
brackets:
min-spaces-inside: 0
max-spaces-inside: 1
colons:
max-spaces-before: 0
max-spaces-after: 1
commas:
max-spaces-before: 0
min-spaces-after: 1
max-spaces-after: 1
comments:
level: warning
require-starting-space: true
min-spaces-from-content: 2
comments-indentation:
level: warning
document-end: disable
document-start: disable
empty-lines:
max: 2
max-start: 0
max-end: 0
hyphens:
max-spaces-after: 1
indentation:
spaces: consistent
indent-sequences: whatever
check-multi-line-strings: false
key-duplicates: enable
line-length:
max: 180
allow-non-breakable-words: true
allow-non-breakable-inline-mappings: false
new-line-at-end-of-file: enable
new-lines:
type: unix
trailing-spaces: enable
truthy: disable

3
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,3 @@
Please refer to [Contributing to CrowdSec](https://doc.crowdsec.net/docs/next/contributing/getting_started).

View file

@ -1,24 +1,63 @@
ARG GOVERSION=1.16
# vim: set ft=dockerfile:
FROM golang:1.22.2-alpine3.18 AS build
FROM golang:${GOVERSION}-alpine AS build
ARG BUILD_VERSION
WORKDIR /go/src/crowdsec
RUN apk update && apk add --no-cache git jq gcc libc-dev make bash gettext binutils-gold
# We like to choose the release of re2 to use, and Alpine does not ship a static version anyway.
ENV RE2_VERSION=2023-03-01
ENV BUILD_VERSION=${BUILD_VERSION}
# wizard.sh requires GNU coreutils
RUN apk add --no-cache git g++ gcc libc-dev make bash gettext binutils-gold coreutils pkgconfig && \
wget https://github.com/google/re2/archive/refs/tags/${RE2_VERSION}.tar.gz && \
tar -xzf ${RE2_VERSION}.tar.gz && \
cd re2-${RE2_VERSION} && \
make install && \
echo "githubciXXXXXXXXXXXXXXXXXXXXXXXX" > /etc/machine-id && \
go install github.com/mikefarah/yq/v4@v4.43.1
COPY . .
RUN SYSTEM="docker" make release
RUN /bin/bash wizard.sh --docker-mode
RUN cscli hub update && cscli collections install crowdsecurity/linux
RUN make clean release DOCKER_BUILD=1 BUILD_STATIC=1 && \
cd crowdsec-v* && \
./wizard.sh --docker-mode && \
cd - >/dev/null && \
cscli hub update && \
cscli collections install crowdsecurity/linux && \
cscli parsers install crowdsecurity/whitelists
FROM alpine:latest
RUN apk update --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community && apk add --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community tzdata yq
COPY --from=build /etc/crowdsec /etc/crowdsec
COPY --from=build /var/lib/crowdsec /var/lib/crowdsec
COPY --from=build /usr/local/bin/crowdsec /usr/local/bin/crowdsec
COPY --from=build /usr/local/bin/cscli /usr/local/bin/cscli
# In case we need to remove agents here..
# cscli machines list -o json | yq '.[].machineId' | xargs -r cscli machines delete
FROM alpine:latest as slim
RUN apk add --no-cache --repository=http://dl-cdn.alpinelinux.org/alpine/edge/community tzdata bash rsync && \
mkdir -p /staging/etc/crowdsec && \
mkdir -p /staging/etc/crowdsec/acquis.d && \
mkdir -p /staging/var/lib/crowdsec && \
mkdir -p /var/lib/crowdsec/data
COPY --from=build /go/bin/yq /usr/local/bin/crowdsec /usr/local/bin/cscli /usr/local/bin/
COPY --from=build /etc/crowdsec /staging/etc/crowdsec
COPY --from=build /go/src/crowdsec/docker/docker_start.sh /
COPY --from=build /go/src/crowdsec/docker/config.yaml /etc/crowdsec/config.yaml
COPY --from=build /go/src/crowdsec/docker/config.yaml /staging/etc/crowdsec/config.yaml
COPY --from=build /var/lib/crowdsec /staging/var/lib/crowdsec
RUN yq -n '.url="http://0.0.0.0:8080"' | install -m 0600 /dev/stdin /staging/etc/crowdsec/local_api_credentials.yaml
ENTRYPOINT /bin/sh docker_start.sh
ENTRYPOINT /bin/bash /docker_start.sh
FROM slim as full
# Due to the wizard using cp -n, we have to copy the config files directly from the source as -n does not exist in busybox cp
# The files are here for reference, as users will need to mount a new version to be actually able to use notifications
COPY --from=build \
/go/src/crowdsec/cmd/notification-email/email.yaml \
/go/src/crowdsec/cmd/notification-http/http.yaml \
/go/src/crowdsec/cmd/notification-slack/slack.yaml \
/go/src/crowdsec/cmd/notification-splunk/splunk.yaml \
/go/src/crowdsec/cmd/notification-sentinel/sentinel.yaml \
/staging/etc/crowdsec/notifications/
COPY --from=build /usr/local/lib/crowdsec/plugins /usr/local/lib/crowdsec/plugins

87
Dockerfile.debian Normal file
View file

@ -0,0 +1,87 @@
# vim: set ft=dockerfile:
FROM golang:1.22.2-bookworm AS build
ARG BUILD_VERSION
WORKDIR /go/src/crowdsec
ENV DEBIAN_FRONTEND=noninteractive
ENV DEBCONF_NOWARNINGS="yes"
# We like to choose the release of re2 to use, the debian version is usually older.
ENV RE2_VERSION=2023-03-01
ENV BUILD_VERSION=${BUILD_VERSION}
# wizard.sh requires GNU coreutils
RUN apt-get update && \
apt-get install -y -q git gcc libc-dev make bash gettext binutils-gold coreutils tzdata && \
wget https://github.com/google/re2/archive/refs/tags/${RE2_VERSION}.tar.gz && \
tar -xzf ${RE2_VERSION}.tar.gz && \
cd re2-${RE2_VERSION} && \
make && \
make install && \
echo "githubciXXXXXXXXXXXXXXXXXXXXXXXX" > /etc/machine-id && \
go install github.com/mikefarah/yq/v4@v4.43.1
COPY . .
RUN make clean release DOCKER_BUILD=1 BUILD_STATIC=1 && \
cd crowdsec-v* && \
./wizard.sh --docker-mode && \
cd - >/dev/null && \
cscli hub update && \
cscli collections install crowdsecurity/linux && \
cscli parsers install crowdsecurity/whitelists
# In case we need to remove agents here..
# cscli machines list -o json | yq '.[].machineId' | xargs -r cscli machines delete
FROM debian:bookworm-slim as slim
ENV DEBIAN_FRONTEND=noninteractive
ENV DEBCONF_NOWARNINGS="yes"
RUN apt-get update && \
apt-get install -y -q --install-recommends --no-install-suggests \
procps \
systemd \
iproute2 \
ca-certificates \
bash \
tzdata \
rsync && \
mkdir -p /staging/etc/crowdsec && \
mkdir -p /staging/etc/crowdsec/acquis.d && \
mkdir -p /staging/var/lib/crowdsec && \
mkdir -p /var/lib/crowdsec/data
COPY --from=build /go/bin/yq /usr/local/bin/crowdsec /usr/local/bin/cscli /usr/local/bin/
COPY --from=build /etc/crowdsec /staging/etc/crowdsec
COPY --from=build /go/src/crowdsec/docker/docker_start.sh /
COPY --from=build /go/src/crowdsec/docker/config.yaml /staging/etc/crowdsec/config.yaml
RUN yq -n '.url="http://0.0.0.0:8080"' | install -m 0600 /dev/stdin /staging/etc/crowdsec/local_api_credentials.yaml && \
yq eval -i ".plugin_config.group = \"nogroup\"" /staging/etc/crowdsec/config.yaml
ENTRYPOINT /bin/bash docker_start.sh
FROM slim as plugins
# Due to the wizard using cp -n, we have to copy the config files directly from the source as -n does not exist in busybox cp
# The files are here for reference, as users will need to mount a new version to be actually able to use notifications
COPY --from=build \
/go/src/crowdsec/cmd/notification-email/email.yaml \
/go/src/crowdsec/cmd/notification-http/http.yaml \
/go/src/crowdsec/cmd/notification-slack/slack.yaml \
/go/src/crowdsec/cmd/notification-splunk/splunk.yaml \
/go/src/crowdsec/cmd/notification-sentinel/sentinel.yaml \
/staging/etc/crowdsec/notifications/
COPY --from=build /usr/local/lib/crowdsec/plugins /usr/local/lib/crowdsec/plugins
FROM slim as geoip
COPY --from=build /var/lib/crowdsec /staging/var/lib/crowdsec
FROM plugins as full
COPY --from=build /var/lib/crowdsec /staging/var/lib/crowdsec

View file

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2020-2021 crowdsecurity
Copyright (c) 2020-2023 Crowdsec
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

394
Makefile
View file

@ -1,148 +1,304 @@
ROOT= $(shell pwd)
SYSTEM?= $(shell uname -s | tr '[A-Z]' '[a-z]')
include mk/platform.mk
include mk/gmsl
ifneq ("$(wildcard $(ROOT)/platform/$(SYSTEM).mk)", "")
include $(ROOT)/platform/$(SYSTEM).mk
else
include $(ROOT)/platform/linux.mk
# By default, this build requires the C++ re2 library to be installed.
#
# Debian/Ubuntu: apt install libre2-dev
# Fedora/CentOS: dnf install re2-devel
# FreeBSD: pkg install re2
# Alpine: apk add re2-dev
# Windows: choco install re2
# MacOS: brew install re2
# To build without re2, run "make BUILD_RE2_WASM=1"
# The WASM version is slower and introduces a short delay when starting a process
# (including cscli) so it is not recommended for production use.
BUILD_RE2_WASM ?= 0
# To build static binaries, run "make BUILD_STATIC=1".
# On some platforms, this requires additional packages
# (e.g. glibc-static and libstdc++-static on fedora, centos.. which are on the powertools/crb repository).
# If the static build fails at the link stage, it might be because the static library is not provided
# for your distribution (look for libre2.a). See the Dockerfile for an example of how to build it.
BUILD_STATIC ?= 0
# List of plugins to build
PLUGINS ?= $(patsubst ./cmd/notification-%,%,$(wildcard ./cmd/notification-*))
# Can be overriden, if you can deal with the consequences
BUILD_REQUIRE_GO_MAJOR ?= 1
BUILD_REQUIRE_GO_MINOR ?= 21
#--------------------------------------
GO = go
GOTEST = $(GO) test
BUILD_CODENAME ?= alphaga
CROWDSEC_FOLDER = ./cmd/crowdsec
CSCLI_FOLDER = ./cmd/crowdsec-cli/
PLUGINS_DIR_PREFIX = ./cmd/notification-
CROWDSEC_BIN = crowdsec$(EXT)
CSCLI_BIN = cscli$(EXT)
# semver comparison to select the hub branch requires the version to start with "v"
ifneq ($(call substr,$(BUILD_VERSION),1,1),v)
$(error BUILD_VERSION "$(BUILD_VERSION)" should start with "v")
endif
PREFIX?="/tmp/crowdsec/"
CFG_PREFIX = $(PREFIX)"/etc/crowdsec/"
BIN_PREFIX = $(PREFIX)"/usr/local/bin/"
DATA_PREFIX = $(PREFIX)"/var/run/crowdsec/"
PID_DIR = $(PREFIX)"/var/run/"
CROWDSEC_FOLDER = "./cmd/crowdsec"
CSCLI_FOLDER = "./cmd/crowdsec-cli/"
CROWDSEC_BIN = "crowdsec"
CSCLI_BIN = "cscli"
BUILD_CMD = "build"
GOARCH=amd64
#Golang version info
GO_MAJOR_VERSION = $(shell go version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f1)
GO_MINOR_VERSION = $(shell go version | cut -c 14- | cut -d' ' -f1 | cut -d'.' -f2)
MINIMUM_SUPPORTED_GO_MAJOR_VERSION = 1
MINIMUM_SUPPORTED_GO_MINOR_VERSION = 13
GO_VERSION_VALIDATION_ERR_MSG = Golang version ($(BUILD_GOVERSION)) is not supported, please use least $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION).$(MINIMUM_SUPPORTED_GO_MINOR_VERSION)
#Current versioning information from env
BUILD_VERSION?="$(shell git describe --tags `git rev-list --tags --max-count=1`)"
BUILD_GOVERSION="$(shell go version | cut -d " " -f3 | sed -E 's/[go]+//g')"
BUILD_CODENAME=$(shell cat RELEASE.json | jq -r .CodeName)
BUILD_TIMESTAMP=$(shell date +%F"_"%T)
BUILD_TAG="$(shell git rev-parse HEAD)"
export LD_OPTS=-ldflags "-s -w -X github.com/crowdsecurity/crowdsec/pkg/cwversion.Version=$(BUILD_VERSION) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.System=$(SYSTEM) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.BuildDate=$(BUILD_TIMESTAMP) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.Codename=$(BUILD_CODENAME) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.Tag=$(BUILD_TAG) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.GoVersion=$(BUILD_GOVERSION)"
export LD_OPTS_STATIC=-ldflags "-s -w -X github.com/crowdsecurity/crowdsec/pkg/cwversion.Version=$(BUILD_VERSION) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.BuildDate=$(BUILD_TIMESTAMP) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.Codename=$(BUILD_CODENAME) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.Tag=$(BUILD_TAG) \
-X github.com/crowdsecurity/crowdsec/pkg/cwversion.GoVersion=$(BUILD_GOVERSION) \
-extldflags '-static'"
# Directory for the release files
RELDIR = crowdsec-$(BUILD_VERSION)
all: clean test build
GO_MODULE_NAME = github.com/crowdsecurity/crowdsec
build: goversion crowdsec cscli
# Check if a given value is considered truthy and returns "0" or "1".
# A truthy value is one of the following: "1", "yes", or "true", case-insensitive.
#
# Usage:
# ifeq ($(call bool,$(FOO)),1)
# $(info Let's foo)
# endif
bool = $(if $(filter $(call lc, $1),1 yes true),1,0)
static: goversion crowdsec_static cscli_static
#--------------------------------------
#
# Define MAKE_FLAGS and LD_OPTS for the sub-makefiles in cmd/
#
goversion:
@if [ $(GO_MAJOR_VERSION) -gt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \
exit 0 ;\
elif [ $(GO_MAJOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MAJOR_VERSION) ]; then \
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
exit 1; \
elif [ $(GO_MINOR_VERSION) -lt $(MINIMUM_SUPPORTED_GO_MINOR_VERSION) ] ; then \
echo '$(GO_VERSION_VALIDATION_ERR_MSG)';\
exit 1; \
fi
MAKE_FLAGS = --no-print-directory GOARCH=$(GOARCH) GOOS=$(GOOS) RM="$(RM)" WIN_IGNORE_ERR="$(WIN_IGNORE_ERR)" CP="$(CP)" CPR="$(CPR)" MKDIR="$(MKDIR)"
clean:
@$(MAKE) -C $(CROWDSEC_FOLDER) clean --no-print-directory
@$(MAKE) -C $(CSCLI_FOLDER) clean --no-print-directory
@rm -f $(CROWDSEC_BIN)
@rm -f $(CSCLI_BIN)
@rm -f *.log
@rm -f crowdsec-release.tgz
LD_OPTS_VARS= \
-X 'github.com/crowdsecurity/go-cs-lib/version.Version=$(BUILD_VERSION)' \
-X 'github.com/crowdsecurity/go-cs-lib/version.BuildDate=$(BUILD_TIMESTAMP)' \
-X 'github.com/crowdsecurity/go-cs-lib/version.Tag=$(BUILD_TAG)' \
-X '$(GO_MODULE_NAME)/pkg/cwversion.Codename=$(BUILD_CODENAME)' \
-X '$(GO_MODULE_NAME)/pkg/csconfig.defaultConfigDir=$(DEFAULT_CONFIGDIR)' \
-X '$(GO_MODULE_NAME)/pkg/csconfig.defaultDataDir=$(DEFAULT_DATADIR)'
cscli:
ifeq ($(lastword $(RESPECT_VERSION)), $(CURRENT_GOVERSION))
@$(MAKE) -C $(CSCLI_FOLDER) build --no-print-directory
else
@echo "Required golang version is $(REQUIRE_GOVERSION). The current one is $(CURRENT_GOVERSION). Exiting.."
@exit 1;
ifneq (,$(DOCKER_BUILD))
LD_OPTS_VARS += -X '$(GO_MODULE_NAME)/pkg/cwversion.System=docker'
endif
GO_TAGS := netgo,osusergo,sqlite_omit_load_extension
crowdsec:
ifeq ($(lastword $(RESPECT_VERSION)), $(CURRENT_GOVERSION))
@$(MAKE) -C $(CROWDSEC_FOLDER) build --no-print-directory
else
@echo "Required golang version is $(REQUIRE_GOVERSION). The current one is $(CURRENT_GOVERSION). Exiting.."
@exit 1;
# this will be used by Go in the make target, some distributions require it
export PKG_CONFIG_PATH:=/usr/local/lib/pkgconfig:$(PKG_CONFIG_PATH)
ifeq ($(call bool,$(BUILD_RE2_WASM)),0)
ifeq ($(PKG_CONFIG),)
$(error "pkg-config is not available. Please install pkg-config.")
endif
cscli_static:
ifeq ($(lastword $(RESPECT_VERSION)), $(CURRENT_GOVERSION))
@$(MAKE) -C $(CSCLI_FOLDER) static --no-print-directory
ifeq ($(RE2_CHECK),)
RE2_FAIL := "libre2-dev is not installed, please install it or set BUILD_RE2_WASM=1 to use the WebAssembly version"
else
@echo "Required golang version is $(REQUIRE_GOVERSION). The current one is $(CURRENT_GOVERSION). Exiting.."
@exit 1;
# += adds a space that we don't want
GO_TAGS := $(GO_TAGS),re2_cgo
LD_OPTS_VARS += -X '$(GO_MODULE_NAME)/pkg/cwversion.Libre2=C++'
endif
endif
crowdsec_static:
ifeq ($(lastword $(RESPECT_VERSION)), $(CURRENT_GOVERSION))
@$(MAKE) -C $(CROWDSEC_FOLDER) static --no-print-directory
# Build static to avoid the runtime dependency on libre2.so
ifeq ($(call bool,$(BUILD_STATIC)),1)
BUILD_TYPE = static
EXTLDFLAGS := -extldflags '-static'
else
@echo "Required golang version is $(REQUIRE_GOVERSION). The current one is $(CURRENT_GOVERSION). Exiting.."
@exit 1;
BUILD_TYPE = dynamic
EXTLDFLAGS :=
endif
#.PHONY: test
test:
ifeq ($(lastword $(RESPECT_VERSION)), $(CURRENT_GOVERSION))
@$(MAKE) -C $(CROWDSEC_FOLDER) test --no-print-directory
# Build with debug symbols, and disable optimizations + inlining, to use Delve
ifeq ($(call bool,$(DEBUG)),1)
STRIP_SYMBOLS :=
DISABLE_OPTIMIZATION := -gcflags "-N -l"
else
@echo "Required golang version is $(REQUIRE_GOVERSION). The current one is $(CURRENT_GOVERSION). Exiting.."
@exit 1;
STRIP_SYMBOLS := -s -w
DISABLE_OPTIMIZATION :=
endif
export LD_OPTS=-ldflags "$(STRIP_SYMBOLS) $(EXTLDFLAGS) $(LD_OPTS_VARS)" \
-trimpath -tags $(GO_TAGS) $(DISABLE_OPTIMIZATION)
ifeq ($(call bool,$(TEST_COVERAGE)),1)
LD_OPTS += -cover
endif
#--------------------------------------
.PHONY: build
build: pre-build goversion crowdsec cscli plugins ## Build crowdsec, cscli and plugins
.PHONY: pre-build
pre-build: ## Sanity checks and build information
$(info Building $(BUILD_VERSION) ($(BUILD_TAG)) $(BUILD_TYPE) for $(GOOS)/$(GOARCH))
ifneq (,$(RE2_FAIL))
$(error $(RE2_FAIL))
endif
ifneq (,$(RE2_CHECK))
$(info Using C++ regexp library)
else
$(info Fallback to WebAssembly regexp library. To use the C++ version, make sure you have installed libre2-dev and pkg-config.)
endif
ifeq ($(call bool,$(DEBUG)),1)
$(info Building with debug symbols and disabled optimizations)
endif
ifeq ($(call bool,$(TEST_COVERAGE)),1)
$(info Test coverage collection enabled)
endif
# intentional, empty line
$(info )
.PHONY: all
all: clean test build ## Clean, test and build (requires localstack)
.PHONY: plugins
plugins: ## Build notification plugins
@$(foreach plugin,$(PLUGINS), \
$(MAKE) -C $(PLUGINS_DIR_PREFIX)$(plugin) build $(MAKE_FLAGS); \
)
# same as "$(MAKE) -f debian/rules clean" but without the dependency on debhelper
.PHONY: clean-debian
clean-debian:
@$(RM) -r debian/crowdsec
@$(RM) -r debian/crowdsec
@$(RM) -r debian/files
@$(RM) -r debian/.debhelper
@$(RM) -r debian/*.substvars
@$(RM) -r debian/*-stamp
.PHONY: clean-rpm
clean-rpm:
@$(RM) -r rpm/BUILD
@$(RM) -r rpm/BUILDROOT
@$(RM) -r rpm/RPMS
@$(RM) -r rpm/SOURCES/*.tar.gz
@$(RM) -r rpm/SRPMS
.PHONY: clean
clean: clean-debian clean-rpm testclean ## Remove build artifacts
@$(MAKE) -C $(CROWDSEC_FOLDER) clean $(MAKE_FLAGS)
@$(MAKE) -C $(CSCLI_FOLDER) clean $(MAKE_FLAGS)
@$(RM) $(CROWDSEC_BIN) $(WIN_IGNORE_ERR)
@$(RM) $(CSCLI_BIN) $(WIN_IGNORE_ERR)
@$(RM) *.log $(WIN_IGNORE_ERR)
@$(RM) crowdsec-release.tgz $(WIN_IGNORE_ERR)
@$(foreach plugin,$(PLUGINS), \
$(MAKE) -C $(PLUGINS_DIR_PREFIX)$(plugin) clean $(MAKE_FLAGS); \
)
.PHONY: cscli
cscli: goversion ## Build cscli
@$(MAKE) -C $(CSCLI_FOLDER) build $(MAKE_FLAGS)
.PHONY: crowdsec
crowdsec: goversion ## Build crowdsec
@$(MAKE) -C $(CROWDSEC_FOLDER) build $(MAKE_FLAGS)
.PHONY: generate
generate: ## Generate code for the database and APIs
$(GO) generate ./pkg/database/ent
$(GO) generate ./pkg/models
.PHONY: testclean
testclean: bats-clean ## Remove test artifacts
@$(RM) pkg/apiserver/ent $(WIN_IGNORE_ERR)
@$(RM) pkg/cwhub/hubdir $(WIN_IGNORE_ERR)
@$(RM) pkg/cwhub/install $(WIN_IGNORE_ERR)
@$(RM) pkg/types/example.txt $(WIN_IGNORE_ERR)
# for the tests with localstack
export AWS_ENDPOINT_FORCE=http://localhost:4566
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=test
testenv:
@echo 'NOTE: You need Docker, docker-compose and run "make localstack" in a separate shell ("make localstack-stop" to terminate it)'
.PHONY: test
test: testenv goversion ## Run unit tests with localstack
$(GOTEST) $(LD_OPTS) ./...
.PHONY: go-acc
go-acc: testenv goversion ## Run unit tests with localstack + coverage
go-acc ./... -o coverage.out --ignore database,notifications,protobufs,cwversion,cstest,models -- $(LD_OPTS)
# mock AWS services
.PHONY: localstack
localstack: ## Run localstack containers (required for unit testing)
docker-compose -f test/localstack/docker-compose.yml up
.PHONY: localstack-stop
localstack-stop: ## Stop localstack containers
docker-compose -f test/localstack/docker-compose.yml down
# build vendor.tgz to be distributed with the release
.PHONY: vendor
vendor: vendor-remove ## CI only - vendor dependencies and archive them for packaging
$(GO) mod vendor
tar czf vendor.tgz vendor
tar --create --auto-compress --file=$(RELDIR)-vendor.tar.xz vendor
# remove vendor directories and vendor.tgz
.PHONY: vendor-remove
vendor-remove: ## Remove vendor dependencies and archives
$(RM) vendor vendor.tgz *-vendor.tar.xz
.PHONY: package
package:
@echo "Building Release to dir $(RELDIR)"
@$(MKDIR) $(RELDIR)/cmd/crowdsec
@$(MKDIR) $(RELDIR)/cmd/crowdsec-cli
@$(CP) $(CROWDSEC_FOLDER)/$(CROWDSEC_BIN) $(RELDIR)/cmd/crowdsec
@$(CP) $(CSCLI_FOLDER)/$(CSCLI_BIN) $(RELDIR)/cmd/crowdsec-cli
@$(foreach plugin,$(PLUGINS), \
$(MKDIR) $(RELDIR)/$(PLUGINS_DIR_PREFIX)$(plugin); \
$(CP) $(PLUGINS_DIR_PREFIX)$(plugin)/notification-$(plugin)$(EXT) $(RELDIR)/$(PLUGINS_DIR_PREFIX)$(plugin); \
$(CP) $(PLUGINS_DIR_PREFIX)$(plugin)/$(plugin).yaml $(RELDIR)/$(PLUGINS_DIR_PREFIX)$(plugin)/; \
)
@$(CPR) ./config $(RELDIR)
@$(CP) wizard.sh $(RELDIR)
@$(CP) scripts/test_env.sh $(RELDIR)
@$(CP) scripts/test_env.ps1 $(RELDIR)
@tar cvzf crowdsec-release.tgz $(RELDIR)
.PHONY: check_release
check_release:
ifneq ($(OS), Windows_NT)
@if [ -d $(RELDIR) ]; then echo "$(RELDIR) already exists, abort" ; exit 1 ; fi
else
@if (Test-Path -Path $(RELDIR)) { echo "$(RELDIR) already exists, abort" ; exit 1 ; }
endif
.PHONY:
release: check_release build
@echo Building Release to dir $(RELDIR)
@mkdir -p $(RELDIR)/cmd/crowdsec
@mkdir -p $(RELDIR)/cmd/crowdsec-cli
@cp $(CROWDSEC_FOLDER)/$(CROWDSEC_BIN) $(RELDIR)/cmd/crowdsec
@cp $(CSCLI_FOLDER)/$(CSCLI_BIN) $(RELDIR)/cmd/crowdsec-cli
@cp -R ./config/ $(RELDIR)
@cp wizard.sh $(RELDIR)
@cp scripts/test_env.sh $(RELDIR)
@tar cvzf crowdsec-release.tgz $(RELDIR)
.PHONY: release
release: check_release build package ## Build a release tarball
.PHONY:
release_static: check_release static
@echo Building Release to dir $(RELDIR)
@mkdir -p $(RELDIR)/cmd/crowdsec
@mkdir -p $(RELDIR)/cmd/crowdsec-cli
@cp $(CROWDSEC_FOLDER)/$(CROWDSEC_BIN) $(RELDIR)/cmd/crowdsec
@cp $(CSCLI_FOLDER)/$(CSCLI_BIN) $(RELDIR)/cmd/crowdsec-cli
@cp -R ./config/ $(RELDIR)
@cp wizard.sh $(RELDIR)
@cp scripts/test_env.sh $(RELDIR)
@tar cvzf crowdsec-release-static.tgz $(RELDIR)
.PHONY: windows_installer
windows_installer: build ## Windows - build the installer
@.\make_installer.ps1 -version $(BUILD_VERSION)
.PHONY: chocolatey
chocolatey: windows_installer ## Windows - build the chocolatey package
@.\make_chocolatey.ps1 -version $(BUILD_VERSION)
# Include test/bats.mk only if it exists
# to allow building without a test/ directory
# (i.e. inside docker)
ifeq (,$(wildcard test/bats.mk))
bats-clean:
else
include test/bats.mk
endif
include mk/goversion.mk
include mk/help.mk

View file

@ -1,36 +1,46 @@
<p align="center">
<img src="https://raw.githubusercontent.com/crowdsecurity/crowdsec-docs/main/docs/assets/images/crowdsec_logo.png" alt="CrowdSec" title="CrowdSec" width="400" height="260"/>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/crowdsec_logo.png" alt="CrowdSec" title="CrowdSec" width="400" height="260"/>
</p>
</br>
</br>
</br>
<p align="center">
<img src="https://github.com/crowdsecurity/crowdsec/workflows/tests/badge.svg">
<img src="https://github.com/crowdsecurity/crowdsec/workflows/build/badge.svg">
<a href='https://coveralls.io/github/crowdsecurity/crowdsec?branch=master'><img src='https://coveralls.io/repos/github/crowdsecurity/crowdsec/badge.svg?branch=master' alt='Coverage Status' /></a>
<img src="https://github.com/crowdsecurity/crowdsec/actions/workflows/go-tests.yml/badge.svg">
<img src="https://github.com/crowdsecurity/crowdsec/actions/workflows/bats.yml/badge.svg">
<a href="https://codecov.io/gh/crowdsecurity/crowdsec">
<img src="https://codecov.io/gh/crowdsecurity/crowdsec/branch/master/graph/badge.svg?token=CQGSPNY3PT"/>
</a>
<img src="https://goreportcard.com/badge/github.com/crowdsecurity/crowdsec">
<img src="https://img.shields.io/github/license/crowdsecurity/crowdsec">
<img src="https://github.com/crowdsecurity/crowdsec/workflows/Hub-CI/badge.svg">
<img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/AlteredCoder/ed74e50c43e3b17bdfc4d93149f23d37/raw/crowdsec_parsers_badge.json">
<img src="https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/AlteredCoder/ed74e50c43e3b17bdfc4d93149f23d37/raw/crowdsec_scenarios_badge.json">
<a href="https://hub.docker.com/r/crowdsecurity/crowdsec">
<img src="https://img.shields.io/docker/pulls/crowdsecurity/crowdsec?logo=docker">
</a>
<a href="https://discord.com/invite/crowdsec">
<img src="https://img.shields.io/discord/921520481163673640?label=Discord&logo=discord">
</a>
</p>
<p align="center">
:computer: <a href="https://app.crowdsec.net">Console (WebApp)</a>
:books: <a href="https://doc.crowdsec.net">Documentation</a>
:diamond_shape_with_a_dot_inside: <a href="https://hub.crowdsec.net">Configuration Hub</a>
:speech_balloon: <a href="https://discourse.crowdsec.net">Discourse (Forum)</a>
:speech_balloon: <a href="https://gitter.im/crowdsec-project/community?utm_source=share-link&utm_medium=link&utm_campaign=share-link">Gitter (Live chat)</a>
:speech_balloon: <a href="https://discord.gg/crowdsec">Discord (Live Chat)</a>
</p>
:dancer: This is a community driven project, <a href="https://forms.gle/ZQBQcptG2wYGajRX8">we need your feedback</a>.
:dancer: This is a community-driven project, <a href="https://forms.gle/ZQBQcptG2wYGajRX8">we need your feedback</a>.
## <TL;DR>
CrowdSec is a free, modern & collaborative behavior detection engine, coupled with a global IP reputation network. It stacks on fail2ban's philosophy but is IPV6 compatible and 60x faster (Go vs Python), uses Grok patterns to parse logs and YAML scenario to identify behaviors. CrowdSec is engineered for modern Cloud / Containers / VM based infrastructures (by decoupling detection and remediation). Once detected you can remedy threats with various bouncers (firewall block, nginx http 403, Captchas, etc.) while the aggressive IP can be sent to CrowdSec for curation before being shared among all users to further improve everyone's security. See [FAQ](https://doc.crowdsec.net/faq/) or read bellow for more.
CrowdSec is a free, modern & collaborative behavior detection engine, coupled with a global IP reputation network. It stacks on fail2ban's philosophy but is IPV6 compatible and 60x faster (Go vs Python), it uses Grok patterns to parse logs and YAML scenarios to identify behaviors. CrowdSec is engineered for modern Cloud / Containers / VM-based infrastructures (by decoupling detection and remediation). Once detected you can remedy threats with various bouncers (firewall block, nginx http 403, Captchas, etc.) while the aggressive IP can be sent to CrowdSec for curation before being shared among all users to further improve everyone's security. See [FAQ](https://doc.crowdsec.net/docs/faq) or read below for more.
## 2 mins install
Installing it through the [Package system](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/) of your OS is the easiest way to proceed.
Installing it through the [Package system](https://doc.crowdsec.net/docs/getting_started/install_crowdsec) of your OS is the easiest way to proceed.
Otherwise, you can install it from source.
### From package (Debian)
@ -45,7 +55,14 @@ sudo apt-get install crowdsec
```sh
curl -s https://packagecloud.io/install/repositories/crowdsec/crowdsec/script.rpm.sh | sudo bash
yum install crowdsec
sudo yum install crowdsec
```
### From package (FreeBSD)
```
sudo pkg update
sudo pkg install crowdsec
```
### From source
@ -58,39 +75,38 @@ cd crowdsec-v* && sudo ./wizard.sh -i
## :information_source: About the CrowdSec project
Crowdsec is an open-source, lightweight software, detecting peers with aggressive behaviors to prevent them from accessing your systems. Its user friendly design and assistance offers a low technical barrier of entry and nevertheless a high security gain.
Crowdsec is an open-source, lightweight software, detecting peers with aggressive behaviors to prevent them from accessing your systems. Its user-friendly design and assistance offer a low technical barrier of entry and nevertheless a high security gain.
Processing is done in 4 steps:
The architecture is as follows :
<p align="center">
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/CS-simplified-treatment.png?raw=true" alt="CrowdSec" title="CrowdSec" width="844" height="341"/>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/crowdsec_architecture.png" alt="CrowdSec" title="CrowdSec"/>
</p>
Once an unwanted behavior is detected, deal with it through a [bouncer](https://hub.crowdsec.net/browse/#bouncers). The aggressive IP, scenario triggered and timestamp are sent for curation, to avoid poisoning & false positives. (This can be disabled). If verified, this IP is then redistributed to all CrowdSec users running the same scenario.
## Outnumbering hackers all together
By sharing the threat they faced, all users are protecting each-others (hence the name Crowd-Security). Crowdsec is designed for modern infrastructures, with its "*Detect Here, Remedy There*" approach, letting you analyse logs coming from several sources in one place and block threats at various levels (applicative, system, infrastructural) of your stack.
By sharing the threat they faced, all users are protecting each-others (hence the name Crowd-Security). Crowdsec is designed for modern infrastructures, with its "*Detect Here, Remedy There*" approach, letting you analyze logs coming from several sources in one place and block threats at various levels (applicative, system, infrastructural) of your stack.
CrowdSec ships by default with scenarios (brute force, port scan, web scan, etc.) adapted for most context, but you can easily extend it by picking more of them from the **[HUB](https://hub.crowdsec.net)**. It is also easy to adapt an existing one or create one yourself.
CrowdSec ships by default with scenarios (brute force, port scan, web scan, etc.) adapted for most contexts, but you can easily extend it by picking more of them from the **[HUB](https://hub.crowdsec.net)**. It is also easy to adapt an existing one or create one yourself.
## :point_right: What it is not
CrowdSec is not a SIEM, storing your logs (neither locally nor remotely). Your data are analyzed locally and forgotten.
Signals sent to the curation platform are limited to the very strict minimum: IP, Scenario, Timestamp. They are only used to allow the system to spot new rogue IPs, rule out false positives or poisoning attempts.
Signals sent to the curation platform are limited to the very strict minimum: IP, Scenario, Timestamp. They are only used to allow the system to spot new rogue IPs, and rule out false positives or poisoning attempts.
## :arrow_down: Install it !
Crowdsec is available for various platforms :
- [Use our debian repositories](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/#install-using-crowdsec-repository) or [the official debian packages](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/#install-using-debian-official-packages)
- [Use our debian repositories](https://doc.crowdsec.net/docs/getting_started/install_crowdsec) or the [official debian packages](https://packages.debian.org/search?keywords=crowdsec&searchon=names&suite=stable&section=all)
- An [image](https://hub.docker.com/r/crowdsecurity/crowdsec) is available for docker
- [Prebuilt release packages](https://github.com/crowdsecurity/crowdsec/releases) are also available (suitable for `amd64`)
- You can as well [build it from source](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/#install-from-source)
- FreeBSD support is [wip](https://github.com/crowdsecurity/crowdsec/issues/651)
- You can as well [build it from source](https://doc.crowdsec.net/docs/user_guides/building)
Or look directly at [installation documentation](https://doc.crowdsec.net/Crowdsec/v1/getting_started/installation/) for other methods.
Or look directly at [installation documentation](https://doc.crowdsec.net/docs/getting_started/install_crowdsec) for other methods and platforms.
## :tada: Key benefits
@ -98,35 +114,35 @@ Or look directly at [installation documentation](https://doc.crowdsec.net/Crowds
<details open>
<summary>Initial configuration is automated, providing functional out-of-the-box setup</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/crowdsec_install.gif?raw=true">
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/crowdsec_install.gif?raw=true">
</details>
### Out of the box detection
<details>
<summary>Baseline detection is effective out-of-the-box, no fine-tuning required (click to expand)</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/out-of-the-box-protection.gif?raw=true">
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/out-of-the-box-protection.gif?raw=true">
</details>
### Easy bouncer deployment
<details>
<summary>It's trivial to add bouncers to enforce decisions of crowdsec (click to expand)</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/blocker-installation.gif?raw=true">
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/blocker-installation.gif?raw=true">
</details>
### Easy dashboard access
<details>
<summary>It's easy to deploy a metabase interface to view your data simply with cscli (click to expand)</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/cscli-metabase.gif?raw=true">
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/cscli-metabase.gif?raw=true">
</details>
### Hot & Cold logs
<details>
<summary>Process cold logs, for forensic, tests and chasing false-positives & false negatives (click to expand)</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/docs/assets/images/forensic-mode.gif?raw=true">
<summary>Process cold logs, for forensic, tests and chasing false positives & false negatives (click to expand)</summary>
<img src="https://github.com/crowdsecurity/crowdsec-docs/blob/main/crowdsec-docs/static/img/forensic-mode.gif?raw=true">
</details>

View file

@ -1,3 +0,0 @@
{
"CodeName": "alphaga"
}

31
SECURITY.md Normal file
View file

@ -0,0 +1,31 @@
# Security Policy
## Scope
This security policy applies to :
- Crowdsec agent
- Crowdsec Local API
- Crowdsec bouncers **developed and maintained** by the Crowdsec team [1]
Reports regarding developements of community members that are not part of the crowdsecurity organization will be thoroughly investigated nonetheless.
[1] Projects developed and maintained by the Crowdsec team are under the **crowdsecurity** github organization. Bouncers developed by community members that are not part of the Crowdsec organization are explictely excluded.
## Reporting a Vulnerability
We are extremely grateful to security researchers and users that report vulnerabilities regarding the Crowdsec project. All reports are thoroughly investigated by members of the Crowdsec organization.
You can email the private [security@crowdsec.net](mailto:security@crowdsec.net) list with the security details and the details expected for [all Crowdsec bug reports](https://github.com/crowdsecurity/crowdsec/blob/master/.github/ISSUE_TEMPLATE/bug_report.md).
You may encrypt your email to this list using the GPG key of the [Security team](https://doc.crowdsec.net/docs/next/contact_team). Encryption using GPG is NOT required to make a disclosure.
## When Should I Report a Vulnerability?
- You think you discovered a potential security vulnerability in Crowdsec
- You are unsure how a vulnerability affects Crowdsec
- You think you discovered a vulnerability in another project that Crowdsec depends on
For projects with their own vulnerability reporting and disclosure process, please report it directly there.
<!-- Very heavily inspired from https://kubernetes.io/docs/reference/issues-security/security/ -->

186
azure-pipelines.yml Normal file
View file

@ -0,0 +1,186 @@
trigger:
tags:
include:
- "v*"
exclude:
- "v*freebsd"
branches:
exclude:
- "*"
pr: none
pool:
vmImage: windows-latest
stages:
- stage: Build
jobs:
- job: Build
displayName: "Build"
steps:
- task: GoTool@0
displayName: "Install Go"
inputs:
version: '1.22.2'
- pwsh: |
choco install -y make
displayName: "Install builds deps"
- task: PowerShell@2
inputs:
targetType: 'inline'
pwsh: true
#we are not calling make windows_installer because we want to sign the binaries before they are added to the MSI
script: |
make build BUILD_RE2_WASM=1
- pwsh: |
$build_version=$env:BUILD_SOURCEBRANCHNAME
#Override the version if it's set in the pipeline
if ( ${env:USERBUILDVERSION} -ne "")
{
$build_version = ${env:USERBUILDVERSION}
}
if ($build_version.StartsWith("v"))
{
$build_version = $build_version.Substring(1)
}
if ($build_version.Contains("-"))
{
$build_version = $build_version.Substring(0, $build_version.IndexOf("-"))
}
Write-Host "##vso[task.setvariable variable=BuildVersion;isOutput=true]$build_version"
displayName: GetCrowdsecVersion
name: GetCrowdsecVersion
- pwsh: |
Get-ChildItem -Path .\cmd -Directory | ForEach-Object {
$dirName = $_.Name
Get-ChildItem -Path .\cmd\$dirName -File -Filter '*.exe' | ForEach-Object {
$fileName = $_.Name
$destDir = Join-Path $(Build.ArtifactStagingDirectory) cmd\$dirName
New-Item -ItemType Directory -Path $destDir -Force
Copy-Item -Path .\cmd\$dirName\$fileName -Destination $destDir
}
}
displayName: "Copy binaries to staging directory"
- task: PublishPipelineArtifact@1
inputs:
targetPath: '$(Build.ArtifactStagingDirectory)'
artifact: 'unsigned_binaries'
displayName: "Upload binaries artifact"
- stage: Sign
dependsOn: Build
variables:
- group: 'FOSS Build Variables'
- name: BuildVersion
value: $[ stageDependencies.Build.Build.outputs['GetCrowdsecVersion.BuildVersion'] ]
condition: succeeded()
jobs:
- job: Sign
displayName: "Sign"
steps:
- download: current
artifact: unsigned_binaries
displayName: "Download binaries artifact"
- task: CopyFiles@2
inputs:
SourceFolder: '$(Pipeline.Workspace)/unsigned_binaries'
TargetFolder: '$(Build.SourcesDirectory)'
displayName: "Copy binaries to workspace"
- task: DotNetCoreCLI@2
displayName: "Install SignTool tool"
inputs:
command: 'custom'
custom: 'tool'
arguments: install --global sign --version 0.9.0-beta.23127.3
- task: AzureKeyVault@2
displayName: "Get signing parameters"
inputs:
azureSubscription: "Azure subscription"
KeyVaultName: "$(KeyVaultName)"
SecretsFilter: "TenantId,ClientId,ClientSecret,Certificate,KeyVaultUrl"
- pwsh: |
sign code azure-key-vault `
"**/*.exe" `
--base-directory "$(Build.SourcesDirectory)/cmd/" `
--publisher-name "CrowdSec" `
--description "CrowdSec" `
--description-url "https://github.com/crowdsecurity/crowdsec" `
--azure-key-vault-tenant-id "$(TenantId)" `
--azure-key-vault-client-id "$(ClientId)" `
--azure-key-vault-client-secret "$(ClientSecret)" `
--azure-key-vault-certificate "$(Certificate)" `
--azure-key-vault-url "$(KeyVaultUrl)"
displayName: "Sign crowdsec binaries"
- pwsh: |
.\make_installer.ps1 -version '$(BuildVersion)'
displayName: "Build Crowdsec MSI"
name: BuildMSI
- pwsh: |
.\make_chocolatey.ps1 -version '$(BuildVersion)'
displayName: "Build Chocolatey nupkg"
- pwsh: |
sign code azure-key-vault `
"*.msi" `
--base-directory "$(Build.SourcesDirectory)" `
--publisher-name "CrowdSec" `
--description "CrowdSec" `
--description-url "https://github.com/crowdsecurity/crowdsec" `
--azure-key-vault-tenant-id "$(TenantId)" `
--azure-key-vault-client-id "$(ClientId)" `
--azure-key-vault-client-secret "$(ClientSecret)" `
--azure-key-vault-certificate "$(Certificate)" `
--azure-key-vault-url "$(KeyVaultUrl)"
displayName: "Sign MSI package"
- pwsh: |
sign code azure-key-vault `
"*.nupkg" `
--base-directory "$(Build.SourcesDirectory)" `
--publisher-name "CrowdSec" `
--description "CrowdSec" `
--description-url "https://github.com/crowdsecurity/crowdsec" `
--azure-key-vault-tenant-id "$(TenantId)" `
--azure-key-vault-client-id "$(ClientId)" `
--azure-key-vault-client-secret "$(ClientSecret)" `
--azure-key-vault-certificate "$(Certificate)" `
--azure-key-vault-url "$(KeyVaultUrl)"
displayName: "Sign nuget package"
- task: PublishPipelineArtifact@1
inputs:
targetPath: '$(Build.SourcesDirectory)/crowdsec_$(BuildVersion).msi'
artifact: 'signed_msi_package'
displayName: "Upload signed MSI artifact"
- task: PublishPipelineArtifact@1
inputs:
targetPath: '$(Build.SourcesDirectory)/crowdsec.$(BuildVersion).nupkg'
artifact: 'signed_nuget_package'
displayName: "Upload signed nuget artifact"
- stage: Publish
dependsOn: Sign
jobs:
- deployment: "Publish"
displayName: "Publish to GitHub"
environment: github
strategy:
runOnce:
deploy:
steps:
- bash: |
tag=$(curl -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/crowdsecurity/crowdsec/releases | jq -r '. | map(select(.prerelease==true)) | sort_by(.created_at) | reverse | .[0].tag_name')
echo "##vso[task.setvariable variable=LatestPreRelease;isOutput=true]$tag"
name: GetLatestPrelease
- task: GitHubRelease@1
inputs:
gitHubConnection: "github.com_blotus"
repositoryName: '$(Build.Repository.Name)'
action: 'edit'
tag: '$(GetLatestPrelease.LatestPreRelease)'
assetUploadMode: 'replace'
addChangeLog: false
isPreRelease: true #we force prerelease because the pipeline is invoked on tag creation, which happens when we do a prerelease
assets: |
$(Pipeline.Workspace)/signed_msi_package/*.msi
$(Pipeline.Workspace)/signed_nuget_package/*.nupkg
condition: ne(variables['GetLatestPrelease.LatestPreRelease'], '')

View file

@ -1,21 +1,23 @@
# Go parameters
GOCMD=go
GOBUILD=$(GOCMD) build
GOCLEAN=$(GOCMD) clean
GOTEST=$(GOCMD) test
GOGET=$(GOCMD) get
BINARY_NAME=cscli
PREFIX?="/"
ifeq ($(OS), Windows_NT)
SHELL := pwsh.exe
.SHELLFLAGS := -NoProfile -Command
EXT = .exe
endif
GO = go
GOBUILD = $(GO) build
BINARY_NAME = cscli$(EXT)
PREFIX ?= "/"
BIN_PREFIX = $(PREFIX)"/usr/local/bin/"
.PHONY: all
all: clean build
build: clean
@$(GOBUILD) $(LD_OPTS) -o $(BINARY_NAME) -v
static: clean
@$(GOBUILD) $(LD_OPTS_STATIC) -o $(BINARY_NAME) -v -a -tags netgo
$(GOBUILD) $(LD_OPTS) -o $(BINARY_NAME)
.PHONY: install
install: install-conf install-bin
install-conf:
@ -24,8 +26,8 @@ install-bin:
@install -v -m 755 -D "$(BINARY_NAME)" "$(BIN_PREFIX)/$(BINARY_NAME)" || exit
uninstall:
@rm -rf $(CSCLI_CONFIG)
@rm -rf $(BIN_PREFIX)$(BINARY_NAME)
@$(RM) $(CSCLI_CONFIG) $(WIN_IGNORE_ERR)
@$(RM) $(BIN_PREFIX)$(BINARY_NAME) $(WIN_IGNORE_ERR)
clean:
@rm -f $(BINARY_NAME)
@$(RM) $(BINARY_NAME) $(WIN_IGNORE_ERR)

View file

@ -1 +0,0 @@
see doc in `doc/`

View file

@ -2,236 +2,235 @@ package main
import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"text/template"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/olekukonko/tablewriter"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
"gopkg.in/yaml.v3"
var printMachine bool
var limit *int
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
func DecisionsFromAlert(alert *models.Alert) string {
ret := ""
var decMap = make(map[string]int)
decMap := make(map[string]int)
for _, decision := range alert.Decisions {
k := *decision.Type
if *decision.Simulated {
k = fmt.Sprintf("(simul)%s", k)
}
v := decMap[k]
decMap[k] = v + 1
}
for k, v := range decMap {
if len(ret) > 0 {
ret += " "
}
ret += fmt.Sprintf("%s:%d", k, v)
}
return ret
}
func AlertsToTable(alerts *models.GetAlertsResponse, printMachine bool) error {
func (cli *cliAlerts) alertsToTable(alerts *models.GetAlertsResponse, printMachine bool) error {
switch cli.cfg().Cscli.Output {
case "raw":
csvwriter := csv.NewWriter(os.Stdout)
header := []string{"id", "scope", "value", "reason", "country", "as", "decisions", "created_at"}
if csConfig.Cscli.Output == "raw" {
if printMachine {
fmt.Printf("id,scope,value,reason,country,as,decisions,created_at,machine\n")
} else {
fmt.Printf("id,scope,value,reason,country,as,decisions,created_at\n")
header = append(header, "machine")
}
if err := csvwriter.Write(header); err != nil {
return err
}
for _, alertItem := range *alerts {
row := []string{
strconv.FormatInt(alertItem.ID, 10),
*alertItem.Source.Scope,
*alertItem.Source.Value,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.GetAsNumberName(),
DecisionsFromAlert(alertItem),
*alertItem.StartAt,
}
if printMachine {
fmt.Printf("%v,%v,%v,%v,%v,%v,%v,%v,%v\n",
alertItem.ID,
*alertItem.Source.Scope,
*alertItem.Source.Value,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.AsNumber+" "+alertItem.Source.AsName,
DecisionsFromAlert(alertItem),
*alertItem.StartAt,
alertItem.MachineID)
} else {
fmt.Printf("%v,%v,%v,%v,%v,%v,%v,%v\n",
alertItem.ID,
*alertItem.Source.Scope,
*alertItem.Source.Value,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.AsNumber+" "+alertItem.Source.AsName,
DecisionsFromAlert(alertItem),
*alertItem.StartAt)
row = append(row, alertItem.MachineID)
}
if err := csvwriter.Write(row); err != nil {
return err
}
}
} else if csConfig.Cscli.Output == "json" {
csvwriter.Flush()
case "json":
if *alerts == nil {
// avoid returning "null" in json
// could be cleaner if we used slice of alerts directly
fmt.Println("[]")
return nil
}
x, _ := json.MarshalIndent(alerts, "", " ")
fmt.Printf("%s", string(x))
} else if csConfig.Cscli.Output == "human" {
table := tablewriter.NewWriter(os.Stdout)
if printMachine {
table.SetHeader([]string{"ID", "value", "reason", "country", "as", "decisions", "created_at", "machine"})
} else {
table.SetHeader([]string{"ID", "value", "reason", "country", "as", "decisions", "created_at"})
}
fmt.Print(string(x))
case "human":
if len(*alerts) == 0 {
fmt.Println("No active alerts")
return nil
}
for _, alertItem := range *alerts {
displayVal := *alertItem.Source.Scope
if *alertItem.Source.Value != "" {
displayVal += ":" + *alertItem.Source.Value
}
if printMachine {
table.Append([]string{
strconv.Itoa(int(alertItem.ID)),
displayVal,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.AsNumber + " " + alertItem.Source.AsName,
DecisionsFromAlert(alertItem),
*alertItem.StartAt,
alertItem.MachineID,
})
} else {
table.Append([]string{
strconv.Itoa(int(alertItem.ID)),
displayVal,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.AsNumber + " " + alertItem.Source.AsName,
DecisionsFromAlert(alertItem),
*alertItem.StartAt,
})
}
}
table.Render() // Send output
alertsTable(color.Output, alerts, printMachine)
}
return nil
}
func DisplayOneAlert(alert *models.Alert, withDetail bool) error {
if csConfig.Cscli.Output == "human" {
fmt.Printf("\n################################################################################################\n\n")
scopeAndValue := *alert.Source.Scope
if *alert.Source.Value != "" {
scopeAndValue += ":" + *alert.Source.Value
}
fmt.Printf(" - ID : %d\n", alert.ID)
fmt.Printf(" - Date : %s\n", alert.CreatedAt)
fmt.Printf(" - Machine : %s\n", alert.MachineID)
fmt.Printf(" - Simulation : %v\n", *alert.Simulated)
fmt.Printf(" - Reason : %s\n", *alert.Scenario)
fmt.Printf(" - Events Count : %d\n", *alert.EventsCount)
fmt.Printf(" - Scope:Value: %s\n", scopeAndValue)
fmt.Printf(" - Country : %s\n", alert.Source.Cn)
fmt.Printf(" - AS : %s\n\n", alert.Source.AsName)
foundActive := false
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "scope:value", "action", "expiration", "created_at"})
for _, decision := range alert.Decisions {
parsedDuration, err := time.ParseDuration(*decision.Duration)
if err != nil {
log.Errorf(err.Error())
var alertTemplate = `
################################################################################################
- ID : {{.ID}}
- Date : {{.CreatedAt}}
- Machine : {{.MachineID}}
- Simulation : {{.Simulated}}
- Reason : {{.Scenario}}
- Events Count : {{.EventsCount}}
- Scope:Value : {{.Source.Scope}}{{if .Source.Value}}:{{.Source.Value}}{{end}}
- Country : {{.Source.Cn}}
- AS : {{.Source.AsName}}
- Begin : {{.StartAt}}
- End : {{.StopAt}}
- UUID : {{.UUID}}
`
func (cli *cliAlerts) displayOneAlert(alert *models.Alert, withDetail bool) error {
tmpl, err := template.New("alert").Parse(alertTemplate)
if err != nil {
return err
}
if err = tmpl.Execute(os.Stdout, alert); err != nil {
return err
}
alertDecisionsTable(color.Output, alert)
if len(alert.Meta) > 0 {
fmt.Printf("\n - Context :\n")
sort.Slice(alert.Meta, func(i, j int) bool {
return alert.Meta[i].Key < alert.Meta[j].Key
})
table := newTable(color.Output)
table.SetRowLines(false)
table.SetHeaders("Key", "Value")
for _, meta := range alert.Meta {
var valSlice []string
if err := json.Unmarshal([]byte(meta.Value), &valSlice); err != nil {
return fmt.Errorf("unknown context value type '%s': %w", meta.Value, err)
}
expire := time.Now().Add(parsedDuration)
if time.Now().After(expire) {
continue
for _, value := range valSlice {
table.AddRow(
meta.Key,
value,
)
}
foundActive = true
scopeAndValue := *decision.Scope
if *decision.Value != "" {
scopeAndValue += ":" + *decision.Value
}
table.Append([]string{
strconv.Itoa(int(decision.ID)),
scopeAndValue,
*decision.Type,
*decision.Duration,
alert.CreatedAt,
})
}
if foundActive {
fmt.Printf(" - Active Decisions :\n")
table.Render() // Send output
}
if withDetail {
fmt.Printf("\n - Events :\n")
for _, event := range alert.Events {
fmt.Printf("\n- Date: %s\n", *event.Timestamp)
table = tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Key", "Value"})
sort.Slice(event.Meta, func(i, j int) bool {
return event.Meta[i].Key < event.Meta[j].Key
})
for _, meta := range event.Meta {
table.Append([]string{
meta.Key,
meta.Value,
})
}
table.Render()
}
table.Render() // Send output
}
if withDetail {
fmt.Printf("\n - Events :\n")
for _, event := range alert.Events {
alertEventTable(color.Output, event)
}
}
return nil
}
func NewAlertsCmd() *cobra.Command {
/* ---- ALERTS COMMAND */
var cmdAlerts = &cobra.Command{
Use: "alerts [action]",
Short: "Manage alerts",
Args: cobra.MinimumNArgs(1),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
var err error
if err := csConfig.LoadAPIClient(); err != nil {
log.Fatalf("loading api client: %s", err.Error())
type cliAlerts struct {
client *apiclient.ApiClient
cfg configGetter
}
func NewCLIAlerts(getconfig configGetter) *cliAlerts {
return &cliAlerts{
cfg: getconfig,
}
}
func (cli *cliAlerts) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "alerts [action]",
Short: "Manage alerts",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
Aliases: []string{"alert"},
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := cfg.LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %w", err)
}
if csConfig.API.Client == nil {
log.Fatalln("There is no configuration on 'api_client:'")
}
if csConfig.API.Client.Credentials == nil {
log.Fatalf("Please provide credentials for the API in '%s'", csConfig.API.Client.CredentialsFilePath)
}
apiURL, err := url.Parse(csConfig.API.Client.Credentials.URL)
apiURL, err := url.Parse(cfg.API.Client.Credentials.URL)
if err != nil {
log.Fatalf("parsing api url: %s", apiURL)
return fmt.Errorf("parsing api url %s: %w", apiURL, err)
}
Client, err = apiclient.NewClient(&apiclient.Config{
MachineID: csConfig.API.Client.Credentials.Login,
Password: strfmt.Password(csConfig.API.Client.Credentials.Password),
UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
cli.client, err = apiclient.NewClient(&apiclient.Config{
MachineID: cfg.API.Client.Credentials.Login,
Password: strfmt.Password(cfg.API.Client.Credentials.Password),
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiURL,
VersionPrefix: "v1",
})
if err != nil {
log.Fatalf("new api client: %s", err.Error())
return fmt.Errorf("new api client: %w", err)
}
return nil
},
}
var alertListFilter = apiclient.AlertsListOpts{
cmd.AddCommand(cli.NewListCmd())
cmd.AddCommand(cli.NewInspectCmd())
cmd.AddCommand(cli.NewFlushCmd())
cmd.AddCommand(cli.NewDeleteCmd())
return cmd
}
func (cli *cliAlerts) NewListCmd() *cobra.Command {
alertListFilter := apiclient.AlertsListOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
ScenarioEquals: new(string),
@ -240,24 +239,31 @@ func NewAlertsCmd() *cobra.Command {
Since: new(string),
Until: new(string),
TypeEquals: new(string),
IncludeCAPI: new(bool),
OriginEquals: new(string),
}
limit = new(int)
limit := new(int)
contained := new(bool)
var cmdAlertsList = &cobra.Command{
var printMachine bool
cmd := &cobra.Command{
Use: "list [filters]",
Short: "List alerts",
Example: `cscli alerts list
cscli alerts list --ip 1.2.3.4
cscli alerts list --range 1.2.3.0/24
cscli alerts list --origin lists
cscli alerts list -s crowdsecurity/ssh-bf
cscli alerts list --type ban`,
Run: func(cmd *cobra.Command, args []string) {
var err error
Long: `List alerts with optional filters`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
if err := manageCliDecisionAlerts(alertListFilter.IPEquals, alertListFilter.RangeEquals,
alertListFilter.ScopeEquals, alertListFilter.ValueEquals); err != nil {
_ = cmd.Help()
log.Fatalf("%s", err)
printHelp(cmd)
return err
}
if limit != nil {
alertListFilter.Limit = limit
@ -265,32 +271,33 @@ cscli alerts list --type ban`,
if *alertListFilter.Until == "" {
alertListFilter.Until = nil
} else {
} else if strings.HasSuffix(*alertListFilter.Until, "d") {
/*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
if strings.HasSuffix(*alertListFilter.Until, "d") {
realDuration := strings.TrimSuffix(*alertListFilter.Until, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
cmd.Help()
log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *alertListFilter.Until)
}
*alertListFilter.Until = fmt.Sprintf("%d%s", days*24, "h")
realDuration := strings.TrimSuffix(*alertListFilter.Until, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
printHelp(cmd)
return fmt.Errorf("can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *alertListFilter.Until)
}
*alertListFilter.Until = fmt.Sprintf("%d%s", days*24, "h")
}
if *alertListFilter.Since == "" {
alertListFilter.Since = nil
} else {
} else if strings.HasSuffix(*alertListFilter.Since, "d") {
/*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
if strings.HasSuffix(*alertListFilter.Since, "d") {
realDuration := strings.TrimSuffix(*alertListFilter.Since, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
cmd.Help()
log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *alertListFilter.Since)
}
*alertListFilter.Since = fmt.Sprintf("%d%s", days*24, "h")
realDuration := strings.TrimSuffix(*alertListFilter.Since, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
printHelp(cmd)
return fmt.Errorf("can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *alertListFilter.Since)
}
*alertListFilter.Since = fmt.Sprintf("%d%s", days*24, "h")
}
if *alertListFilter.IncludeCAPI {
*alertListFilter.Limit = 0
}
if *alertListFilter.TypeEquals == "" {
alertListFilter.TypeEquals = nil
}
@ -309,70 +316,95 @@ cscli alerts list --type ban`,
if *alertListFilter.RangeEquals == "" {
alertListFilter.RangeEquals = nil
}
if *alertListFilter.OriginEquals == "" {
alertListFilter.OriginEquals = nil
}
if contained != nil && *contained {
alertListFilter.Contains = new(bool)
}
alerts, _, err := Client.Alerts.List(context.Background(), alertListFilter)
alerts, _, err := cli.client.Alerts.List(context.Background(), alertListFilter)
if err != nil {
log.Fatalf("Unable to list alerts : %v", err.Error())
return fmt.Errorf("unable to list alerts: %w", err)
}
err = AlertsToTable(alerts, printMachine)
if err != nil {
log.Fatalf("unable to list alerts : %v", err.Error())
if err = cli.alertsToTable(alerts, printMachine); err != nil {
return fmt.Errorf("unable to list alerts: %w", err)
}
return nil
},
}
cmdAlertsList.Flags().SortFlags = false
cmdAlertsList.Flags().StringVar(alertListFilter.Until, "until", "", "restrict to alerts older than until (ie. 4h, 30d)")
cmdAlertsList.Flags().StringVar(alertListFilter.Since, "since", "", "restrict to alerts newer than since (ie. 4h, 30d)")
cmdAlertsList.Flags().StringVarP(alertListFilter.IPEquals, "ip", "i", "", "restrict to alerts from this source ip (shorthand for --scope ip --value <IP>)")
cmdAlertsList.Flags().StringVarP(alertListFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
cmdAlertsList.Flags().StringVarP(alertListFilter.RangeEquals, "range", "r", "", "restrict to alerts from this range (shorthand for --scope range --value <RANGE/X>)")
cmdAlertsList.Flags().StringVar(alertListFilter.TypeEquals, "type", "", "restrict to alerts with given decision type (ie. ban, captcha)")
cmdAlertsList.Flags().StringVar(alertListFilter.ScopeEquals, "scope", "", "restrict to alerts of this scope (ie. ip,range)")
cmdAlertsList.Flags().StringVarP(alertListFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
cmdAlertsList.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
cmdAlertsList.Flags().BoolVarP(&printMachine, "machine", "m", false, "print machines that sended alerts")
cmdAlertsList.Flags().IntVarP(limit, "limit", "l", 50, "limit size of alerts list table (0 to view all alerts)")
cmdAlerts.AddCommand(cmdAlertsList)
var ActiveDecision *bool
var AlertDeleteAll bool
var alertDeleteFilter = apiclient.AlertsDeleteOpts{
flags := cmd.Flags()
flags.SortFlags = false
flags.BoolVarP(alertListFilter.IncludeCAPI, "all", "a", false, "Include decisions from Central API")
flags.StringVar(alertListFilter.Until, "until", "", "restrict to alerts older than until (ie. 4h, 30d)")
flags.StringVar(alertListFilter.Since, "since", "", "restrict to alerts newer than since (ie. 4h, 30d)")
flags.StringVarP(alertListFilter.IPEquals, "ip", "i", "", "restrict to alerts from this source ip (shorthand for --scope ip --value <IP>)")
flags.StringVarP(alertListFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
flags.StringVarP(alertListFilter.RangeEquals, "range", "r", "", "restrict to alerts from this range (shorthand for --scope range --value <RANGE/X>)")
flags.StringVar(alertListFilter.TypeEquals, "type", "", "restrict to alerts with given decision type (ie. ban, captcha)")
flags.StringVar(alertListFilter.ScopeEquals, "scope", "", "restrict to alerts of this scope (ie. ip,range)")
flags.StringVarP(alertListFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
flags.StringVar(alertListFilter.OriginEquals, "origin", "", fmt.Sprintf("the value to match for the specified origin (%s ...)", strings.Join(types.GetOrigins(), ",")))
flags.BoolVar(contained, "contained", false, "query decisions contained by range")
flags.BoolVarP(&printMachine, "machine", "m", false, "print machines that sent alerts")
flags.IntVarP(limit, "limit", "l", 50, "limit size of alerts list table (0 to view all alerts)")
return cmd
}
func (cli *cliAlerts) NewDeleteCmd() *cobra.Command {
var (
ActiveDecision *bool
AlertDeleteAll bool
delAlertByID string
)
alertDeleteFilter := apiclient.AlertsDeleteOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
ScenarioEquals: new(string),
IPEquals: new(string),
RangeEquals: new(string),
}
var cmdAlertsDelete = &cobra.Command{
contained := new(bool)
cmd := &cobra.Command{
Use: "delete [filters] [--all]",
Short: `Delete alerts
/!\ This command can be use only on the same machine than the local API.`,
Example: `cscli alerts delete --ip 1.2.3.4
cscli alerts delete --range 1.2.3.0/24
cscli alerts delete -s crowdsecurity/ssh-bf"`,
Args: cobra.ExactArgs(0),
PreRun: func(cmd *cobra.Command, args []string) {
DisableAutoGenTag: true,
Aliases: []string{"remove"},
Args: cobra.ExactArgs(0),
PreRunE: func(cmd *cobra.Command, _ []string) error {
if AlertDeleteAll {
return
return nil
}
if *alertDeleteFilter.ScopeEquals == "" && *alertDeleteFilter.ValueEquals == "" &&
*alertDeleteFilter.ScenarioEquals == "" && *alertDeleteFilter.IPEquals == "" &&
*alertDeleteFilter.RangeEquals == "" {
*alertDeleteFilter.RangeEquals == "" && delAlertByID == "" {
_ = cmd.Usage()
log.Fatalln("At least one filter or --all must be specified")
return errors.New("at least one filter or --all must be specified")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, _ []string) error {
var err error
if !AlertDeleteAll {
if err := manageCliDecisionAlerts(alertDeleteFilter.IPEquals, alertDeleteFilter.RangeEquals,
if err = manageCliDecisionAlerts(alertDeleteFilter.IPEquals, alertDeleteFilter.RangeEquals,
alertDeleteFilter.ScopeEquals, alertDeleteFilter.ValueEquals); err != nil {
_ = cmd.Help()
log.Fatalf("%s", err)
printHelp(cmd)
return err
}
if ActiveDecision != nil {
alertDeleteFilter.ActiveDecisionEquals = ActiveDecision
@ -396,74 +428,133 @@ cscli alerts delete -s crowdsecurity/ssh-bf"`,
if contained != nil && *contained {
alertDeleteFilter.Contains = new(bool)
}
limit := 0
alertDeleteFilter.Limit = &limit
} else {
limit := 0
alertDeleteFilter = apiclient.AlertsDeleteOpts{Limit: &limit}
}
alerts, _, err := Client.Alerts.Delete(context.Background(), alertDeleteFilter)
if err != nil {
log.Fatalf("Unable to delete alerts : %v", err.Error())
var alerts *models.DeleteAlertsResponse
if delAlertByID == "" {
alerts, _, err = cli.client.Alerts.Delete(context.Background(), alertDeleteFilter)
if err != nil {
return fmt.Errorf("unable to delete alerts: %w", err)
}
} else {
alerts, _, err = cli.client.Alerts.DeleteOne(context.Background(), delAlertByID)
if err != nil {
return fmt.Errorf("unable to delete alert: %w", err)
}
}
log.Infof("%s alert(s) deleted", alerts.NbDeleted)
return nil
},
}
cmdAlertsDelete.Flags().SortFlags = false
cmdAlertsDelete.Flags().StringVar(alertDeleteFilter.ScopeEquals, "scope", "", "the scope (ie. ip,range)")
cmdAlertsDelete.Flags().StringVarP(alertDeleteFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
cmdAlertsDelete.Flags().StringVarP(alertDeleteFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
cmdAlertsDelete.Flags().StringVarP(alertDeleteFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
cmdAlertsDelete.Flags().StringVarP(alertDeleteFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
cmdAlertsDelete.Flags().BoolVarP(&AlertDeleteAll, "all", "a", false, "delete all alerts")
cmdAlertsDelete.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
cmdAlerts.AddCommand(cmdAlertsDelete)
flags := cmd.Flags()
flags.SortFlags = false
flags.StringVar(alertDeleteFilter.ScopeEquals, "scope", "", "the scope (ie. ip,range)")
flags.StringVarP(alertDeleteFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
flags.StringVarP(alertDeleteFilter.ScenarioEquals, "scenario", "s", "", "the scenario (ie. crowdsecurity/ssh-bf)")
flags.StringVarP(alertDeleteFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
flags.StringVarP(alertDeleteFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
flags.StringVar(&delAlertByID, "id", "", "alert ID")
flags.BoolVarP(&AlertDeleteAll, "all", "a", false, "delete all alerts")
flags.BoolVar(contained, "contained", false, "query decisions contained by range")
return cmd
}
func (cli *cliAlerts) NewInspectCmd() *cobra.Command {
var details bool
var cmdAlertsInspect = &cobra.Command{
Use: "inspect <alert_id>",
Short: `Show info about an alert`,
Example: `cscli alerts inspect 123`,
Run: func(cmd *cobra.Command, args []string) {
cmd := &cobra.Command{
Use: `inspect "alert_id"`,
Short: `Show info about an alert`,
Example: `cscli alerts inspect 123`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := cli.cfg()
if len(args) == 0 {
_ = cmd.Help()
return
printHelp(cmd)
return errors.New("missing alert_id")
}
for _, alertID := range args {
id, err := strconv.Atoi(alertID)
if err != nil {
log.Fatalf("bad alert id %s", alertID)
continue
return fmt.Errorf("bad alert id %s", alertID)
}
alert, _, err := Client.Alerts.GetByID(context.Background(), id)
alert, _, err := cli.client.Alerts.GetByID(context.Background(), id)
if err != nil {
log.Fatalf("can't find alert with id %s: %s", alertID, err)
return fmt.Errorf("can't find alert with id %s: %w", alertID, err)
}
switch csConfig.Cscli.Output {
switch cfg.Cscli.Output {
case "human":
if err := DisplayOneAlert(alert, details); err != nil {
if err := cli.displayOneAlert(alert, details); err != nil {
continue
}
case "json":
data, err := json.MarshalIndent(alert, "", " ")
if err != nil {
log.Fatalf("unable to marshal alert with id %s: %s", alertID, err)
return fmt.Errorf("unable to marshal alert with id %s: %w", alertID, err)
}
fmt.Printf("%s\n", string(data))
case "raw":
data, err := yaml.Marshal(alert)
if err != nil {
log.Fatalf("unable to marshal alert with id %s: %s", alertID, err)
return fmt.Errorf("unable to marshal alert with id %s: %w", alertID, err)
}
fmt.Printf("%s\n", string(data))
fmt.Println(string(data))
}
}
return nil
},
}
cmdAlertsInspect.Flags().SortFlags = false
cmdAlertsInspect.Flags().BoolVarP(&details, "details", "d", false, "show alerts with events")
cmdAlerts.AddCommand(cmdAlertsInspect)
cmd.Flags().SortFlags = false
cmd.Flags().BoolVarP(&details, "details", "d", false, "show alerts with events")
return cmdAlerts
return cmd
}
func (cli *cliAlerts) NewFlushCmd() *cobra.Command {
var (
maxItems int
maxAge string
)
cmd := &cobra.Command{
Use: `flush`,
Short: `Flush alerts
/!\ This command can be used only on the same machine than the local API`,
Example: `cscli alerts flush --max-items 1000 --max-age 7d`,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := require.LAPI(cfg); err != nil {
return err
}
db, err := database.NewClient(cfg.DbConfig)
if err != nil {
return fmt.Errorf("unable to create new database client: %w", err)
}
log.Info("Flushing alerts. !! This may take a long time !!")
err = db.FlushAlerts(maxAge, maxItems)
if err != nil {
return fmt.Errorf("unable to flush alerts: %w", err)
}
log.Info("Alerts flushed")
return nil
},
}
cmd.Flags().SortFlags = false
cmd.Flags().IntVar(&maxItems, "max-items", 5000, "Maximum number of alert items to keep in the database")
cmd.Flags().StringVar(&maxAge, "max-age", "7d", "Maximum age of alert items to keep in the database")
return cmd
}

View file

@ -0,0 +1,102 @@
package main
import (
"fmt"
"io"
"sort"
"strconv"
"time"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
func alertsTable(out io.Writer, alerts *models.GetAlertsResponse, printMachine bool) {
t := newTable(out)
t.SetRowLines(false)
header := []string{"ID", "value", "reason", "country", "as", "decisions", "created_at"}
if printMachine {
header = append(header, "machine")
}
t.SetHeaders(header...)
for _, alertItem := range *alerts {
displayVal := *alertItem.Source.Scope
if len(alertItem.Decisions) > 1 {
displayVal = fmt.Sprintf("%s (%d %ss)", *alertItem.Source.Scope, len(alertItem.Decisions), *alertItem.Decisions[0].Scope)
} else if *alertItem.Source.Value != "" {
displayVal += ":" + *alertItem.Source.Value
}
row := []string{
strconv.Itoa(int(alertItem.ID)),
displayVal,
*alertItem.Scenario,
alertItem.Source.Cn,
alertItem.Source.GetAsNumberName(),
DecisionsFromAlert(alertItem),
*alertItem.StartAt,
}
if printMachine {
row = append(row, alertItem.MachineID)
}
t.AddRow(row...)
}
t.Render()
}
func alertDecisionsTable(out io.Writer, alert *models.Alert) {
foundActive := false
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("ID", "scope:value", "action", "expiration", "created_at")
for _, decision := range alert.Decisions {
parsedDuration, err := time.ParseDuration(*decision.Duration)
if err != nil {
log.Error(err)
}
expire := time.Now().UTC().Add(parsedDuration)
if time.Now().UTC().After(expire) {
continue
}
foundActive = true
scopeAndValue := *decision.Scope
if *decision.Value != "" {
scopeAndValue += ":" + *decision.Value
}
t.AddRow(
strconv.Itoa(int(decision.ID)),
scopeAndValue,
*decision.Type,
*decision.Duration,
alert.CreatedAt,
)
}
if foundActive {
fmt.Printf(" - Active Decisions :\n")
t.Render() // Send output
}
}
func alertEventTable(out io.Writer, event *models.Event) {
fmt.Fprintf(out, "\n- Date: %s\n", *event.Timestamp)
t := newTable(out)
t.SetHeaders("Key", "Value")
sort.Slice(event.Meta, func(i, j int) bool {
return event.Meta[i].Key < event.Meta[j].Key
})
for _, meta := range event.Meta {
t.AddRow(
meta.Key,
meta.Value,
)
}
t.Render() // Send output
}

View file

@ -1,157 +1,320 @@
package main
import (
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"os"
"slices"
"strings"
"time"
middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/enescakir/emoji"
"github.com/olekukonko/tablewriter"
"github.com/AlecAivazis/survey/v2"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
middlewares "github.com/crowdsecurity/crowdsec/pkg/apiserver/middlewares/v1"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
var keyName string
var keyIP string
var keyLength int
func askYesNo(message string, defaultAnswer bool) (bool, error) {
var answer bool
func NewBouncersCmd() *cobra.Command {
/* ---- DECISIONS COMMAND */
var cmdBouncers = &cobra.Command{
prompt := &survey.Confirm{
Message: message,
Default: defaultAnswer,
}
if err := survey.AskOne(prompt, &answer); err != nil {
return defaultAnswer, err
}
return answer, nil
}
type cliBouncers struct {
db *database.Client
cfg configGetter
}
func NewCLIBouncers(cfg configGetter) *cliBouncers {
return &cliBouncers{
cfg: cfg,
}
}
func (cli *cliBouncers) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "bouncers [action]",
Short: "Manage bouncers [requires local API]",
Long: `To list/add/delete bouncers.
Long: `To list/add/delete/prune bouncers.
Note: This command requires database direct access, so is intended to be run on Local API/master.
`,
Args: cobra.MinimumNArgs(1),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
Args: cobra.MinimumNArgs(1),
Aliases: []string{"bouncer"},
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
var err error
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
cfg := cli.cfg()
if err = require.LAPI(cfg); err != nil {
return err
}
if err := csConfig.LoadDBConfig(); err != nil {
log.Fatalf(err.Error())
}
dbClient, err = database.NewClient(csConfig.DbConfig)
cli.db, err = database.NewClient(cfg.DbConfig)
if err != nil {
log.Fatalf("unable to create new database client: %s", err)
return fmt.Errorf("can't connect to the database: %w", err)
}
return nil
},
}
var cmdBouncersList = &cobra.Command{
Use: "list",
Short: "List bouncers",
Long: `List bouncers`,
Example: `cscli bouncers list`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, arg []string) {
blockers, err := dbClient.ListBouncers()
if err != nil {
log.Errorf("unable to list blockers: %s", err)
}
if csConfig.Cscli.Output == "human" {
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newAddCmd())
cmd.AddCommand(cli.newDeleteCmd())
cmd.AddCommand(cli.newPruneCmd())
table := tablewriter.NewWriter(os.Stdout)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeader([]string{"Name", "IP Address", "Valid", "Last API pull", "Type", "Version"})
for _, b := range blockers {
var revoked string
if !b.Revoked {
revoked = fmt.Sprintf("%s", emoji.CheckMark)
} else {
revoked = fmt.Sprintf("%s", emoji.Prohibited)
}
table.Append([]string{b.Name, b.IPAddress, revoked, b.LastPull.Format(time.RFC3339), b.Type, b.Version})
}
table.Render()
} else if csConfig.Cscli.Output == "json" {
x, err := json.MarshalIndent(blockers, "", " ")
if err != nil {
log.Fatalf("failed to unmarshal")
}
fmt.Printf("%s", string(x))
} else if csConfig.Cscli.Output == "raw" {
for _, b := range blockers {
var revoked string
if !b.Revoked {
revoked = "validated"
} else {
revoked = "pending"
}
fmt.Printf("%s,%s,%s,%s,%s\n", b.Name, b.IPAddress, revoked, b.LastPull.Format(time.RFC3339), b.Version)
}
}
},
}
cmdBouncers.AddCommand(cmdBouncersList)
var cmdBouncersAdd = &cobra.Command{
Use: "add MyBouncerName [--length 16]",
Short: "add bouncer",
Long: `add bouncer`,
Example: `cscli bouncers add MyBouncerName
cscli bouncers add MyBouncerName -l 24`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, arg []string) {
keyName := arg[0]
if keyName == "" {
log.Errorf("Please provide a name for the api key")
return
}
apiKey, err := middlewares.GenerateAPIKey(keyLength)
if err != nil {
log.Errorf("unable to generate api key: %s", err)
return
}
err = dbClient.CreateBouncer(keyName, keyIP, middlewares.HashSHA512(apiKey))
if err != nil {
log.Errorf("unable to create bouncer: %s", err)
return
}
if csConfig.Cscli.Output == "human" {
fmt.Printf("Api key for '%s':\n\n", keyName)
fmt.Printf(" %s\n\n", apiKey)
fmt.Print("Please keep this key since you will not be able to retrieve it!\n")
} else if csConfig.Cscli.Output == "raw" {
fmt.Printf("%s", apiKey)
} else if csConfig.Cscli.Output == "json" {
j, err := json.Marshal(apiKey)
if err != nil {
log.Fatalf("unable to marshal api key")
}
fmt.Printf("%s", string(j))
}
},
}
cmdBouncersAdd.Flags().IntVarP(&keyLength, "length", "l", 16, "length of the api key")
cmdBouncers.AddCommand(cmdBouncersAdd)
var cmdBouncersDelete = &cobra.Command{
Use: "delete MyBouncerName",
Short: "delete bouncer",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, arg []string) {
keyName := arg[0]
if keyName == "" {
log.Errorf("Please provide a bouncer name")
return
}
err := dbClient.DeleteBouncer(keyName)
if err != nil {
log.Errorf("unable to delete bouncer: %s", err)
return
}
},
}
cmdBouncers.AddCommand(cmdBouncersDelete)
return cmdBouncers
return cmd
}
func (cli *cliBouncers) list() error {
out := color.Output
bouncers, err := cli.db.ListBouncers()
if err != nil {
return fmt.Errorf("unable to list bouncers: %w", err)
}
switch cli.cfg().Cscli.Output {
case "human":
getBouncersTable(out, bouncers)
case "json":
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
if err := enc.Encode(bouncers); err != nil {
return fmt.Errorf("failed to marshal: %w", err)
}
return nil
case "raw":
csvwriter := csv.NewWriter(out)
if err := csvwriter.Write([]string{"name", "ip", "revoked", "last_pull", "type", "version", "auth_type"}); err != nil {
return fmt.Errorf("failed to write raw header: %w", err)
}
for _, b := range bouncers {
valid := "validated"
if b.Revoked {
valid = "pending"
}
if err := csvwriter.Write([]string{b.Name, b.IPAddress, valid, b.LastPull.Format(time.RFC3339), b.Type, b.Version, b.AuthType}); err != nil {
return fmt.Errorf("failed to write raw: %w", err)
}
}
csvwriter.Flush()
}
return nil
}
func (cli *cliBouncers) newListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list all bouncers within the database",
Example: `cscli bouncers list`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list()
},
}
return cmd
}
func (cli *cliBouncers) add(bouncerName string, key string) error {
var err error
keyLength := 32
if key == "" {
key, err = middlewares.GenerateAPIKey(keyLength)
if err != nil {
return fmt.Errorf("unable to generate api key: %w", err)
}
}
_, err = cli.db.CreateBouncer(bouncerName, "", middlewares.HashSHA512(key), types.ApiKeyAuthType)
if err != nil {
return fmt.Errorf("unable to create bouncer: %w", err)
}
switch cli.cfg().Cscli.Output {
case "human":
fmt.Printf("API key for '%s':\n\n", bouncerName)
fmt.Printf(" %s\n\n", key)
fmt.Print("Please keep this key since you will not be able to retrieve it!\n")
case "raw":
fmt.Print(key)
case "json":
j, err := json.Marshal(key)
if err != nil {
return errors.New("unable to marshal api key")
}
fmt.Print(string(j))
}
return nil
}
func (cli *cliBouncers) newAddCmd() *cobra.Command {
var key string
cmd := &cobra.Command{
Use: "add MyBouncerName",
Short: "add a single bouncer to the database",
Example: `cscli bouncers add MyBouncerName
cscli bouncers add MyBouncerName --key <random-key>`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
return cli.add(args[0], key)
},
}
flags := cmd.Flags()
flags.StringP("length", "l", "", "length of the api key")
_ = flags.MarkDeprecated("length", "use --key instead")
flags.StringVarP(&key, "key", "k", "", "api key for the bouncer")
return cmd
}
func (cli *cliBouncers) deleteValid(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
bouncers, err := cli.db.ListBouncers()
if err != nil {
cobra.CompError("unable to list bouncers " + err.Error())
}
ret := []string{}
for _, bouncer := range bouncers {
if strings.Contains(bouncer.Name, toComplete) && !slices.Contains(args, bouncer.Name) {
ret = append(ret, bouncer.Name)
}
}
return ret, cobra.ShellCompDirectiveNoFileComp
}
func (cli *cliBouncers) delete(bouncers []string) error {
for _, bouncerID := range bouncers {
err := cli.db.DeleteBouncer(bouncerID)
if err != nil {
return fmt.Errorf("unable to delete bouncer '%s': %w", bouncerID, err)
}
log.Infof("bouncer '%s' deleted successfully", bouncerID)
}
return nil
}
func (cli *cliBouncers) newDeleteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "delete MyBouncerName",
Short: "delete bouncer(s) from the database",
Args: cobra.MinimumNArgs(1),
Aliases: []string{"remove"},
DisableAutoGenTag: true,
ValidArgsFunction: cli.deleteValid,
RunE: func(_ *cobra.Command, args []string) error {
return cli.delete(args)
},
}
return cmd
}
func (cli *cliBouncers) prune(duration time.Duration, force bool) error {
if duration < 2*time.Minute {
if yes, err := askYesNo(
"The duration you provided is less than 2 minutes. " +
"This may remove active bouncers. Continue?", false); err != nil {
return err
} else if !yes {
fmt.Println("User aborted prune. No changes were made.")
return nil
}
}
bouncers, err := cli.db.QueryBouncersLastPulltimeLT(time.Now().UTC().Add(-duration))
if err != nil {
return fmt.Errorf("unable to query bouncers: %w", err)
}
if len(bouncers) == 0 {
fmt.Println("No bouncers to prune.")
return nil
}
getBouncersTable(color.Output, bouncers)
if !force {
if yes, err := askYesNo(
"You are about to PERMANENTLY remove the above bouncers from the database. " +
"These will NOT be recoverable. Continue?", false); err != nil {
return err
} else if !yes {
fmt.Println("User aborted prune. No changes were made.")
return nil
}
}
deleted, err := cli.db.BulkDeleteBouncers(bouncers)
if err != nil {
return fmt.Errorf("unable to prune bouncers: %w", err)
}
fmt.Fprintf(os.Stderr, "Successfully deleted %d bouncers\n", deleted)
return nil
}
func (cli *cliBouncers) newPruneCmd() *cobra.Command {
var (
duration time.Duration
force bool
)
const defaultDuration = 60 * time.Minute
cmd := &cobra.Command{
Use: "prune",
Short: "prune multiple bouncers from the database",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
Example: `cscli bouncers prune -d 45m
cscli bouncers prune -d 45m --force`,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.prune(duration, force)
},
}
flags := cmd.Flags()
flags.DurationVarP(&duration, "duration", "d", defaultDuration, "duration of time since last pull")
flags.BoolVar(&force, "force", false, "force prune without asking for confirmation")
return cmd
}

View file

@ -0,0 +1,29 @@
package main
import (
"io"
"time"
"github.com/aquasecurity/table"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
)
func getBouncersTable(out io.Writer, bouncers []*ent.Bouncer) {
t := newLightTable(out)
t.SetHeaders("Name", "IP Address", "Valid", "Last API pull", "Type", "Version", "Auth Type")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
for _, b := range bouncers {
revoked := emoji.CheckMark
if b.Revoked {
revoked = emoji.Prohibited
}
t.AddRow(b.Name, b.IPAddress, revoked, b.LastPull.Format(time.RFC3339), b.Type, b.Version, b.AuthType)
}
t.Render()
}

View file

@ -2,170 +2,221 @@ package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http/httputil"
"net/url"
"os"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
var CAPIURLPrefix string = "v2"
var CAPIBaseURL string = "https://api.crowdsec.net/"
const (
CAPIBaseURL = "https://api.crowdsec.net/"
CAPIURLPrefix = "v3"
)
func NewCapiCmd() *cobra.Command {
var cmdCapi = &cobra.Command{
Use: "capi [action]",
Short: "Manage interaction with Central API (CAPI)",
Args: cobra.MinimumNArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
type cliCapi struct {
cfg configGetter
}
func NewCLICapi(cfg configGetter) *cliCapi {
return &cliCapi{
cfg: cfg,
}
}
func (cli *cliCapi) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "capi [action]",
Short: "Manage interaction with Central API (CAPI)",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := require.LAPI(cfg); err != nil {
return err
}
if csConfig.API.Server.OnlineClient == nil {
log.Fatalf("no configuration for crowdsec API in '%s'", *csConfig.FilePath)
if err := require.CAPI(cfg); err != nil {
return err
}
return nil
},
}
var cmdCapiRegister = &cobra.Command{
Use: "register",
Short: "Register to Central API (CAPI)",
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var err error
cmd.AddCommand(cli.newRegisterCmd())
cmd.AddCommand(cli.newStatusCmd())
id, err := generateID()
if err != nil {
log.Fatalf("unable to generate machine id: %s", err)
}
password := strfmt.Password(generatePassword(passwordLength))
apiurl, err := url.Parse(CAPIBaseURL)
if err != nil {
log.Fatalf("unable to parse api url %s : %s", CAPIBaseURL, err)
}
_, err = apiclient.RegisterClient(&apiclient.Config{
MachineID: id,
Password: password,
UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
URL: apiurl,
VersionPrefix: CAPIURLPrefix,
}, nil)
if err != nil {
log.Fatalf("api client register ('%s'): %s", CAPIBaseURL, err)
}
log.Printf("Successfully registered to Central API (CAPI)")
var dumpFile string
if outputFile != "" {
dumpFile = outputFile
} else if csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
dumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath
} else {
dumpFile = ""
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: id,
Password: password.String(),
URL: CAPIBaseURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
log.Fatalf("unable to marshal api credentials: %s", err)
}
if dumpFile != "" {
err = ioutil.WriteFile(dumpFile, apiConfigDump, 0600)
if err != nil {
log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
}
log.Printf("Central API credentials dumped to '%s'", dumpFile)
} else {
fmt.Printf("%s\n", string(apiConfigDump))
}
log.Warningf(ReloadMessage())
},
}
cmdCapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
cmdCapi.AddCommand(cmdCapiRegister)
var cmdCapiStatus = &cobra.Command{
Use: "status",
Short: "Check status with the Central API (CAPI)",
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var err error
if csConfig.API.Server == nil {
log.Fatalln("There is no configuration on 'api_client:'")
}
if csConfig.API.Server.OnlineClient == nil {
log.Fatalf("Please provide credentials for the API in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)
}
if csConfig.API.Server.OnlineClient.Credentials == nil {
log.Fatalf("no credentials for crowdsec API in '%s'", csConfig.API.Server.OnlineClient.CredentialsFilePath)
}
password := strfmt.Password(csConfig.API.Server.OnlineClient.Credentials.Password)
apiurl, err := url.Parse(csConfig.API.Server.OnlineClient.Credentials.URL)
if err != nil {
log.Fatalf("parsing api url ('%s'): %s", csConfig.API.Server.OnlineClient.Credentials.URL, err)
}
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to load hub index : %s", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
if err != nil {
log.Fatalf("failed to get scenarios : %s", err.Error())
}
if len(scenarios) == 0 {
log.Fatalf("no scenarios installed, abort")
}
Client, err = apiclient.NewDefaultClient(apiurl, CAPIURLPrefix, fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()), nil)
if err != nil {
log.Fatalf("init default client: %s", err)
}
t := models.WatcherAuthRequest{
MachineID: &csConfig.API.Server.OnlineClient.Credentials.Login,
Password: &password,
Scenarios: scenarios,
}
log.Infof("Loaded credentials from %s", csConfig.API.Server.OnlineClient.CredentialsFilePath)
log.Infof("Trying to authenticate with username %s on %s", csConfig.API.Server.OnlineClient.Credentials.Login, apiurl)
resp, err := Client.Auth.AuthenticateWatcher(context.Background(), t)
if err != nil {
log.Fatalf("Failed to authenticate to Central API (CAPI) : %s", err)
} else {
log.Infof("You can successfully interact with Central API (CAPI)")
}
for k, v := range resp.Response.Header {
log.Debugf("[headers] %s : %s", k, v)
}
dump, _ := httputil.DumpResponse(resp.Response, true)
log.Debugf("Response: %s", string(dump))
},
}
cmdCapi.AddCommand(cmdCapiStatus)
return cmdCapi
return cmd
}
func (cli *cliCapi) register(capiUserPrefix string, outputFile string) error {
cfg := cli.cfg()
capiUser, err := generateID(capiUserPrefix)
if err != nil {
return fmt.Errorf("unable to generate machine id: %w", err)
}
password := strfmt.Password(generatePassword(passwordLength))
apiurl, err := url.Parse(types.CAPIBaseURL)
if err != nil {
return fmt.Errorf("unable to parse api url %s: %w", types.CAPIBaseURL, err)
}
_, err = apiclient.RegisterClient(&apiclient.Config{
MachineID: capiUser,
Password: password,
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiurl,
VersionPrefix: CAPIURLPrefix,
}, nil)
if err != nil {
return fmt.Errorf("api client register ('%s'): %w", types.CAPIBaseURL, err)
}
log.Infof("Successfully registered to Central API (CAPI)")
var dumpFile string
switch {
case outputFile != "":
dumpFile = outputFile
case cfg.API.Server.OnlineClient.CredentialsFilePath != "":
dumpFile = cfg.API.Server.OnlineClient.CredentialsFilePath
default:
dumpFile = ""
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: capiUser,
Password: password.String(),
URL: types.CAPIBaseURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
return fmt.Errorf("unable to marshal api credentials: %w", err)
}
if dumpFile != "" {
err = os.WriteFile(dumpFile, apiConfigDump, 0o600)
if err != nil {
return fmt.Errorf("write api credentials in '%s' failed: %w", dumpFile, err)
}
log.Infof("Central API credentials written to '%s'", dumpFile)
} else {
fmt.Println(string(apiConfigDump))
}
log.Warning(ReloadMessage())
return nil
}
func (cli *cliCapi) newRegisterCmd() *cobra.Command {
var (
capiUserPrefix string
outputFile string
)
cmd := &cobra.Command{
Use: "register",
Short: "Register to Central API (CAPI)",
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.register(capiUserPrefix, outputFile)
},
}
cmd.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
cmd.Flags().StringVar(&capiUserPrefix, "schmilblick", "", "set a schmilblick (use in tests only)")
if err := cmd.Flags().MarkHidden("schmilblick"); err != nil {
log.Fatalf("failed to hide flag: %s", err)
}
return cmd
}
func (cli *cliCapi) status() error {
cfg := cli.cfg()
if err := require.CAPIRegistered(cfg); err != nil {
return err
}
password := strfmt.Password(cfg.API.Server.OnlineClient.Credentials.Password)
apiurl, err := url.Parse(cfg.API.Server.OnlineClient.Credentials.URL)
if err != nil {
return fmt.Errorf("parsing api url ('%s'): %w", cfg.API.Server.OnlineClient.Credentials.URL, err)
}
hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}
scenarios, err := hub.GetInstalledNamesByType(cwhub.SCENARIOS)
if err != nil {
return fmt.Errorf("failed to get scenarios: %w", err)
}
if len(scenarios) == 0 {
return errors.New("no scenarios installed, abort")
}
Client, err = apiclient.NewDefaultClient(apiurl, CAPIURLPrefix, fmt.Sprintf("crowdsec/%s", version.String()), nil)
if err != nil {
return fmt.Errorf("init default client: %w", err)
}
t := models.WatcherAuthRequest{
MachineID: &cfg.API.Server.OnlineClient.Credentials.Login,
Password: &password,
Scenarios: scenarios,
}
log.Infof("Loaded credentials from %s", cfg.API.Server.OnlineClient.CredentialsFilePath)
log.Infof("Trying to authenticate with username %s on %s", cfg.API.Server.OnlineClient.Credentials.Login, apiurl)
_, _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
if err != nil {
return fmt.Errorf("failed to authenticate to Central API (CAPI): %w", err)
}
log.Info("You can successfully interact with Central API (CAPI)")
return nil
}
func (cli *cliCapi) newStatusCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Check status with the Central API (CAPI)",
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.status()
},
}
return cmd
}

View file

@ -1,143 +0,0 @@
package main
import (
"fmt"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func NewCollectionsCmd() *cobra.Command {
var cmdCollections = &cobra.Command{
Use: "collections [action]",
Short: "Manage collections from hub",
Long: `Install/Remove/Upgrade/Inspect collections from the CrowdSec Hub.`,
/*TBD fix help*/
Args: cobra.MinimumNArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if csConfig.Hub == nil {
return fmt.Errorf("you must configure cli before interacting with hub")
}
if err := setHubBranch(); err != nil {
return fmt.Errorf("error while setting hub branch: %s", err)
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
return nil
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if cmd.Name() == "inspect" || cmd.Name() == "list" {
return
}
log.Infof(ReloadMessage())
},
}
var cmdCollectionsInstall = &cobra.Command{
Use: "install collection",
Short: "Install given collection(s)",
Long: `Fetch and install given collection(s) from hub`,
Example: `cscli collections install crowdsec/xxx crowdsec/xyz`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, name := range args {
InstallItem(name, cwhub.COLLECTIONS, forceAction)
}
},
}
cmdCollectionsInstall.PersistentFlags().BoolVarP(&downloadOnly, "download-only", "d", false, "Only download packages, don't enable")
cmdCollectionsInstall.PersistentFlags().BoolVar(&forceAction, "force", false, "Force install : Overwrite tainted and outdated files")
cmdCollections.AddCommand(cmdCollectionsInstall)
var cmdCollectionsRemove = &cobra.Command{
Use: "remove collection",
Short: "Remove given collection(s)",
Long: `Remove given collection(s) from hub`,
Example: `cscli collections remove crowdsec/xxx crowdsec/xyz`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if all {
RemoveMany(cwhub.COLLECTIONS, "")
} else {
for _, name := range args {
if !forceAction {
item := cwhub.GetItem(cwhub.COLLECTIONS, name)
if len(item.BelongsToCollections) > 0 {
log.Warningf("%s belongs to other collections :\n%s\n", name, item.BelongsToCollections)
log.Printf("Run 'sudo cscli collections remove %s --force' if you want to force remove this sub collection\n", name)
continue
}
}
RemoveMany(cwhub.COLLECTIONS, name)
}
}
},
}
cmdCollectionsRemove.PersistentFlags().BoolVar(&purge, "purge", false, "Delete source file too")
cmdCollectionsRemove.PersistentFlags().BoolVar(&forceAction, "force", false, "Force remove : Remove tainted and outdated files")
cmdCollectionsRemove.PersistentFlags().BoolVar(&all, "all", false, "Delete all the collections")
cmdCollections.AddCommand(cmdCollectionsRemove)
var cmdCollectionsUpgrade = &cobra.Command{
Use: "upgrade collection",
Short: "Upgrade given collection(s)",
Long: `Fetch and upgrade given collection(s) from hub`,
Example: `cscli collections upgrade crowdsec/xxx crowdsec/xyz`,
Run: func(cmd *cobra.Command, args []string) {
if all {
UpgradeConfig(cwhub.COLLECTIONS, "", forceAction)
} else {
if len(args) == 0 {
log.Fatalf("no target collection to upgrade")
}
for _, name := range args {
UpgradeConfig(cwhub.COLLECTIONS, name, forceAction)
}
}
},
}
cmdCollectionsUpgrade.PersistentFlags().BoolVarP(&all, "all", "a", false, "Upgrade all the collections")
cmdCollectionsUpgrade.PersistentFlags().BoolVar(&forceAction, "force", false, "Force upgrade : Overwrite tainted and outdated files")
cmdCollections.AddCommand(cmdCollectionsUpgrade)
var cmdCollectionsInspect = &cobra.Command{
Use: "inspect collection",
Short: "Inspect given collection",
Long: `Inspect given collection`,
Example: `cscli collections inspect crowdsec/xxx crowdsec/xyz`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
for _, name := range args {
InspectItem(name, cwhub.COLLECTIONS)
}
},
}
cmdCollectionsInspect.PersistentFlags().StringVarP(&prometheusURL, "url", "u", "", "Prometheus url")
cmdCollections.AddCommand(cmdCollectionsInspect)
var cmdCollectionsList = &cobra.Command{
Use: "list collection [-a]",
Short: "List all collections or given one",
Long: `List all collections or given one`,
Example: `cscli collections list`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
ListItem(cwhub.COLLECTIONS, args)
},
}
cmdCollectionsList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List as well disabled items")
cmdCollections.AddCommand(cmdCollectionsList)
return cmdCollections
}

View file

@ -7,14 +7,13 @@ import (
)
func NewCompletionCmd() *cobra.Command {
var completionCmd = &cobra.Command{
Use: "completion [bash|zsh]",
completionCmd := &cobra.Command{
Use: "completion [bash|zsh|powershell|fish]",
Short: "Generate completion script",
Long: `To load completions:
### Bash:
` + "```shell" + `
$ source <(cscli completion bash)
# To load completions for each session, execute once:
@ -35,9 +34,10 @@ func NewCompletionCmd() *cobra.Command {
* Install bash-completion package
$ source /etc/profile
$ source <(cscli completion bash)
` + "```" + `
### Zsh:
### Zsh:
` + "```shell" + `
# If shell completion is not already enabled in your environment,
# you will need to enable it. You can execute the following once:
@ -48,21 +48,39 @@ func NewCompletionCmd() *cobra.Command {
$ cscli completion zsh > "${fpath[1]}/_cscli"
# You will need to start a new shell for this setup to take effect.
`,
### fish:
` + "```shell" + `
$ cscli completion fish | source
# To load completions for each session, execute once:
$ cscli completion fish > ~/.config/fish/completions/cscli.fish
` + "```" + `
### PowerShell:
` + "```powershell" + `
PS> cscli completion powershell | Out-String | Invoke-Expression
# To load completions for every new session, run:
PS> cscli completion powershell > cscli.ps1
# and source this file from your PowerShell profile.
` + "```",
DisableFlagsInUseLine: true,
ValidArgs: []string{"bash", "zsh"},
Args: cobra.ExactValidArgs(1),
DisableAutoGenTag: true,
ValidArgs: []string{"bash", "zsh", "powershell", "fish"},
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
cmd.Root().GenZshCompletion(os.Stdout)
/*case "fish":
case "powershell":
cmd.Root().GenPowerShellCompletion(os.Stdout)
case "fish":
cmd.Root().GenFishCompletion(os.Stdout, true)
*/
}
},
}
return completionCmd
}

View file

@ -1,436 +1,32 @@
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/types"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
)
type OldAPICfg struct {
MachineID string `json:"machine_id"`
Password string `json:"password"`
type cliConfig struct {
cfg configGetter
}
/* Backup crowdsec configurations to directory <dirPath> :
- Main config (config.yaml)
- Profiles config (profiles.yaml)
- Simulation config (simulation.yaml)
- Backup of API credentials (local API and online API)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
*/
func backupConfigToDirectory(dirPath string) error {
var err error
if dirPath == "" {
return fmt.Errorf("directory path can't be empty")
func NewCLIConfig(cfg configGetter) *cliConfig {
return &cliConfig{
cfg: cfg,
}
log.Infof("Starting configuration backup")
/*if parent directory doesn't exist, bail out. create final dir with Mkdir*/
parentDir := filepath.Dir(dirPath)
if _, err := os.Stat(parentDir); err != nil {
return errors.Wrapf(err, "while checking parent directory %s existence", parentDir)
}
if err = os.Mkdir(dirPath, 0700); err != nil {
return fmt.Errorf("error while creating %s : %s", dirPath, err)
}
if csConfig.ConfigPaths.SimulationFilePath != "" {
backupSimulation := fmt.Sprintf("%s/simulation.yaml", dirPath)
if err = types.CopyFile(csConfig.ConfigPaths.SimulationFilePath, backupSimulation); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", csConfig.ConfigPaths.SimulationFilePath, backupSimulation, err)
}
log.Infof("Saved simulation to %s", backupSimulation)
}
/*
- backup AcquisitionFilePath
- backup the other files of acquisition directory
*/
if csConfig.Crowdsec != nil && csConfig.Crowdsec.AcquisitionFilePath != "" {
backupAcquisition := fmt.Sprintf("%s/acquis.yaml", dirPath)
if err = types.CopyFile(csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", csConfig.Crowdsec.AcquisitionFilePath, backupAcquisition, err)
}
}
acquisBackupDir := dirPath + "/acquis/"
if err = os.Mkdir(acquisBackupDir, 0700); err != nil {
return fmt.Errorf("error while creating %s : %s", acquisBackupDir, err)
}
if csConfig.Crowdsec != nil && len(csConfig.Crowdsec.AcquisitionFiles) > 0 {
for _, acquisFile := range csConfig.Crowdsec.AcquisitionFiles {
/*if it was the default one, it was already backup'ed*/
if csConfig.Crowdsec.AcquisitionFilePath == acquisFile {
continue
}
targetFname, err := filepath.Abs(acquisBackupDir + filepath.Base(acquisFile))
if err != nil {
return errors.Wrapf(err, "while saving %s to %s", acquisFile, acquisBackupDir)
}
if err = types.CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", acquisFile, targetFname, err)
}
log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
}
}
if ConfigFilePath != "" {
backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
if err = types.CopyFile(ConfigFilePath, backupMain); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", ConfigFilePath, backupMain, err)
}
log.Infof("Saved default yaml to %s", backupMain)
}
if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
if err = types.CopyFile(csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds, err)
}
log.Infof("Saved online API credentials to %s", backupCAPICreds)
}
if csConfig.API != nil && csConfig.API.Client != nil && csConfig.API.Client.CredentialsFilePath != "" {
backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
if err = types.CopyFile(csConfig.API.Client.CredentialsFilePath, backupLAPICreds); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Client.CredentialsFilePath, backupLAPICreds, err)
}
log.Infof("Saved local API credentials to %s", backupLAPICreds)
}
if csConfig.API != nil && csConfig.API.Server != nil && csConfig.API.Server.ProfilesPath != "" {
backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
if err = types.CopyFile(csConfig.API.Server.ProfilesPath, backupProfiles); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", csConfig.API.Server.ProfilesPath, backupProfiles, err)
}
log.Infof("Saved profiles to %s", backupProfiles)
}
if err = BackupHub(dirPath); err != nil {
return fmt.Errorf("failed to backup hub config : %s", err)
}
return nil
}
/* Restore crowdsec configurations to directory <dirPath> :
- Main config (config.yaml)
- Profiles config (profiles.yaml)
- Simulation config (simulation.yaml)
- Backup of API credentials (local API and online API)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
*/
func restoreConfigFromDirectory(dirPath string) error {
var err error
if !restoreOldBackup {
backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
if _, err = os.Stat(backupMain); err == nil {
if csConfig.ConfigPaths != nil && csConfig.ConfigPaths.ConfigDir != "" {
if err = types.CopyFile(backupMain, fmt.Sprintf("%s/config.yaml", csConfig.ConfigPaths.ConfigDir)); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupMain, csConfig.ConfigPaths.ConfigDir, err)
}
}
}
// Now we have config.yaml, we should regenerate config struct to have rights paths etc
ConfigFilePath = fmt.Sprintf("%s/config.yaml", csConfig.ConfigPaths.ConfigDir)
initConfig()
backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
if _, err = os.Stat(backupCAPICreds); err == nil {
if err = types.CopyFile(backupCAPICreds, csConfig.API.Server.OnlineClient.CredentialsFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupCAPICreds, csConfig.API.Server.OnlineClient.CredentialsFilePath, err)
}
}
backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
if _, err = os.Stat(backupLAPICreds); err == nil {
if err = types.CopyFile(backupLAPICreds, csConfig.API.Client.CredentialsFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupLAPICreds, csConfig.API.Client.CredentialsFilePath, err)
}
}
backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
if _, err = os.Stat(backupProfiles); err == nil {
if err = types.CopyFile(backupProfiles, csConfig.API.Server.ProfilesPath); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupProfiles, csConfig.API.Server.ProfilesPath, err)
}
}
} else {
var oldAPICfg OldAPICfg
backupOldAPICfg := fmt.Sprintf("%s/api_creds.json", dirPath)
jsonFile, err := os.Open(backupOldAPICfg)
if err != nil {
log.Warningf("failed to open %s : %s", backupOldAPICfg, err)
} else {
byteValue, _ := ioutil.ReadAll(jsonFile)
err = json.Unmarshal(byteValue, &oldAPICfg)
if err != nil {
return fmt.Errorf("failed to load json file %s : %s", backupOldAPICfg, err)
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: oldAPICfg.MachineID,
Password: oldAPICfg.Password,
URL: CAPIBaseURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
return fmt.Errorf("unable to dump api credentials: %s", err)
}
apiConfigDumpFile := fmt.Sprintf("%s/online_api_credentials.yaml", csConfig.ConfigPaths.ConfigDir)
if csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
apiConfigDumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath
}
err = ioutil.WriteFile(apiConfigDumpFile, apiConfigDump, 0644)
if err != nil {
return fmt.Errorf("write api credentials in '%s' failed: %s", apiConfigDumpFile, err)
}
log.Infof("Saved API credentials to %s", apiConfigDumpFile)
}
func (cli *cliConfig) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "config [command]",
Short: "Allows to view current config",
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
}
backupSimulation := fmt.Sprintf("%s/simulation.yaml", dirPath)
if _, err = os.Stat(backupSimulation); err == nil {
if err = types.CopyFile(backupSimulation, csConfig.ConfigPaths.SimulationFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupSimulation, csConfig.ConfigPaths.SimulationFilePath, err)
}
}
cmd.AddCommand(cli.newShowCmd())
cmd.AddCommand(cli.newShowYAMLCmd())
cmd.AddCommand(cli.newBackupCmd())
cmd.AddCommand(cli.newRestoreCmd())
cmd.AddCommand(cli.newFeatureFlagsCmd())
/*if there is a acquisition dir, restore its content*/
if csConfig.Crowdsec.AcquisitionDirPath != "" {
if err = os.Mkdir(csConfig.Crowdsec.AcquisitionDirPath, 0700); err != nil {
return fmt.Errorf("error while creating %s : %s", csConfig.Crowdsec.AcquisitionDirPath, err)
}
}
//if there was a single one
backupAcquisition := fmt.Sprintf("%s/acquis.yaml", dirPath)
if _, err = os.Stat(backupAcquisition); err == nil {
log.Debugf("restoring backup'ed %s", backupAcquisition)
if err = types.CopyFile(backupAcquisition, csConfig.Crowdsec.AcquisitionFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", backupAcquisition, csConfig.Crowdsec.AcquisitionFilePath, err)
}
}
//if there is files in the acquis backup dir, restore them
acquisBackupDir := dirPath + "/acquis/*.yaml"
if acquisFiles, err := filepath.Glob(acquisBackupDir); err == nil {
for _, acquisFile := range acquisFiles {
targetFname, err := filepath.Abs(csConfig.Crowdsec.AcquisitionDirPath + "/" + filepath.Base(acquisFile))
if err != nil {
return errors.Wrapf(err, "while saving %s to %s", acquisFile, targetFname)
}
log.Debugf("restoring %s to %s", acquisFile, targetFname)
if err = types.CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", acquisFile, targetFname, err)
}
}
}
if csConfig.Crowdsec != nil && len(csConfig.Crowdsec.AcquisitionFiles) > 0 {
for _, acquisFile := range csConfig.Crowdsec.AcquisitionFiles {
log.Infof("backup filepath from dir -> %s", acquisFile)
/*if it was the default one, it was already backup'ed*/
if csConfig.Crowdsec.AcquisitionFilePath == acquisFile {
log.Infof("skip this one")
continue
}
targetFname, err := filepath.Abs(acquisBackupDir + filepath.Base(acquisFile))
if err != nil {
return errors.Wrapf(err, "while saving %s to %s", acquisFile, acquisBackupDir)
}
if err = types.CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s : %s", acquisFile, targetFname, err)
}
log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
}
}
if err = RestoreHub(dirPath); err != nil {
return fmt.Errorf("failed to restore hub config : %s", err)
}
return nil
}
func NewConfigCmd() *cobra.Command {
var cmdConfig = &cobra.Command{
Use: "config [command]",
Short: "Allows to view current config",
Args: cobra.ExactArgs(0),
}
var cmdConfigShow = &cobra.Command{
Use: "show",
Short: "Displays current config",
Long: `Displays the current cli configuration.`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
switch csConfig.Cscli.Output {
case "human":
fmt.Printf("Global:\n")
if csConfig.ConfigPaths != nil {
fmt.Printf(" - Configuration Folder : %s\n", csConfig.ConfigPaths.ConfigDir)
fmt.Printf(" - Data Folder : %s\n", csConfig.ConfigPaths.DataDir)
fmt.Printf(" - Hub Folder : %s\n", csConfig.ConfigPaths.HubDir)
fmt.Printf(" - Simulation File : %s\n", csConfig.ConfigPaths.SimulationFilePath)
}
if csConfig.Common != nil {
fmt.Printf(" - Log Folder : %s\n", csConfig.Common.LogDir)
fmt.Printf(" - Log level : %s\n", csConfig.Common.LogLevel)
fmt.Printf(" - Log Media : %s\n", csConfig.Common.LogMedia)
}
if csConfig.Crowdsec != nil {
fmt.Printf("Crowdsec:\n")
fmt.Printf(" - Acquisition File : %s\n", csConfig.Crowdsec.AcquisitionFilePath)
fmt.Printf(" - Parsers routines : %d\n", csConfig.Crowdsec.ParserRoutinesCount)
}
if csConfig.Cscli != nil {
fmt.Printf("cscli:\n")
fmt.Printf(" - Output : %s\n", csConfig.Cscli.Output)
fmt.Printf(" - Hub Branch : %s\n", csConfig.Cscli.HubBranch)
fmt.Printf(" - Hub Folder : %s\n", csConfig.Cscli.HubDir)
}
if csConfig.API != nil {
if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil {
fmt.Printf("API Client:\n")
fmt.Printf(" - URL : %s\n", csConfig.API.Client.Credentials.URL)
fmt.Printf(" - Login : %s\n", csConfig.API.Client.Credentials.Login)
fmt.Printf(" - Credentials File : %s\n", csConfig.API.Client.CredentialsFilePath)
}
if csConfig.API.Server != nil {
fmt.Printf("Local API Server:\n")
fmt.Printf(" - Listen URL : %s\n", csConfig.API.Server.ListenURI)
fmt.Printf(" - Profile File : %s\n", csConfig.API.Server.ProfilesPath)
if csConfig.API.Server.TLS != nil {
if csConfig.API.Server.TLS.CertFilePath != "" {
fmt.Printf(" - Cert File : %s\n", csConfig.API.Server.TLS.CertFilePath)
}
if csConfig.API.Server.TLS.KeyFilePath != "" {
fmt.Printf(" - Key File : %s\n", csConfig.API.Server.TLS.KeyFilePath)
}
}
if csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.Credentials != nil {
fmt.Printf("Central API:\n")
fmt.Printf(" - URL : %s\n", csConfig.API.Server.OnlineClient.Credentials.URL)
fmt.Printf(" - Login : %s\n", csConfig.API.Server.OnlineClient.Credentials.Login)
fmt.Printf(" - Credentials File : %s\n", csConfig.API.Server.OnlineClient.CredentialsFilePath)
}
}
}
if csConfig.DbConfig != nil {
fmt.Printf(" - Database:\n")
fmt.Printf(" - Type : %s\n", csConfig.DbConfig.Type)
switch csConfig.DbConfig.Type {
case "sqlite":
fmt.Printf(" - Path : %s\n", csConfig.DbConfig.DbPath)
case "mysql", "postgresql", "postgres":
fmt.Printf(" - Host : %s\n", csConfig.DbConfig.Host)
fmt.Printf(" - Port : %d\n", csConfig.DbConfig.Port)
fmt.Printf(" - User : %s\n", csConfig.DbConfig.User)
fmt.Printf(" - DB Name : %s\n", csConfig.DbConfig.DbName)
}
if csConfig.DbConfig.Flush != nil {
if *csConfig.DbConfig.Flush.MaxAge != "" {
fmt.Printf(" - Flush age : %s\n", *csConfig.DbConfig.Flush.MaxAge)
}
if *csConfig.DbConfig.Flush.MaxItems != 0 {
fmt.Printf(" - Flush size : %d\n", *csConfig.DbConfig.Flush.MaxItems)
}
}
}
case "json":
data, err := json.MarshalIndent(csConfig, "", " ")
if err != nil {
log.Fatalf("failed to marshal configuration: %s", err)
}
fmt.Printf("%s\n", string(data))
case "raw":
data, err := yaml.Marshal(csConfig)
if err != nil {
log.Fatalf("failed to marshal configuration: %s", err)
}
fmt.Printf("%s\n", string(data))
}
},
}
cmdConfig.AddCommand(cmdConfigShow)
var cmdConfigBackup = &cobra.Command{
Use: "backup <directory>",
Short: "Backup current config",
Long: `Backup the current crowdsec configuration including :
- Main config (config.yaml)
- Simulation config (simulation.yaml)
- Profiles config (profiles.yaml)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Backup of API credentials (local API and online API)`,
Example: `cscli config backup ./my-backup`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var err error
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err = cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
if err = backupConfigToDirectory(args[0]); err != nil {
log.Fatalf("Failed to backup configurations: %s", err)
}
},
}
cmdConfig.AddCommand(cmdConfigBackup)
var cmdConfigRestore = &cobra.Command{
Use: "restore <directory>",
Short: "Restore config in backup <directory>",
Long: `Restore the crowdsec configuration from specified backup <directory> including:
- Main config (config.yaml)
- Simulation config (simulation.yaml)
- Profiles config (profiles.yaml)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Backup of API credentials (local API and online API)`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var err error
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err = cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
if err := restoreConfigFromDirectory(args[0]); err != nil {
log.Fatalf("failed restoring configurations from %s : %s", args[0], err)
}
},
}
cmdConfigRestore.PersistentFlags().BoolVar(&restoreOldBackup, "old-backup", false, "To use when you are upgrading crowdsec v0.X to v1.X and you need to restore backup from v0.X")
cmdConfig.AddCommand(cmdConfigRestore)
return cmdConfig
return cmd
}

View file

@ -0,0 +1,240 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func (cli *cliConfig) backupHub(dirPath string) error {
hub, err := require.Hub(cli.cfg(), nil, nil)
if err != nil {
return err
}
for _, itemType := range cwhub.ItemTypes {
clog := log.WithFields(log.Fields{
"type": itemType,
})
itemMap := hub.GetItemMap(itemType)
if itemMap == nil {
clog.Infof("No %s to backup.", itemType)
continue
}
itemDirectory := fmt.Sprintf("%s/%s/", dirPath, itemType)
if err = os.MkdirAll(itemDirectory, os.ModePerm); err != nil {
return fmt.Errorf("error while creating %s: %w", itemDirectory, err)
}
upstreamParsers := []string{}
for k, v := range itemMap {
clog = clog.WithFields(log.Fields{
"file": v.Name,
})
if !v.State.Installed { // only backup installed ones
clog.Debugf("[%s]: not installed", k)
continue
}
// for the local/tainted ones, we back up the full file
if v.State.Tainted || v.State.IsLocal() || !v.State.UpToDate {
// we need to backup stages for parsers
if itemType == cwhub.PARSERS || itemType == cwhub.POSTOVERFLOWS {
fstagedir := fmt.Sprintf("%s%s", itemDirectory, v.Stage)
if err = os.MkdirAll(fstagedir, os.ModePerm); err != nil {
return fmt.Errorf("error while creating stage dir %s: %w", fstagedir, err)
}
}
clog.Debugf("[%s]: backing up file (tainted:%t local:%t up-to-date:%t)", k, v.State.Tainted, v.State.IsLocal(), v.State.UpToDate)
tfile := fmt.Sprintf("%s%s/%s", itemDirectory, v.Stage, v.FileName)
if err = CopyFile(v.State.LocalPath, tfile); err != nil {
return fmt.Errorf("failed copy %s %s to %s: %w", itemType, v.State.LocalPath, tfile, err)
}
clog.Infof("local/tainted saved %s to %s", v.State.LocalPath, tfile)
continue
}
clog.Debugf("[%s]: from hub, just backup name (up-to-date:%t)", k, v.State.UpToDate)
clog.Infof("saving, version:%s, up-to-date:%t", v.Version, v.State.UpToDate)
upstreamParsers = append(upstreamParsers, v.Name)
}
// write the upstream items
upstreamParsersFname := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itemType)
upstreamParsersContent, err := json.MarshalIndent(upstreamParsers, "", " ")
if err != nil {
return fmt.Errorf("failed marshaling upstream parsers: %w", err)
}
err = os.WriteFile(upstreamParsersFname, upstreamParsersContent, 0o644)
if err != nil {
return fmt.Errorf("unable to write to %s %s: %w", itemType, upstreamParsersFname, err)
}
clog.Infof("Wrote %d entries for %s to %s", len(upstreamParsers), itemType, upstreamParsersFname)
}
return nil
}
/*
Backup crowdsec configurations to directory <dirPath>:
- Main config (config.yaml)
- Profiles config (profiles.yaml)
- Simulation config (simulation.yaml)
- Backup of API credentials (local API and online API)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Acquisition files (acquis.yaml, acquis.d/*.yaml)
*/
func (cli *cliConfig) backup(dirPath string) error {
var err error
cfg := cli.cfg()
if dirPath == "" {
return errors.New("directory path can't be empty")
}
log.Infof("Starting configuration backup")
/*if parent directory doesn't exist, bail out. create final dir with Mkdir*/
parentDir := filepath.Dir(dirPath)
if _, err = os.Stat(parentDir); err != nil {
return fmt.Errorf("while checking parent directory %s existence: %w", parentDir, err)
}
if err = os.Mkdir(dirPath, 0o700); err != nil {
return fmt.Errorf("while creating %s: %w", dirPath, err)
}
if cfg.ConfigPaths.SimulationFilePath != "" {
backupSimulation := filepath.Join(dirPath, "simulation.yaml")
if err = CopyFile(cfg.ConfigPaths.SimulationFilePath, backupSimulation); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", cfg.ConfigPaths.SimulationFilePath, backupSimulation, err)
}
log.Infof("Saved simulation to %s", backupSimulation)
}
/*
- backup AcquisitionFilePath
- backup the other files of acquisition directory
*/
if cfg.Crowdsec != nil && cfg.Crowdsec.AcquisitionFilePath != "" {
backupAcquisition := filepath.Join(dirPath, "acquis.yaml")
if err = CopyFile(cfg.Crowdsec.AcquisitionFilePath, backupAcquisition); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", cfg.Crowdsec.AcquisitionFilePath, backupAcquisition, err)
}
}
acquisBackupDir := filepath.Join(dirPath, "acquis")
if err = os.Mkdir(acquisBackupDir, 0o700); err != nil {
return fmt.Errorf("error while creating %s: %w", acquisBackupDir, err)
}
if cfg.Crowdsec != nil && len(cfg.Crowdsec.AcquisitionFiles) > 0 {
for _, acquisFile := range cfg.Crowdsec.AcquisitionFiles {
/*if it was the default one, it was already backup'ed*/
if cfg.Crowdsec.AcquisitionFilePath == acquisFile {
continue
}
targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
if err != nil {
return fmt.Errorf("while saving %s to %s: %w", acquisFile, acquisBackupDir, err)
}
if err = CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", acquisFile, targetFname, err)
}
log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
}
}
if ConfigFilePath != "" {
backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
if err = CopyFile(ConfigFilePath, backupMain); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", ConfigFilePath, backupMain, err)
}
log.Infof("Saved default yaml to %s", backupMain)
}
if cfg.API != nil && cfg.API.Server != nil && cfg.API.Server.OnlineClient != nil && cfg.API.Server.OnlineClient.CredentialsFilePath != "" {
backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
if err = CopyFile(cfg.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", cfg.API.Server.OnlineClient.CredentialsFilePath, backupCAPICreds, err)
}
log.Infof("Saved online API credentials to %s", backupCAPICreds)
}
if cfg.API != nil && cfg.API.Client != nil && cfg.API.Client.CredentialsFilePath != "" {
backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
if err = CopyFile(cfg.API.Client.CredentialsFilePath, backupLAPICreds); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", cfg.API.Client.CredentialsFilePath, backupLAPICreds, err)
}
log.Infof("Saved local API credentials to %s", backupLAPICreds)
}
if cfg.API != nil && cfg.API.Server != nil && cfg.API.Server.ProfilesPath != "" {
backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
if err = CopyFile(cfg.API.Server.ProfilesPath, backupProfiles); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", cfg.API.Server.ProfilesPath, backupProfiles, err)
}
log.Infof("Saved profiles to %s", backupProfiles)
}
if err = cli.backupHub(dirPath); err != nil {
return fmt.Errorf("failed to backup hub config: %w", err)
}
return nil
}
func (cli *cliConfig) newBackupCmd() *cobra.Command {
cmd := &cobra.Command{
Use: `backup "directory"`,
Short: "Backup current config",
Long: `Backup the current crowdsec configuration including :
- Main config (config.yaml)
- Simulation config (simulation.yaml)
- Profiles config (profiles.yaml)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Backup of API credentials (local API and online API)`,
Example: `cscli config backup ./my-backup`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
if err := cli.backup(args[0]); err != nil {
return fmt.Errorf("failed to backup config: %w", err)
}
return nil
},
}
return cmd
}

View file

@ -0,0 +1,135 @@
package main
import (
"fmt"
"path/filepath"
"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
)
func (cli *cliConfig) featureFlags(showRetired bool) error {
green := color.New(color.FgGreen).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
yellow := color.New(color.FgYellow).SprintFunc()
magenta := color.New(color.FgMagenta).SprintFunc()
printFeature := func(feat fflag.Feature) {
nameDesc := feat.Name
if feat.Description != "" {
nameDesc += ": " + feat.Description
}
status := red("✗")
if feat.IsEnabled() {
status = green("✓")
}
fmt.Printf("%s %s", status, nameDesc)
if feat.State == fflag.DeprecatedState {
fmt.Printf("\n %s %s", yellow("DEPRECATED"), feat.DeprecationMsg)
}
if feat.State == fflag.RetiredState {
fmt.Printf("\n %s %s", magenta("RETIRED"), feat.DeprecationMsg)
}
fmt.Println()
}
feats := fflag.Crowdsec.GetAllFeatures()
enabled := []fflag.Feature{}
disabled := []fflag.Feature{}
retired := []fflag.Feature{}
for _, feat := range feats {
if feat.State == fflag.RetiredState {
retired = append(retired, feat)
continue
}
if feat.IsEnabled() {
enabled = append(enabled, feat)
continue
}
disabled = append(disabled, feat)
}
if len(enabled) > 0 {
fmt.Println(" --- Enabled features ---")
fmt.Println()
for _, feat := range enabled {
printFeature(feat)
}
fmt.Println()
}
if len(disabled) > 0 {
fmt.Println(" --- Disabled features ---")
fmt.Println()
for _, feat := range disabled {
printFeature(feat)
}
fmt.Println()
}
fmt.Println("To enable a feature you can: ")
fmt.Println(" - set the environment variable CROWDSEC_FEATURE_<uppercase_feature_name> to true")
featurePath, err := filepath.Abs(csconfig.GetFeatureFilePath(ConfigFilePath))
if err != nil {
// we already read the file, shouldn't happen
return err
}
fmt.Printf(" - add the line '- <feature_name>' to the file %s\n", featurePath)
fmt.Println()
if len(enabled) == 0 && len(disabled) == 0 {
fmt.Println("However, no feature flag is available in this release.")
fmt.Println()
}
if showRetired && len(retired) > 0 {
fmt.Println(" --- Retired features ---")
fmt.Println()
for _, feat := range retired {
printFeature(feat)
}
fmt.Println()
}
return nil
}
func (cli *cliConfig) newFeatureFlagsCmd() *cobra.Command {
var showRetired bool
cmd := &cobra.Command{
Use: "feature-flags",
Short: "Displays feature flag status",
Long: `Displays the supported feature flags and their current status.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.featureFlags(showRetired)
},
}
flags := cmd.Flags()
flags.BoolVar(&showRetired, "retired", false, "Show retired features")
return cmd
}

View file

@ -0,0 +1,273 @@
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func (cli *cliConfig) restoreHub(dirPath string) error {
cfg := cli.cfg()
hub, err := require.Hub(cfg, require.RemoteHub(cfg), nil)
if err != nil {
return err
}
for _, itype := range cwhub.ItemTypes {
itemDirectory := fmt.Sprintf("%s/%s/", dirPath, itype)
if _, err = os.Stat(itemDirectory); err != nil {
log.Infof("no %s in backup", itype)
continue
}
/*restore the upstream items*/
upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
file, err := os.ReadFile(upstreamListFN)
if err != nil {
return fmt.Errorf("error while opening %s: %w", upstreamListFN, err)
}
var upstreamList []string
err = json.Unmarshal(file, &upstreamList)
if err != nil {
return fmt.Errorf("error unmarshaling %s: %w", upstreamListFN, err)
}
for _, toinstall := range upstreamList {
item := hub.GetItem(itype, toinstall)
if item == nil {
log.Errorf("Item %s/%s not found in hub", itype, toinstall)
continue
}
if err = item.Install(false, false); err != nil {
log.Errorf("Error while installing %s : %s", toinstall, err)
}
}
/*restore the local and tainted items*/
files, err := os.ReadDir(itemDirectory)
if err != nil {
return fmt.Errorf("failed enumerating files of %s: %w", itemDirectory, err)
}
for _, file := range files {
// this was the upstream data
if file.Name() == fmt.Sprintf("upstream-%s.json", itype) {
continue
}
if itype == cwhub.PARSERS || itype == cwhub.POSTOVERFLOWS {
// we expect a stage here
if !file.IsDir() {
continue
}
stage := file.Name()
stagedir := fmt.Sprintf("%s/%s/%s/", cfg.ConfigPaths.ConfigDir, itype, stage)
log.Debugf("Found stage %s in %s, target directory : %s", stage, itype, stagedir)
if err = os.MkdirAll(stagedir, os.ModePerm); err != nil {
return fmt.Errorf("error while creating stage directory %s: %w", stagedir, err)
}
// find items
ifiles, err := os.ReadDir(itemDirectory + "/" + stage + "/")
if err != nil {
return fmt.Errorf("failed enumerating files of %s: %w", itemDirectory+"/"+stage, err)
}
// finally copy item
for _, tfile := range ifiles {
log.Infof("Going to restore local/tainted [%s]", tfile.Name())
sourceFile := fmt.Sprintf("%s/%s/%s", itemDirectory, stage, tfile.Name())
destinationFile := fmt.Sprintf("%s%s", stagedir, tfile.Name())
if err = CopyFile(sourceFile, destinationFile); err != nil {
return fmt.Errorf("failed copy %s %s to %s: %w", itype, sourceFile, destinationFile, err)
}
log.Infof("restored %s to %s", sourceFile, destinationFile)
}
} else {
log.Infof("Going to restore local/tainted [%s]", file.Name())
sourceFile := fmt.Sprintf("%s/%s", itemDirectory, file.Name())
destinationFile := fmt.Sprintf("%s/%s/%s", cfg.ConfigPaths.ConfigDir, itype, file.Name())
if err = CopyFile(sourceFile, destinationFile); err != nil {
return fmt.Errorf("failed copy %s %s to %s: %w", itype, sourceFile, destinationFile, err)
}
log.Infof("restored %s to %s", sourceFile, destinationFile)
}
}
}
return nil
}
/*
Restore crowdsec configurations to directory <dirPath>:
- Main config (config.yaml)
- Profiles config (profiles.yaml)
- Simulation config (simulation.yaml)
- Backup of API credentials (local API and online API)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Acquisition files (acquis.yaml, acquis.d/*.yaml)
*/
func (cli *cliConfig) restore(dirPath string) error {
var err error
cfg := cli.cfg()
backupMain := fmt.Sprintf("%s/config.yaml", dirPath)
if _, err = os.Stat(backupMain); err == nil {
if cfg.ConfigPaths != nil && cfg.ConfigPaths.ConfigDir != "" {
if err = CopyFile(backupMain, fmt.Sprintf("%s/config.yaml", cfg.ConfigPaths.ConfigDir)); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupMain, cfg.ConfigPaths.ConfigDir, err)
}
}
}
// Now we have config.yaml, we should regenerate config struct to have rights paths etc
ConfigFilePath = fmt.Sprintf("%s/config.yaml", cfg.ConfigPaths.ConfigDir)
log.Debug("Reloading configuration")
csConfig, _, err = loadConfigFor("config")
if err != nil {
return fmt.Errorf("failed to reload configuration: %w", err)
}
cfg = cli.cfg()
backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
if _, err = os.Stat(backupCAPICreds); err == nil {
if err = CopyFile(backupCAPICreds, cfg.API.Server.OnlineClient.CredentialsFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupCAPICreds, cfg.API.Server.OnlineClient.CredentialsFilePath, err)
}
}
backupLAPICreds := fmt.Sprintf("%s/local_api_credentials.yaml", dirPath)
if _, err = os.Stat(backupLAPICreds); err == nil {
if err = CopyFile(backupLAPICreds, cfg.API.Client.CredentialsFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupLAPICreds, cfg.API.Client.CredentialsFilePath, err)
}
}
backupProfiles := fmt.Sprintf("%s/profiles.yaml", dirPath)
if _, err = os.Stat(backupProfiles); err == nil {
if err = CopyFile(backupProfiles, cfg.API.Server.ProfilesPath); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupProfiles, cfg.API.Server.ProfilesPath, err)
}
}
backupSimulation := fmt.Sprintf("%s/simulation.yaml", dirPath)
if _, err = os.Stat(backupSimulation); err == nil {
if err = CopyFile(backupSimulation, cfg.ConfigPaths.SimulationFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupSimulation, cfg.ConfigPaths.SimulationFilePath, err)
}
}
/*if there is a acquisition dir, restore its content*/
if cfg.Crowdsec.AcquisitionDirPath != "" {
if err = os.MkdirAll(cfg.Crowdsec.AcquisitionDirPath, 0o700); err != nil {
return fmt.Errorf("error while creating %s: %w", cfg.Crowdsec.AcquisitionDirPath, err)
}
}
// if there was a single one
backupAcquisition := fmt.Sprintf("%s/acquis.yaml", dirPath)
if _, err = os.Stat(backupAcquisition); err == nil {
log.Debugf("restoring backup'ed %s", backupAcquisition)
if err = CopyFile(backupAcquisition, cfg.Crowdsec.AcquisitionFilePath); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", backupAcquisition, cfg.Crowdsec.AcquisitionFilePath, err)
}
}
// if there are files in the acquis backup dir, restore them
acquisBackupDir := filepath.Join(dirPath, "acquis", "*.yaml")
if acquisFiles, err := filepath.Glob(acquisBackupDir); err == nil {
for _, acquisFile := range acquisFiles {
targetFname, err := filepath.Abs(cfg.Crowdsec.AcquisitionDirPath + "/" + filepath.Base(acquisFile))
if err != nil {
return fmt.Errorf("while saving %s to %s: %w", acquisFile, targetFname, err)
}
log.Debugf("restoring %s to %s", acquisFile, targetFname)
if err = CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", acquisFile, targetFname, err)
}
}
}
if cfg.Crowdsec != nil && len(cfg.Crowdsec.AcquisitionFiles) > 0 {
for _, acquisFile := range cfg.Crowdsec.AcquisitionFiles {
log.Infof("backup filepath from dir -> %s", acquisFile)
// if it was the default one, it has already been backed up
if cfg.Crowdsec.AcquisitionFilePath == acquisFile {
log.Infof("skip this one")
continue
}
targetFname, err := filepath.Abs(filepath.Join(acquisBackupDir, filepath.Base(acquisFile)))
if err != nil {
return fmt.Errorf("while saving %s to %s: %w", acquisFile, acquisBackupDir, err)
}
if err = CopyFile(acquisFile, targetFname); err != nil {
return fmt.Errorf("failed copy %s to %s: %w", acquisFile, targetFname, err)
}
log.Infof("Saved acquis %s to %s", acquisFile, targetFname)
}
}
if err = cli.restoreHub(dirPath); err != nil {
return fmt.Errorf("failed to restore hub config: %w", err)
}
return nil
}
func (cli *cliConfig) newRestoreCmd() *cobra.Command {
cmd := &cobra.Command{
Use: `restore "directory"`,
Short: `Restore config in backup "directory"`,
Long: `Restore the crowdsec configuration from specified backup "directory" including:
- Main config (config.yaml)
- Simulation config (simulation.yaml)
- Profiles config (profiles.yaml)
- List of scenarios, parsers, postoverflows and collections that are up-to-date
- Tainted/local/out-of-date scenarios, parsers, postoverflows and collections
- Backup of API credentials (local API and online API)`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
dirPath := args[0]
if err := cli.restore(dirPath); err != nil {
return fmt.Errorf("failed to restore config from %s: %w", dirPath, err)
}
return nil
},
}
return cmd
}

View file

@ -0,0 +1,258 @@
package main
import (
"encoding/json"
"fmt"
"os"
"text/template"
"github.com/antonmedv/expr"
"github.com/sanity-io/litter"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
)
func (cli *cliConfig) showKey(key string) error {
cfg := cli.cfg()
type Env struct {
Config *csconfig.Config
}
opts := []expr.Option{}
opts = append(opts, exprhelpers.GetExprOptions(map[string]interface{}{})...)
opts = append(opts, expr.Env(Env{}))
program, err := expr.Compile(key, opts...)
if err != nil {
return err
}
output, err := expr.Run(program, Env{Config: cfg})
if err != nil {
return err
}
switch cfg.Cscli.Output {
case "human", "raw":
// Don't use litter for strings, it adds quotes
// that would break compatibility with previous versions
switch output.(type) {
case string:
fmt.Println(output)
default:
litter.Dump(output)
}
case "json":
data, err := json.MarshalIndent(output, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal configuration: %w", err)
}
fmt.Println(string(data))
}
return nil
}
func (cli *cliConfig) template() string {
return `Global:
{{- if .ConfigPaths }}
- Configuration Folder : {{.ConfigPaths.ConfigDir}}
- Data Folder : {{.ConfigPaths.DataDir}}
- Hub Folder : {{.ConfigPaths.HubDir}}
- Simulation File : {{.ConfigPaths.SimulationFilePath}}
{{- end }}
{{- if .Common }}
- Log Folder : {{.Common.LogDir}}
- Log level : {{.Common.LogLevel}}
- Log Media : {{.Common.LogMedia}}
{{- end }}
{{- if .Crowdsec }}
Crowdsec{{if and .Crowdsec.Enable (not (ValueBool .Crowdsec.Enable))}} (disabled){{end}}:
- Acquisition File : {{.Crowdsec.AcquisitionFilePath}}
- Parsers routines : {{.Crowdsec.ParserRoutinesCount}}
{{- if .Crowdsec.AcquisitionDirPath }}
- Acquisition Folder : {{.Crowdsec.AcquisitionDirPath}}
{{- end }}
{{- end }}
{{- if .Cscli }}
cscli:
- Output : {{.Cscli.Output}}
- Hub Branch : {{.Cscli.HubBranch}}
{{- end }}
{{- if .API }}
{{- if .API.Client }}
API Client:
{{- if .API.Client.Credentials }}
- URL : {{.API.Client.Credentials.URL}}
- Login : {{.API.Client.Credentials.Login}}
{{- end }}
- Credentials File : {{.API.Client.CredentialsFilePath}}
{{- end }}
{{- if .API.Server }}
Local API Server{{if and .API.Server.Enable (not (ValueBool .API.Server.Enable))}} (disabled){{end}}:
- Listen URL : {{.API.Server.ListenURI}}
- Listen Socket : {{.API.Server.ListenSocket}}
- Profile File : {{.API.Server.ProfilesPath}}
{{- if .API.Server.TLS }}
{{- if .API.Server.TLS.CertFilePath }}
- Cert File : {{.API.Server.TLS.CertFilePath}}
{{- end }}
{{- if .API.Server.TLS.KeyFilePath }}
- Key File : {{.API.Server.TLS.KeyFilePath}}
{{- end }}
{{- if .API.Server.TLS.CACertPath }}
- CA Cert : {{.API.Server.TLS.CACertPath}}
{{- end }}
{{- if .API.Server.TLS.CRLPath }}
- CRL : {{.API.Server.TLS.CRLPath}}
{{- end }}
{{- if .API.Server.TLS.CacheExpiration }}
- Cache Expiration : {{.API.Server.TLS.CacheExpiration}}
{{- end }}
{{- if .API.Server.TLS.ClientVerification }}
- Client Verification : {{.API.Server.TLS.ClientVerification}}
{{- end }}
{{- if .API.Server.TLS.AllowedAgentsOU }}
{{- range .API.Server.TLS.AllowedAgentsOU }}
- Allowed Agents OU : {{.}}
{{- end }}
{{- end }}
{{- if .API.Server.TLS.AllowedBouncersOU }}
{{- range .API.Server.TLS.AllowedBouncersOU }}
- Allowed Bouncers OU : {{.}}
{{- end }}
{{- end }}
{{- end }}
- Trusted IPs:
{{- range .API.Server.TrustedIPs }}
- {{.}}
{{- end }}
{{- if and .API.Server.OnlineClient .API.Server.OnlineClient.Credentials }}
Central API:
- URL : {{.API.Server.OnlineClient.Credentials.URL}}
- Login : {{.API.Server.OnlineClient.Credentials.Login}}
- Credentials File : {{.API.Server.OnlineClient.CredentialsFilePath}}
{{- end }}
{{- end }}
{{- end }}
{{- if .DbConfig }}
- Database:
- Type : {{.DbConfig.Type}}
{{- if eq .DbConfig.Type "sqlite" }}
- Path : {{.DbConfig.DbPath}}
{{- else}}
- Host : {{.DbConfig.Host}}
- Port : {{.DbConfig.Port}}
- User : {{.DbConfig.User}}
- DB Name : {{.DbConfig.DbName}}
{{- end }}
{{- if .DbConfig.MaxOpenConns }}
- Max Open Conns : {{.DbConfig.MaxOpenConns}}
{{- end }}
{{- if ne .DbConfig.DecisionBulkSize 0 }}
- Decision Bulk Size : {{.DbConfig.DecisionBulkSize}}
{{- end }}
{{- if .DbConfig.Flush }}
{{- if .DbConfig.Flush.MaxAge }}
- Flush age : {{.DbConfig.Flush.MaxAge}}
{{- end }}
{{- if .DbConfig.Flush.MaxItems }}
- Flush size : {{.DbConfig.Flush.MaxItems}}
{{- end }}
{{- end }}
{{- end }}
`
}
func (cli *cliConfig) show() error {
cfg := cli.cfg()
switch cfg.Cscli.Output {
case "human":
// The tests on .Enable look funny because the option has a true default which has
// not been set yet (we don't really load the LAPI) and go templates don't dereference
// pointers in boolean tests. Prefix notation is the cherry on top.
funcs := template.FuncMap{
// can't use generics here
"ValueBool": func(b *bool) bool { return b != nil && *b },
}
tmp, err := template.New("config").Funcs(funcs).Parse(cli.template())
if err != nil {
return err
}
err = tmp.Execute(os.Stdout, cfg)
if err != nil {
return err
}
case "json":
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal configuration: %w", err)
}
fmt.Println(string(data))
case "raw":
data, err := yaml.Marshal(cfg)
if err != nil {
return fmt.Errorf("failed to marshal configuration: %w", err)
}
fmt.Println(string(data))
}
return nil
}
func (cli *cliConfig) newShowCmd() *cobra.Command {
var key string
cmd := &cobra.Command{
Use: "show",
Short: "Displays current config",
Long: `Displays the current cli configuration.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
if err := cli.cfg().LoadAPIClient(); err != nil {
log.Errorf("failed to load API client configuration: %s", err)
// don't return, we can still show the configuration
}
if key != "" {
return cli.showKey(key)
}
return cli.show()
},
}
flags := cmd.Flags()
flags.StringVarP(&key, "key", "", "", "Display only this value (Config.API.Server.ListenURI)")
return cmd
}

View file

@ -0,0 +1,26 @@
package main
import (
"fmt"
"github.com/spf13/cobra"
)
func (cli *cliConfig) showYAML() error {
fmt.Println(mergedConfig)
return nil
}
func (cli *cliConfig) newShowYAMLCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "show-yaml",
Short: "Displays merged config.yaml + config.yaml.local",
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.showYAML()
},
}
return cmd
}

View file

@ -2,35 +2,78 @@ package main
import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"strconv"
"strings"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
func NewConsoleCmd() *cobra.Command {
var cmdConsole = &cobra.Command{
Use: "console [action]",
Short: "Manage interaction with Crowdsec console (https://app.crowdsec.net)",
Args: cobra.MinimumNArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
type cliConsole struct {
cfg configGetter
}
func NewCLIConsole(cfg configGetter) *cliConsole {
return &cliConsole{
cfg: cfg,
}
}
func (cli *cliConsole) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "console [action]",
Short: "Manage interaction with Crowdsec console (https://app.crowdsec.net)",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := require.LAPI(cfg); err != nil {
return err
}
if csConfig.API.Server.OnlineClient == nil {
log.Fatalf("no configuration for crowdsec API in '%s'", *csConfig.FilePath)
if err := require.CAPI(cfg); err != nil {
return err
}
if err := require.CAPIRegistered(cfg); err != nil {
return err
}
return nil
},
}
cmdEnroll := &cobra.Command{
cmd.AddCommand(cli.newEnrollCmd())
cmd.AddCommand(cli.newEnableCmd())
cmd.AddCommand(cli.newDisableCmd())
cmd.AddCommand(cli.newStatusCmd())
return cmd
}
func (cli *cliConsole) newEnrollCmd() *cobra.Command {
name := ""
overwrite := false
tags := []string{}
opts := []string{}
cmd := &cobra.Command{
Use: "enroll [enroll-key]",
Short: "Enroll this instance to https://app.crowdsec.net [requires local API]",
Long: `
@ -38,61 +81,361 @@ Enroll this instance to https://app.crowdsec.net
You can get your enrollment key by creating an account on https://app.crowdsec.net.
After running this command your will need to validate the enrollment in the webapp.`,
Example: "cscli console enroll YOUR-ENROLL-KEY",
Args: cobra.ExactArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
}
if csConfig.API.Server.OnlineClient == nil {
log.Fatalf("no configuration for crowdsec API in '%s'", *csConfig.FilePath)
}
if csConfig.API.Server.OnlineClient.Credentials == nil {
log.Fatal("You must configure CAPI with `cscli capi register` before enrolling your instance")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
password := strfmt.Password(csConfig.API.Server.OnlineClient.Credentials.Password)
apiURL, err := url.Parse(csConfig.API.Server.OnlineClient.Credentials.URL)
Example: fmt.Sprintf(`cscli console enroll YOUR-ENROLL-KEY
cscli console enroll --name [instance_name] YOUR-ENROLL-KEY
cscli console enroll --name [instance_name] --tags [tag_1] --tags [tag_2] YOUR-ENROLL-KEY
cscli console enroll --enable context,manual YOUR-ENROLL-KEY
valid options are : %s,all (see 'cscli console status' for details)`, strings.Join(csconfig.CONSOLE_CONFIGS, ",")),
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
cfg := cli.cfg()
password := strfmt.Password(cfg.API.Server.OnlineClient.Credentials.Password)
apiURL, err := url.Parse(cfg.API.Server.OnlineClient.Credentials.URL)
if err != nil {
log.Fatalf("Could not parse CAPI URL : %s", err)
return fmt.Errorf("could not parse CAPI URL: %w", err)
}
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to load hub index : %s", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
hub, err := require.Hub(cfg, nil, nil)
if err != nil {
log.Fatalf("failed to get scenarios : %s", err.Error())
return err
}
scenarios, err := hub.GetInstalledNamesByType(cwhub.SCENARIOS)
if err != nil {
return fmt.Errorf("failed to get installed scenarios: %w", err)
}
if len(scenarios) == 0 {
scenarios = make([]string, 0)
}
enableOpts := []string{csconfig.SEND_MANUAL_SCENARIOS, csconfig.SEND_TAINTED_SCENARIOS}
if len(opts) != 0 {
for _, opt := range opts {
valid := false
if opt == "all" {
enableOpts = csconfig.CONSOLE_CONFIGS
break
}
for _, availableOpt := range csconfig.CONSOLE_CONFIGS {
if opt == availableOpt {
valid = true
enable := true
for _, enabledOpt := range enableOpts {
if opt == enabledOpt {
enable = false
continue
}
}
if enable {
enableOpts = append(enableOpts, opt)
}
break
}
}
if !valid {
return fmt.Errorf("option %s doesn't exist", opt)
}
}
}
c, _ := apiclient.NewClient(&apiclient.Config{
MachineID: csConfig.API.Server.OnlineClient.Credentials.Login,
MachineID: cli.cfg().API.Server.OnlineClient.Credentials.Login,
Password: password,
Scenarios: scenarios,
UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiURL,
VersionPrefix: "v2",
VersionPrefix: "v3",
})
_, err = c.Auth.EnrollWatcher(context.Background(), args[0])
resp, err := c.Auth.EnrollWatcher(context.Background(), args[0], name, tags, overwrite)
if err != nil {
log.Fatalf("Could not enroll instance: %s", err)
return fmt.Errorf("could not enroll instance: %w", err)
}
log.Infof("Watcher successfully enrolled. Visit https://app.crowdsec.net to accept it.")
if resp.Response.StatusCode == 200 && !overwrite {
log.Warning("Instance already enrolled. You can use '--overwrite' to force enroll")
return nil
}
if err := cli.setConsoleOpts(enableOpts, true); err != nil {
return err
}
for _, opt := range enableOpts {
log.Infof("Enabled %s : %s", opt, csconfig.CONSOLE_CONFIGS_HELP[opt])
}
log.Info("Watcher successfully enrolled. Visit https://app.crowdsec.net to accept it.")
log.Info("Please restart crowdsec after accepting the enrollment.")
return nil
},
}
cmdConsole.AddCommand(cmdEnroll)
return cmdConsole
flags := cmd.Flags()
flags.StringVarP(&name, "name", "n", "", "Name to display in the console")
flags.BoolVarP(&overwrite, "overwrite", "", false, "Force enroll the instance")
flags.StringSliceVarP(&tags, "tags", "t", tags, "Tags to display in the console")
flags.StringSliceVarP(&opts, "enable", "e", opts, "Enable console options")
return cmd
}
func (cli *cliConsole) newEnableCmd() *cobra.Command {
var enableAll bool
cmd := &cobra.Command{
Use: "enable [option]",
Short: "Enable a console option",
Example: "sudo cscli console enable tainted",
Long: `
Enable given information push to the central API. Allows to empower the console`,
ValidArgs: csconfig.CONSOLE_CONFIGS,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
if enableAll {
if err := cli.setConsoleOpts(csconfig.CONSOLE_CONFIGS, true); err != nil {
return err
}
log.Infof("All features have been enabled successfully")
} else {
if len(args) == 0 {
return errors.New("you must specify at least one feature to enable")
}
if err := cli.setConsoleOpts(args, true); err != nil {
return err
}
log.Infof("%v have been enabled", args)
}
log.Infof(ReloadMessage())
return nil
},
}
cmd.Flags().BoolVarP(&enableAll, "all", "a", false, "Enable all console options")
return cmd
}
func (cli *cliConsole) newDisableCmd() *cobra.Command {
var disableAll bool
cmd := &cobra.Command{
Use: "disable [option]",
Short: "Disable a console option",
Example: "sudo cscli console disable tainted",
Long: `
Disable given information push to the central API.`,
ValidArgs: csconfig.CONSOLE_CONFIGS,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
if disableAll {
if err := cli.setConsoleOpts(csconfig.CONSOLE_CONFIGS, false); err != nil {
return err
}
log.Infof("All features have been disabled")
} else {
if err := cli.setConsoleOpts(args, false); err != nil {
return err
}
log.Infof("%v have been disabled", args)
}
log.Infof(ReloadMessage())
return nil
},
}
cmd.Flags().BoolVarP(&disableAll, "all", "a", false, "Disable all console options")
return cmd
}
func (cli *cliConsole) newStatusCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Shows status of the console options",
Example: `sudo cscli console status`,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
consoleCfg := cfg.API.Server.ConsoleConfig
switch cfg.Cscli.Output {
case "human":
cmdConsoleStatusTable(color.Output, *consoleCfg)
case "json":
out := map[string](*bool){
csconfig.SEND_MANUAL_SCENARIOS: consoleCfg.ShareManualDecisions,
csconfig.SEND_CUSTOM_SCENARIOS: consoleCfg.ShareCustomScenarios,
csconfig.SEND_TAINTED_SCENARIOS: consoleCfg.ShareTaintedScenarios,
csconfig.SEND_CONTEXT: consoleCfg.ShareContext,
csconfig.CONSOLE_MANAGEMENT: consoleCfg.ConsoleManagement,
}
data, err := json.MarshalIndent(out, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal configuration: %w", err)
}
fmt.Println(string(data))
case "raw":
csvwriter := csv.NewWriter(os.Stdout)
err := csvwriter.Write([]string{"option", "enabled"})
if err != nil {
return err
}
rows := [][]string{
{csconfig.SEND_MANUAL_SCENARIOS, strconv.FormatBool(*consoleCfg.ShareManualDecisions)},
{csconfig.SEND_CUSTOM_SCENARIOS, strconv.FormatBool(*consoleCfg.ShareCustomScenarios)},
{csconfig.SEND_TAINTED_SCENARIOS, strconv.FormatBool(*consoleCfg.ShareTaintedScenarios)},
{csconfig.SEND_CONTEXT, strconv.FormatBool(*consoleCfg.ShareContext)},
{csconfig.CONSOLE_MANAGEMENT, strconv.FormatBool(*consoleCfg.ConsoleManagement)},
}
for _, row := range rows {
err = csvwriter.Write(row)
if err != nil {
return err
}
}
csvwriter.Flush()
}
return nil
},
}
return cmd
}
func (cli *cliConsole) dumpConfig() error {
serverCfg := cli.cfg().API.Server
out, err := yaml.Marshal(serverCfg.ConsoleConfig)
if err != nil {
return fmt.Errorf("while marshaling ConsoleConfig (for %s): %w", serverCfg.ConsoleConfigPath, err)
}
if serverCfg.ConsoleConfigPath == "" {
serverCfg.ConsoleConfigPath = csconfig.DefaultConsoleConfigFilePath
log.Debugf("Empty console_path, defaulting to %s", serverCfg.ConsoleConfigPath)
}
if err := os.WriteFile(serverCfg.ConsoleConfigPath, out, 0o600); err != nil {
return fmt.Errorf("while dumping console config to %s: %w", serverCfg.ConsoleConfigPath, err)
}
return nil
}
func (cli *cliConsole) setConsoleOpts(args []string, wanted bool) error {
cfg := cli.cfg()
consoleCfg := cfg.API.Server.ConsoleConfig
for _, arg := range args {
switch arg {
case csconfig.CONSOLE_MANAGEMENT:
/*for each flag check if it's already set before setting it*/
if consoleCfg.ConsoleManagement != nil {
if *consoleCfg.ConsoleManagement == wanted {
log.Debugf("%s already set to %t", csconfig.CONSOLE_MANAGEMENT, wanted)
} else {
log.Infof("%s set to %t", csconfig.CONSOLE_MANAGEMENT, wanted)
*consoleCfg.ConsoleManagement = wanted
}
} else {
log.Infof("%s set to %t", csconfig.CONSOLE_MANAGEMENT, wanted)
consoleCfg.ConsoleManagement = ptr.Of(wanted)
}
if cfg.API.Server.OnlineClient.Credentials != nil {
changed := false
if wanted && cfg.API.Server.OnlineClient.Credentials.PapiURL == "" {
changed = true
cfg.API.Server.OnlineClient.Credentials.PapiURL = types.PAPIBaseURL
} else if !wanted && cfg.API.Server.OnlineClient.Credentials.PapiURL != "" {
changed = true
cfg.API.Server.OnlineClient.Credentials.PapiURL = ""
}
if changed {
fileContent, err := yaml.Marshal(cfg.API.Server.OnlineClient.Credentials)
if err != nil {
return fmt.Errorf("cannot marshal credentials: %w", err)
}
log.Infof("Updating credentials file: %s", cfg.API.Server.OnlineClient.CredentialsFilePath)
err = os.WriteFile(cfg.API.Server.OnlineClient.CredentialsFilePath, fileContent, 0o600)
if err != nil {
return fmt.Errorf("cannot write credentials file: %w", err)
}
}
}
case csconfig.SEND_CUSTOM_SCENARIOS:
/*for each flag check if it's already set before setting it*/
if consoleCfg.ShareCustomScenarios != nil {
if *consoleCfg.ShareCustomScenarios == wanted {
log.Debugf("%s already set to %t", csconfig.SEND_CUSTOM_SCENARIOS, wanted)
} else {
log.Infof("%s set to %t", csconfig.SEND_CUSTOM_SCENARIOS, wanted)
*consoleCfg.ShareCustomScenarios = wanted
}
} else {
log.Infof("%s set to %t", csconfig.SEND_CUSTOM_SCENARIOS, wanted)
consoleCfg.ShareCustomScenarios = ptr.Of(wanted)
}
case csconfig.SEND_TAINTED_SCENARIOS:
/*for each flag check if it's already set before setting it*/
if consoleCfg.ShareTaintedScenarios != nil {
if *consoleCfg.ShareTaintedScenarios == wanted {
log.Debugf("%s already set to %t", csconfig.SEND_TAINTED_SCENARIOS, wanted)
} else {
log.Infof("%s set to %t", csconfig.SEND_TAINTED_SCENARIOS, wanted)
*consoleCfg.ShareTaintedScenarios = wanted
}
} else {
log.Infof("%s set to %t", csconfig.SEND_TAINTED_SCENARIOS, wanted)
consoleCfg.ShareTaintedScenarios = ptr.Of(wanted)
}
case csconfig.SEND_MANUAL_SCENARIOS:
/*for each flag check if it's already set before setting it*/
if consoleCfg.ShareManualDecisions != nil {
if *consoleCfg.ShareManualDecisions == wanted {
log.Debugf("%s already set to %t", csconfig.SEND_MANUAL_SCENARIOS, wanted)
} else {
log.Infof("%s set to %t", csconfig.SEND_MANUAL_SCENARIOS, wanted)
*consoleCfg.ShareManualDecisions = wanted
}
} else {
log.Infof("%s set to %t", csconfig.SEND_MANUAL_SCENARIOS, wanted)
consoleCfg.ShareManualDecisions = ptr.Of(wanted)
}
case csconfig.SEND_CONTEXT:
/*for each flag check if it's already set before setting it*/
if consoleCfg.ShareContext != nil {
if *consoleCfg.ShareContext == wanted {
log.Debugf("%s already set to %t", csconfig.SEND_CONTEXT, wanted)
} else {
log.Infof("%s set to %t", csconfig.SEND_CONTEXT, wanted)
*consoleCfg.ShareContext = wanted
}
} else {
log.Infof("%s set to %t", csconfig.SEND_CONTEXT, wanted)
consoleCfg.ShareContext = ptr.Of(wanted)
}
default:
return fmt.Errorf("unknown flag %s", arg)
}
}
if err := cli.dumpConfig(); err != nil {
return fmt.Errorf("failed writing console config: %w", err)
}
return nil
}

View file

@ -0,0 +1,49 @@
package main
import (
"io"
"github.com/aquasecurity/table"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
)
func cmdConsoleStatusTable(out io.Writer, consoleCfg csconfig.ConsoleConfig) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Option Name", "Activated", "Description")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
for _, option := range csconfig.CONSOLE_CONFIGS {
activated := emoji.CrossMark
switch option {
case csconfig.SEND_CUSTOM_SCENARIOS:
if *consoleCfg.ShareCustomScenarios {
activated = emoji.CheckMarkButton
}
case csconfig.SEND_MANUAL_SCENARIOS:
if *consoleCfg.ShareManualDecisions {
activated = emoji.CheckMarkButton
}
case csconfig.SEND_TAINTED_SCENARIOS:
if *consoleCfg.ShareTaintedScenarios {
activated = emoji.CheckMarkButton
}
case csconfig.SEND_CONTEXT:
if *consoleCfg.ShareContext {
activated = emoji.CheckMarkButton
}
case csconfig.CONSOLE_MANAGEMENT:
if *consoleCfg.ConsoleManagement {
activated = emoji.CheckMarkButton
}
}
t.AddRow(option, activated, csconfig.CONSOLE_CONFIGS_HELP[option])
}
t.Render()
}

View file

@ -0,0 +1,82 @@
package main
import (
"fmt"
"io"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
)
/*help to copy the file, ioutil doesn't offer the feature*/
func copyFileContents(src, dst string) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return
}
defer func() {
cerr := out.Close()
if err == nil {
err = cerr
}
}()
if _, err = io.Copy(out, in); err != nil {
return
}
err = out.Sync()
return
}
/*copy the file, ioutile doesn't offer the feature*/
func CopyFile(sourceSymLink, destinationFile string) error {
sourceFile, err := filepath.EvalSymlinks(sourceSymLink)
if err != nil {
log.Infof("Not a symlink : %s", err)
sourceFile = sourceSymLink
}
sourceFileStat, err := os.Stat(sourceFile)
if err != nil {
return err
}
if !sourceFileStat.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories,
// symlinks, devices, etc.)
return fmt.Errorf("copyFile: non-regular source file %s (%q)", sourceFileStat.Name(), sourceFileStat.Mode().String())
}
destinationFileStat, err := os.Stat(destinationFile)
if err != nil {
if !os.IsNotExist(err) {
return err
}
} else {
if !(destinationFileStat.Mode().IsRegular()) {
return fmt.Errorf("copyFile: non-regular destination file %s (%q)", destinationFileStat.Name(), destinationFileStat.Mode().String())
}
if os.SameFile(sourceFileStat, destinationFileStat) {
return err
}
}
if err = os.Link(sourceFile, destinationFile); err != nil {
err = copyFileContents(sourceFile, destinationFile)
}
return err
}

View file

@ -1,30 +1,36 @@
//go:build linux
package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
)
var (
metabaseUser = "crowdsec@crowdsec.net"
metabasePassword string
metabaseDbPath string
metabaseDBPath string
metabaseConfigPath string
metabaseConfigFolder = "metabase/"
metabaseConfigFile = "metabase.yaml"
metabaseImage = "metabase/metabase"
metabaseImage = "metabase/metabase:v0.46.6.1"
/**/
metabaseListenAddress = "127.0.0.1"
metabaseListenPort = "3000"
@ -33,42 +39,52 @@ var (
forceYes bool
dockerGatewayIPAddr = "172.17.0.1"
/*informations needed to setup a random password on user's behalf*/
// information needed to set up a random password on user's behalf
)
func NewDashboardCmd() *cobra.Command {
/* ---- UPDATE COMMAND */
var cmdDashboard = &cobra.Command{
type cliDashboard struct {
cfg configGetter
}
func NewCLIDashboard(cfg configGetter) *cliDashboard {
return &cliDashboard{
cfg: cfg,
}
}
func (cli *cliDashboard) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "dashboard [command]",
Short: "Manage your metabase dashboard container [requires local API]",
Long: `Install/Start/Stop/Remove a metabase container exposing dashboard and metrics.
Note: This command requires database direct access, so is intended to be run on Local API/master.
`,
Args: cobra.ExactArgs(1),
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
Example: `
cscli dashboard setup
cscli dashboard start
cscli dashboard stop
cscli dashboard remove
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := require.LAPI(cfg); err != nil {
return err
}
if err := metabase.TestAvailability(); err != nil {
log.Fatalf("%s", err)
return err
}
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
}
metabaseConfigFolderPath := filepath.Join(csConfig.ConfigPaths.ConfigDir, metabaseConfigFolder)
metabaseConfigFolderPath := filepath.Join(cfg.ConfigPaths.ConfigDir, metabaseConfigFolder)
metabaseConfigPath = filepath.Join(metabaseConfigFolderPath, metabaseConfigFile)
if err := os.MkdirAll(metabaseConfigFolderPath, os.ModePerm); err != nil {
log.Fatalf(err.Error())
return err
}
if err := csConfig.LoadDBConfig(); err != nil {
log.Errorf("This command requires direct database access (must be run on the local API machine)")
log.Fatalf(err.Error())
if err := require.DB(cfg); err != nil {
return err
}
/*
@ -82,23 +98,37 @@ cscli dashboard remove
metabaseContainerID = oldContainerID
}
}
return nil
},
}
cmd.AddCommand(cli.newSetupCmd())
cmd.AddCommand(cli.newStartCmd())
cmd.AddCommand(cli.newStopCmd())
cmd.AddCommand(cli.newShowPasswordCmd())
cmd.AddCommand(cli.newRemoveCmd())
return cmd
}
func (cli *cliDashboard) newSetupCmd() *cobra.Command {
var force bool
var cmdDashSetup = &cobra.Command{
Use: "setup",
Short: "Setup a metabase container.",
Long: `Perform a metabase docker setup, download standard dashboards, create a fresh user and start the container`,
Args: cobra.ExactArgs(0),
cmd := &cobra.Command{
Use: "setup",
Short: "Setup a metabase container.",
Long: `Perform a metabase docker setup, download standard dashboards, create a fresh user and start the container`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
Example: `
cscli dashboard setup
cscli dashboard setup --listen 0.0.0.0
cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
`,
Run: func(cmd *cobra.Command, args []string) {
if metabaseDbPath == "" {
metabaseDbPath = csConfig.ConfigPaths.DataDir
RunE: func(_ *cobra.Command, _ []string) error {
if metabaseDBPath == "" {
metabaseDBPath = cli.cfg().ConfigPaths.DataDir
}
if metabasePassword == "" {
@ -108,54 +138,26 @@ cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
isValid = passwordIsValid(metabasePassword)
}
}
var answer bool
groupExist := false
dockerGroup, err := user.LookupGroup(crowdsecGroup)
if err == nil {
groupExist = true
if err := checkSystemMemory(&forceYes); err != nil {
return err
}
if !forceYes && !groupExist {
prompt := &survey.Confirm{
Message: fmt.Sprintf("For metabase docker to be able to access SQLite file we need to add a new group called '%s' to the system, is it ok for you ?", crowdsecGroup),
Default: true,
}
if err := survey.AskOne(prompt, &answer); err != nil {
log.Fatalf("unable to ask to force: %s", err)
}
warnIfNotLoopback(metabaseListenAddress)
if err := disclaimer(&forceYes); err != nil {
return err
}
if !answer && !forceYes && !groupExist {
log.Fatalf("unable to continue without creating '%s' group", crowdsecGroup)
}
if !groupExist {
groupAddCmd, err := exec.LookPath("groupadd")
if err != nil {
log.Fatalf("unable to find 'groupadd' command, can't continue")
}
groupAdd := &exec.Cmd{Path: groupAddCmd, Args: []string{groupAddCmd, crowdsecGroup}}
if err := groupAdd.Run(); err != nil {
log.Fatalf("unable to add group '%s': %s", dockerGroup, err)
}
dockerGroup, err = user.LookupGroup(crowdsecGroup)
if err != nil {
log.Fatalf("unable to lookup '%s' group: %+v", dockerGroup, err)
}
}
intID, err := strconv.Atoi(dockerGroup.Gid)
dockerGroup, err := checkGroups(&forceYes)
if err != nil {
log.Fatalf("unable to convert group ID to int: %s", err)
return err
}
if err := os.Chown(csConfig.DbConfig.DbPath, 0, intID); err != nil {
log.Fatalf("unable to chown sqlite db file '%s': %s", csConfig.DbConfig.DbPath, err)
if err = cli.chownDatabase(dockerGroup.Gid); err != nil {
return err
}
mb, err := metabase.SetupMetabase(csConfig.API.Server.DbConfig, metabaseListenAddress, metabaseListenPort, metabaseUser, metabasePassword, metabaseDbPath, dockerGroup.Gid, metabaseContainerID)
mb, err := metabase.SetupMetabase(cli.cfg().API.Server.DbConfig, metabaseListenAddress, metabaseListenPort, metabaseUser, metabasePassword, metabaseDBPath, dockerGroup.Gid, metabaseContainerID, metabaseImage)
if err != nil {
log.Fatalf(err.Error())
return err
}
if err := mb.DumpConfig(metabaseConfigPath); err != nil {
log.Fatalf(err.Error())
return err
}
log.Infof("Metabase is ready")
@ -163,120 +165,176 @@ cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
fmt.Printf("\tURL : '%s'\n", mb.Config.ListenURL)
fmt.Printf("\tusername : '%s'\n", mb.Config.Username)
fmt.Printf("\tpassword : '%s'\n", mb.Config.Password)
return nil
},
}
cmdDashSetup.Flags().BoolVarP(&force, "force", "f", false, "Force setup : override existing files.")
cmdDashSetup.Flags().StringVarP(&metabaseDbPath, "dir", "d", "", "Shared directory with metabase container.")
cmdDashSetup.Flags().StringVarP(&metabaseListenAddress, "listen", "l", metabaseListenAddress, "Listen address of container")
cmdDashSetup.Flags().StringVarP(&metabaseListenPort, "port", "p", metabaseListenPort, "Listen port of container")
cmdDashSetup.Flags().BoolVarP(&forceYes, "yes", "y", false, "force yes")
//cmdDashSetup.Flags().StringVarP(&metabaseUser, "user", "u", "crowdsec@crowdsec.net", "metabase user")
cmdDashSetup.Flags().StringVar(&metabasePassword, "password", "", "metabase password")
cmdDashboard.AddCommand(cmdDashSetup)
flags := cmd.Flags()
flags.BoolVarP(&force, "force", "f", false, "Force setup : override existing files")
flags.StringVarP(&metabaseDBPath, "dir", "d", "", "Shared directory with metabase container")
flags.StringVarP(&metabaseListenAddress, "listen", "l", metabaseListenAddress, "Listen address of container")
flags.StringVar(&metabaseImage, "metabase-image", metabaseImage, "Metabase image to use")
flags.StringVarP(&metabaseListenPort, "port", "p", metabaseListenPort, "Listen port of container")
flags.BoolVarP(&forceYes, "yes", "y", false, "force yes")
// flags.StringVarP(&metabaseUser, "user", "u", "crowdsec@crowdsec.net", "metabase user")
flags.StringVar(&metabasePassword, "password", "", "metabase password")
var cmdDashStart = &cobra.Command{
Use: "start",
Short: "Start the metabase container.",
Long: `Stats the metabase container using docker.`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
return cmd
}
func (cli *cliDashboard) newStartCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Start the metabase container.",
Long: `Stats the metabase container using docker.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
mb, err := metabase.NewMetabase(metabaseConfigPath, metabaseContainerID)
if err != nil {
log.Fatalf(err.Error())
return err
}
warnIfNotLoopback(mb.Config.ListenAddr)
if err := disclaimer(&forceYes); err != nil {
return err
}
if err := mb.Container.Start(); err != nil {
log.Fatalf("Failed to start metabase container : %s", err)
return fmt.Errorf("failed to start metabase container : %s", err)
}
log.Infof("Started metabase")
log.Infof("url : http://%s:%s", metabaseListenAddress, metabaseListenPort)
log.Infof("url : http://%s:%s", mb.Config.ListenAddr, mb.Config.ListenPort)
return nil
},
}
cmdDashboard.AddCommand(cmdDashStart)
var cmdDashStop = &cobra.Command{
Use: "stop",
Short: "Stops the metabase container.",
Long: `Stops the metabase container using docker.`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
cmd.Flags().BoolVarP(&forceYes, "yes", "y", false, "force yes")
return cmd
}
func (cli *cliDashboard) newStopCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "stop",
Short: "Stops the metabase container.",
Long: `Stops the metabase container using docker.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
if err := metabase.StopContainer(metabaseContainerID); err != nil {
log.Fatalf("unable to stop container '%s': %s", metabaseContainerID, err)
return fmt.Errorf("unable to stop container '%s': %s", metabaseContainerID, err)
}
return nil
},
}
cmdDashboard.AddCommand(cmdDashStop)
var cmdDashRemove = &cobra.Command{
Use: "remove",
Short: "removes the metabase container.",
Long: `removes the metabase container using docker.`,
Args: cobra.ExactArgs(0),
return cmd
}
func (cli *cliDashboard) newShowPasswordCmd() *cobra.Command {
cmd := &cobra.Command{Use: "show-password",
Short: "displays password of metabase.",
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
m := metabase.Metabase{}
if err := m.LoadConfig(metabaseConfigPath); err != nil {
return err
}
log.Printf("'%s'", m.Config.Password)
return nil
},
}
return cmd
}
func (cli *cliDashboard) newRemoveCmd() *cobra.Command {
var force bool
cmd := &cobra.Command{
Use: "remove",
Short: "removes the metabase container.",
Long: `removes the metabase container using docker.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
Example: `
cscli dashboard remove
cscli dashboard remove --force
`,
Run: func(cmd *cobra.Command, args []string) {
answer := true
RunE: func(_ *cobra.Command, _ []string) error {
if !forceYes {
var answer bool
prompt := &survey.Confirm{
Message: "Do you really want to remove crowdsec dashboard? (all your changes will be lost)",
Default: true,
}
if err := survey.AskOne(prompt, &answer); err != nil {
log.Fatalf("unable to ask to force: %s", err)
return fmt.Errorf("unable to ask to force: %s", err)
}
if !answer {
return fmt.Errorf("user stated no to continue")
}
}
if answer {
if metabase.IsContainerExist(metabaseContainerID) {
log.Debugf("Stopping container %s", metabaseContainerID)
if err := metabase.StopContainer(metabaseContainerID); err != nil {
log.Warningf("unable to stop container '%s': %s", metabaseContainerID, err)
if metabase.IsContainerExist(metabaseContainerID) {
log.Debugf("Stopping container %s", metabaseContainerID)
if err := metabase.StopContainer(metabaseContainerID); err != nil {
log.Warningf("unable to stop container '%s': %s", metabaseContainerID, err)
}
dockerGroup, err := user.LookupGroup(crowdsecGroup)
if err == nil { // if group exist, remove it
groupDelCmd, err := exec.LookPath("groupdel")
if err != nil {
return fmt.Errorf("unable to find 'groupdel' command, can't continue")
}
dockerGroup, err := user.LookupGroup(crowdsecGroup)
if err == nil { // if group exist, remove it
groupDelCmd, err := exec.LookPath("groupdel")
if err != nil {
log.Fatalf("unable to find 'groupdel' command, can't continue")
}
groupDel := &exec.Cmd{Path: groupDelCmd, Args: []string{groupDelCmd, crowdsecGroup}}
if err := groupDel.Run(); err != nil {
log.Errorf("unable to delete group '%s': %s", dockerGroup, err)
}
groupDel := &exec.Cmd{Path: groupDelCmd, Args: []string{groupDelCmd, crowdsecGroup}}
if err := groupDel.Run(); err != nil {
log.Warnf("unable to delete group '%s': %s", dockerGroup, err)
}
log.Debugf("Removing container %s", metabaseContainerID)
if err := metabase.RemoveContainer(metabaseContainerID); err != nil {
log.Warningf("unable to remove container '%s': %s", metabaseContainerID, err)
}
log.Infof("container %s stopped & removed", metabaseContainerID)
}
log.Debugf("Removing metabase db %s", csConfig.ConfigPaths.DataDir)
if err := metabase.RemoveDatabase(csConfig.ConfigPaths.DataDir); err != nil {
log.Warningf("failed to remove metabase internal db : %s", err)
log.Debugf("Removing container %s", metabaseContainerID)
if err := metabase.RemoveContainer(metabaseContainerID); err != nil {
log.Warnf("unable to remove container '%s': %s", metabaseContainerID, err)
}
if force {
if err := metabase.RemoveImageContainer(); err != nil {
if !strings.Contains(err.Error(), "No such image") {
log.Fatalf("removing docker image: %s", err)
}
log.Infof("container %s stopped & removed", metabaseContainerID)
}
log.Debugf("Removing metabase db %s", cli.cfg().ConfigPaths.DataDir)
if err := metabase.RemoveDatabase(cli.cfg().ConfigPaths.DataDir); err != nil {
log.Warnf("failed to remove metabase internal db : %s", err)
}
if force {
m := metabase.Metabase{}
if err := m.LoadConfig(metabaseConfigPath); err != nil {
return err
}
if err := metabase.RemoveImageContainer(m.Config.Image); err != nil {
if !strings.Contains(err.Error(), "No such image") {
return fmt.Errorf("removing docker image: %s", err)
}
}
}
return nil
},
}
cmdDashRemove.Flags().BoolVarP(&force, "force", "f", false, "Remove also the metabase image")
cmdDashRemove.Flags().BoolVarP(&forceYes, "yes", "y", false, "force yes")
cmdDashboard.AddCommand(cmdDashRemove)
return cmdDashboard
flags := cmd.Flags()
flags.BoolVarP(&force, "force", "f", false, "Remove also the metabase image")
flags.BoolVarP(&forceYes, "yes", "y", false, "force yes")
return cmd
}
func passwordIsValid(password string) bool {
hasDigit := false
for _, j := range password {
if unicode.IsDigit(j) {
hasDigit = true
break
}
}
@ -284,6 +342,134 @@ func passwordIsValid(password string) bool {
if !hasDigit || len(password) < 6 {
return false
}
return true
return true
}
func checkSystemMemory(forceYes *bool) error {
totMem := memory.TotalMemory()
if totMem >= uint64(math.Pow(2, 30)) {
return nil
}
if !*forceYes {
var answer bool
prompt := &survey.Confirm{
Message: "Metabase requires 1-2GB of RAM, your system is below this requirement continue ?",
Default: true,
}
if err := survey.AskOne(prompt, &answer); err != nil {
return fmt.Errorf("unable to ask about RAM check: %s", err)
}
if !answer {
return fmt.Errorf("user stated no to continue")
}
return nil
}
log.Warn("Metabase requires 1-2GB of RAM, your system is below this requirement")
return nil
}
func warnIfNotLoopback(addr string) {
if addr == "127.0.0.1" || addr == "::1" {
return
}
log.Warnf("You are potentially exposing your metabase port to the internet (addr: %s), please consider using a reverse proxy", addr)
}
func disclaimer(forceYes *bool) error {
if !*forceYes {
var answer bool
prompt := &survey.Confirm{
Message: "CrowdSec takes no responsibility for the security of your metabase instance. Do you accept these responsibilities ?",
Default: true,
}
if err := survey.AskOne(prompt, &answer); err != nil {
return fmt.Errorf("unable to ask to question: %s", err)
}
if !answer {
return fmt.Errorf("user stated no to responsibilities")
}
return nil
}
log.Warn("CrowdSec takes no responsibility for the security of your metabase instance. You used force yes, so you accept this disclaimer")
return nil
}
func checkGroups(forceYes *bool) (*user.Group, error) {
dockerGroup, err := user.LookupGroup(crowdsecGroup)
if err == nil {
return dockerGroup, nil
}
if !*forceYes {
var answer bool
prompt := &survey.Confirm{
Message: fmt.Sprintf("For metabase docker to be able to access SQLite file we need to add a new group called '%s' to the system, is it ok for you ?", crowdsecGroup),
Default: true,
}
if err := survey.AskOne(prompt, &answer); err != nil {
return dockerGroup, fmt.Errorf("unable to ask to question: %s", err)
}
if !answer {
return dockerGroup, fmt.Errorf("unable to continue without creating '%s' group", crowdsecGroup)
}
}
groupAddCmd, err := exec.LookPath("groupadd")
if err != nil {
return dockerGroup, fmt.Errorf("unable to find 'groupadd' command, can't continue")
}
groupAdd := &exec.Cmd{Path: groupAddCmd, Args: []string{groupAddCmd, crowdsecGroup}}
if err := groupAdd.Run(); err != nil {
return dockerGroup, fmt.Errorf("unable to add group '%s': %s", dockerGroup, err)
}
return user.LookupGroup(crowdsecGroup)
}
func (cli *cliDashboard) chownDatabase(gid string) error {
cfg := cli.cfg()
intID, err := strconv.Atoi(gid)
if err != nil {
return fmt.Errorf("unable to convert group ID to int: %s", err)
}
if stat, err := os.Stat(cfg.DbConfig.DbPath); !os.IsNotExist(err) {
info := stat.Sys()
if err := os.Chown(cfg.DbConfig.DbPath, int(info.(*syscall.Stat_t).Uid), intID); err != nil {
return fmt.Errorf("unable to chown sqlite db file '%s': %s", cfg.DbConfig.DbPath, err)
}
}
if cfg.DbConfig.Type == "sqlite" && cfg.DbConfig.UseWal != nil && *cfg.DbConfig.UseWal {
for _, ext := range []string{"-wal", "-shm"} {
file := cfg.DbConfig.DbPath + ext
if stat, err := os.Stat(file); !os.IsNotExist(err) {
info := stat.Sys()
if err := os.Chown(file, int(info.(*syscall.Stat_t).Uid), intID); err != nil {
return fmt.Errorf("unable to chown sqlite db file '%s': %s", file, err)
}
}
}
}
return nil
}

View file

@ -0,0 +1,32 @@
//go:build !linux
package main
import (
"runtime"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type cliDashboard struct{
cfg configGetter
}
func NewCLIDashboard(cfg configGetter) *cliDashboard {
return &cliDashboard{
cfg: cfg,
}
}
func (cli cliDashboard) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "dashboard",
DisableAutoGenTag: true,
Run: func(_ *cobra.Command, _ []string) {
log.Infof("Dashboard command is disabled on %s", runtime.GOOS)
},
}
return cmd
}

View file

@ -2,7 +2,9 @@ package main
import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
@ -10,189 +12,233 @@ import (
"strings"
"time"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/olekukonko/tablewriter"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
var Client *apiclient.ApiClient
func DecisionsToTable(alerts *models.GetAlertsResponse) error {
func (cli *cliDecisions) decisionsToTable(alerts *models.GetAlertsResponse, printMachine bool) error {
/*here we cheat a bit : to make it more readable for the user, we dedup some entries*/
var spamLimit map[string]bool = make(map[string]bool)
spamLimit := make(map[string]bool)
skipped := 0
/*process in reverse order to keep the latest item only*/
for aIdx := len(*alerts) - 1; aIdx >= 0; aIdx-- {
for aIdx := 0; aIdx < len(*alerts); aIdx++ {
alertItem := (*alerts)[aIdx]
newDecisions := make([]*models.Decision, 0)
for _, decisionItem := range alertItem.Decisions {
spamKey := fmt.Sprintf("%t:%s:%s:%s", *decisionItem.Simulated, *decisionItem.Type, *decisionItem.Scope, *decisionItem.Value)
if _, ok := spamLimit[spamKey]; ok {
skipped++
continue
}
spamLimit[spamKey] = true
newDecisions = append(newDecisions, decisionItem)
}
alertItem.Decisions = newDecisions
}
if csConfig.Cscli.Output == "raw" {
fmt.Printf("id,source,ip,reason,action,country,as,events_count,expiration,simulated,alert_id\n")
for _, alertItem := range *alerts {
for _, decisionItem := range alertItem.Decisions {
fmt.Printf("%v,%v,%v,%v,%v,%v,%v,%v,%v,%v,%v\n",
decisionItem.ID,
*decisionItem.Origin,
*decisionItem.Scope+":"+*decisionItem.Value,
*decisionItem.Scenario,
*decisionItem.Type,
alertItem.Source.Cn,
alertItem.Source.AsNumber+" "+alertItem.Source.AsName,
*alertItem.EventsCount,
*decisionItem.Duration,
*decisionItem.Simulated,
alertItem.ID)
}
switch cli.cfg().Cscli.Output {
case "raw":
csvwriter := csv.NewWriter(os.Stdout)
header := []string{"id", "source", "ip", "reason", "action", "country", "as", "events_count", "expiration", "simulated", "alert_id"}
if printMachine {
header = append(header, "machine")
}
} else if csConfig.Cscli.Output == "json" {
x, _ := json.MarshalIndent(alerts, "", " ")
fmt.Printf("%s", string(x))
} else if csConfig.Cscli.Output == "human" {
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"ID", "Source", "Scope:Value", "Reason", "Action", "Country", "AS", "Events", "expiration", "Alert ID"})
if len(*alerts) == 0 {
fmt.Println("No active decisions")
return nil
err := csvwriter.Write(header)
if err != nil {
return err
}
for _, alertItem := range *alerts {
for _, decisionItem := range alertItem.Decisions {
if *alertItem.Simulated {
*decisionItem.Type = fmt.Sprintf("(simul)%s", *decisionItem.Type)
}
table.Append([]string{
strconv.Itoa(int(decisionItem.ID)),
raw := []string{
fmt.Sprintf("%d", decisionItem.ID),
*decisionItem.Origin,
*decisionItem.Scope + ":" + *decisionItem.Value,
*decisionItem.Scenario,
*decisionItem.Type,
alertItem.Source.Cn,
alertItem.Source.AsNumber + " " + alertItem.Source.AsName,
strconv.Itoa(int(*alertItem.EventsCount)),
alertItem.Source.GetAsNumberName(),
fmt.Sprintf("%d", *alertItem.EventsCount),
*decisionItem.Duration,
strconv.Itoa(int(alertItem.ID)),
})
fmt.Sprintf("%t", *decisionItem.Simulated),
fmt.Sprintf("%d", alertItem.ID),
}
if printMachine {
raw = append(raw, alertItem.MachineID)
}
err := csvwriter.Write(raw)
if err != nil {
return err
}
}
}
table.Render() // Send output
csvwriter.Flush()
case "json":
if *alerts == nil {
// avoid returning "null" in `json"
// could be cleaner if we used slice of alerts directly
fmt.Println("[]")
return nil
}
x, _ := json.MarshalIndent(alerts, "", " ")
fmt.Printf("%s", string(x))
case "human":
if len(*alerts) == 0 {
fmt.Println("No active decisions")
return nil
}
cli.decisionsTable(color.Output, alerts, printMachine)
if skipped > 0 {
fmt.Printf("%d duplicated entries skipped\n", skipped)
}
}
return nil
}
func NewDecisionsCmd() *cobra.Command {
/* ---- DECISIONS COMMAND */
var cmdDecisions = &cobra.Command{
type cliDecisions struct {
cfg configGetter
}
func NewCLIDecisions(cfg configGetter) *cliDecisions {
return &cliDecisions{
cfg: cfg,
}
}
func (cli *cliDecisions) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "decisions [action]",
Short: "Manage decisions",
Long: `Add/List/Delete decisions from LAPI`,
Long: `Add/List/Delete/Import decisions from LAPI`,
Example: `cscli decisions [action] [filter]`,
Aliases: []string{"decision"},
/*TBD example*/
Args: cobra.MinimumNArgs(1),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if err := csConfig.LoadAPIClient(); err != nil {
log.Fatalf(err.Error())
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := cfg.LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %w", err)
}
if csConfig.API.Client == nil {
log.Fatalln("There is no configuration on 'api_client:'")
}
if csConfig.API.Client.Credentials == nil {
log.Fatalf("Please provide credentials for the API in '%s'", csConfig.API.Client.CredentialsFilePath)
}
password := strfmt.Password(csConfig.API.Client.Credentials.Password)
apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
password := strfmt.Password(cfg.API.Client.Credentials.Password)
apiurl, err := url.Parse(cfg.API.Client.Credentials.URL)
if err != nil {
log.Fatalf("parsing api url ('%s'): %s", csConfig.API.Client.Credentials.URL, err)
return fmt.Errorf("parsing api url %s: %w", cfg.API.Client.Credentials.URL, err)
}
Client, err = apiclient.NewClient(&apiclient.Config{
MachineID: csConfig.API.Client.Credentials.Login,
MachineID: cfg.API.Client.Credentials.Login,
Password: password,
UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiurl,
VersionPrefix: "v1",
})
if err != nil {
log.Fatalf("creating api client : %s", err)
return fmt.Errorf("creating api client: %w", err)
}
return nil
},
}
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newAddCmd())
cmd.AddCommand(cli.newDeleteCmd())
cmd.AddCommand(cli.newImportCmd())
return cmd
}
func (cli *cliDecisions) newListCmd() *cobra.Command {
var filter = apiclient.AlertsListOpts{
ValueEquals: new(string),
ScopeEquals: new(string),
ScenarioEquals: new(string),
OriginEquals: new(string),
IPEquals: new(string),
RangeEquals: new(string),
Since: new(string),
Until: new(string),
TypeEquals: new(string),
IncludeCAPI: new(bool),
Limit: new(int),
}
NoSimu := new(bool)
contained := new(bool)
var cmdDecisionsList = &cobra.Command{
var printMachine bool
cmd := &cobra.Command{
Use: "list [options]",
Short: "List decisions from LAPI",
Example: `cscli decisions list -i 1.2.3.4
cscli decisions list -r 1.2.3.0/24
cscli decisions list -s crowdsecurity/ssh-bf
cscli decisions list -t ban
cscli decisions list --origin lists --scenario list_name
`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
var err error
/*take care of shorthand options*/
if err := manageCliDecisionAlerts(filter.IPEquals, filter.RangeEquals, filter.ScopeEquals, filter.ValueEquals); err != nil {
log.Fatalf("%s", err)
if err = manageCliDecisionAlerts(filter.IPEquals, filter.RangeEquals, filter.ScopeEquals, filter.ValueEquals); err != nil {
return err
}
filter.ActiveDecisionEquals = new(bool)
*filter.ActiveDecisionEquals = true
if NoSimu != nil && *NoSimu {
filter.IncludeSimulated = new(bool)
}
/*nulify the empty entries to avoid bad filter*/
/* nullify the empty entries to avoid bad filter */
if *filter.Until == "" {
filter.Until = nil
} else {
} else if strings.HasSuffix(*filter.Until, "d") {
/*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
if strings.HasSuffix(*filter.Until, "d") {
realDuration := strings.TrimSuffix(*filter.Until, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
cmd.Help()
log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Until)
}
*filter.Until = fmt.Sprintf("%d%s", days*24, "h")
realDuration := strings.TrimSuffix(*filter.Until, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
printHelp(cmd)
return fmt.Errorf("can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Until)
}
*filter.Until = fmt.Sprintf("%d%s", days*24, "h")
}
if *filter.Since == "" {
filter.Since = nil
} else {
} else if strings.HasSuffix(*filter.Since, "d") {
/*time.ParseDuration support hours 'h' as bigger unit, let's make the user's life easier*/
if strings.HasSuffix(*filter.Since, "d") {
realDuration := strings.TrimSuffix(*filter.Since, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
cmd.Help()
log.Fatalf("Can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Until)
}
*filter.Since = fmt.Sprintf("%d%s", days*24, "h")
realDuration := strings.TrimSuffix(*filter.Since, "d")
days, err := strconv.Atoi(realDuration)
if err != nil {
printHelp(cmd)
return fmt.Errorf("can't parse duration %s, valid durations format: 1d, 4h, 4h15m", *filter.Since)
}
*filter.Since = fmt.Sprintf("%d%s", days*24, "h")
}
if *filter.IncludeCAPI {
*filter.Limit = 0
}
if *filter.TypeEquals == "" {
filter.TypeEquals = nil
@ -213,36 +259,47 @@ cscli decisions list -t ban
filter.RangeEquals = nil
}
if *filter.OriginEquals == "" {
filter.OriginEquals = nil
}
if contained != nil && *contained {
filter.Contains = new(bool)
}
alerts, _, err := Client.Alerts.List(context.Background(), filter)
if err != nil {
log.Fatalf("Unable to list decisions : %v", err.Error())
return fmt.Errorf("unable to retrieve decisions: %w", err)
}
err = DecisionsToTable(alerts)
err = cli.decisionsToTable(alerts, printMachine)
if err != nil {
log.Fatalf("unable to list decisions : %v", err.Error())
return fmt.Errorf("unable to print decisions: %w", err)
}
return nil
},
}
cmdDecisionsList.Flags().SortFlags = false
cmdDecisionsList.Flags().BoolVarP(filter.IncludeCAPI, "all", "a", false, "Include decisions from Central API")
cmdDecisionsList.Flags().StringVar(filter.Since, "since", "", "restrict to alerts newer than since (ie. 4h, 30d)")
cmdDecisionsList.Flags().StringVar(filter.Until, "until", "", "restrict to alerts older than until (ie. 4h, 30d)")
cmdDecisionsList.Flags().StringVarP(filter.TypeEquals, "type", "t", "", "restrict to this decision type (ie. ban,captcha)")
cmdDecisionsList.Flags().StringVar(filter.ScopeEquals, "scope", "", "restrict to this scope (ie. ip,range,session)")
cmdDecisionsList.Flags().StringVarP(filter.ValueEquals, "value", "v", "", "restrict to this value (ie. 1.2.3.4,userName)")
cmdDecisionsList.Flags().StringVarP(filter.ScenarioEquals, "scenario", "s", "", "restrict to this scenario (ie. crowdsecurity/ssh-bf)")
cmdDecisionsList.Flags().StringVarP(filter.IPEquals, "ip", "i", "", "restrict to alerts from this source ip (shorthand for --scope ip --value <IP>)")
cmdDecisionsList.Flags().StringVarP(filter.RangeEquals, "range", "r", "", "restrict to alerts from this source range (shorthand for --scope range --value <RANGE>)")
cmdDecisionsList.Flags().BoolVar(NoSimu, "no-simu", false, "exclude decisions in simulation mode")
cmdDecisionsList.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
cmd.Flags().SortFlags = false
cmd.Flags().BoolVarP(filter.IncludeCAPI, "all", "a", false, "Include decisions from Central API")
cmd.Flags().StringVar(filter.Since, "since", "", "restrict to alerts newer than since (ie. 4h, 30d)")
cmd.Flags().StringVar(filter.Until, "until", "", "restrict to alerts older than until (ie. 4h, 30d)")
cmd.Flags().StringVarP(filter.TypeEquals, "type", "t", "", "restrict to this decision type (ie. ban,captcha)")
cmd.Flags().StringVar(filter.ScopeEquals, "scope", "", "restrict to this scope (ie. ip,range,session)")
cmd.Flags().StringVar(filter.OriginEquals, "origin", "", fmt.Sprintf("the value to match for the specified origin (%s ...)", strings.Join(types.GetOrigins(), ",")))
cmd.Flags().StringVarP(filter.ValueEquals, "value", "v", "", "restrict to this value (ie. 1.2.3.4,userName)")
cmd.Flags().StringVarP(filter.ScenarioEquals, "scenario", "s", "", "restrict to this scenario (ie. crowdsecurity/ssh-bf)")
cmd.Flags().StringVarP(filter.IPEquals, "ip", "i", "", "restrict to alerts from this source ip (shorthand for --scope ip --value <IP>)")
cmd.Flags().StringVarP(filter.RangeEquals, "range", "r", "", "restrict to alerts from this source range (shorthand for --scope range --value <RANGE>)")
cmd.Flags().IntVarP(filter.Limit, "limit", "l", 100, "number of alerts to get (use 0 to remove the limit)")
cmd.Flags().BoolVar(NoSimu, "no-simu", false, "exclude decisions in simulation mode")
cmd.Flags().BoolVarP(&printMachine, "machine", "m", false, "print machines that triggered decisions")
cmd.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
cmdDecisions.AddCommand(cmdDecisionsList)
return cmd
}
func (cli *cliDecisions) newAddCmd() *cobra.Command {
var (
addIP string
addRange string
@ -253,7 +310,7 @@ cscli decisions list -t ban
addType string
)
var cmdDecisionsAdd = &cobra.Command{
cmd := &cobra.Command{
Use: "add [options]",
Short: "Add decision to LAPI",
Example: `cscli decisions add --ip 1.2.3.4
@ -262,24 +319,24 @@ cscli decisions add --ip 1.2.3.4 --duration 24h --type captcha
cscli decisions add --scope username --value foobar
`,
/*TBD : fix long and example*/
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, _ []string) error {
var err error
var ip, ipRange string
alerts := models.AddAlertsRequest{}
origin := "cscli"
origin := types.CscliOrigin
capacity := int32(0)
leakSpeed := "0"
eventsCount := int32(1)
empty := ""
simulated := false
startAt := time.Now().Format(time.RFC3339)
stopAt := time.Now().Format(time.RFC3339)
createdAt := time.Now().Format(time.RFC3339)
startAt := time.Now().UTC().Format(time.RFC3339)
stopAt := time.Now().UTC().Format(time.RFC3339)
createdAt := time.Now().UTC().Format(time.RFC3339)
/*take care of shorthand options*/
if err := manageCliDecisionAlerts(&addIP, &addRange, &addScope, &addValue); err != nil {
log.Fatalf("%s", err)
if err = manageCliDecisionAlerts(&addIP, &addRange, &addScope, &addValue); err != nil {
return err
}
if addIP != "" {
@ -289,15 +346,13 @@ cscli decisions add --scope username --value foobar
addValue = addRange
addScope = types.Range
} else if addValue == "" {
cmd.Help()
log.Errorf("Missing arguments, a value is required (--ip, --range or --scope and --value)")
return
printHelp(cmd)
return errors.New("missing arguments, a value is required (--ip, --range or --scope and --value)")
}
if addReason == "" {
addReason = fmt.Sprintf("manual '%s' from '%s'", addType, csConfig.API.Client.Credentials.Login)
addReason = fmt.Sprintf("manual '%s' from '%s'", addType, cli.cfg().API.Client.Credentials.Login)
}
decision := models.Decision{
Duration: &addDuration,
Scope: &addScope,
@ -317,12 +372,13 @@ cscli decisions add --scope username --value foobar
Scenario: &addReason,
ScenarioVersion: &empty,
Simulated: &simulated,
// setting empty scope/value broke plugins, and it didn't seem to be needed anymore w/ latest papi changes
Source: &models.Source{
AsName: empty,
AsNumber: empty,
Cn: empty,
IP: ip,
Range: ipRange,
IP: addValue,
Range: "",
Scope: &addScope,
Value: &addValue,
},
@ -334,76 +390,96 @@ cscli decisions add --scope username --value foobar
_, _, err = Client.Alerts.Add(context.Background(), alerts)
if err != nil {
log.Fatalf(err.Error())
return err
}
log.Info("Decision successfully added")
return nil
},
}
cmdDecisionsAdd.Flags().SortFlags = false
cmdDecisionsAdd.Flags().StringVarP(&addIP, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
cmdDecisionsAdd.Flags().StringVarP(&addRange, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
cmdDecisionsAdd.Flags().StringVarP(&addDuration, "duration", "d", "4h", "Decision duration (ie. 1h,4h,30m)")
cmdDecisionsAdd.Flags().StringVarP(&addValue, "value", "v", "", "The value (ie. --scope username --value foobar)")
cmdDecisionsAdd.Flags().StringVar(&addScope, "scope", types.Ip, "Decision scope (ie. ip,range,username)")
cmdDecisionsAdd.Flags().StringVarP(&addReason, "reason", "R", "", "Decision reason (ie. scenario-name)")
cmdDecisionsAdd.Flags().StringVarP(&addType, "type", "t", "ban", "Decision type (ie. ban,captcha,throttle)")
cmdDecisions.AddCommand(cmdDecisionsAdd)
cmd.Flags().SortFlags = false
cmd.Flags().StringVarP(&addIP, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
cmd.Flags().StringVarP(&addRange, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
cmd.Flags().StringVarP(&addDuration, "duration", "d", "4h", "Decision duration (ie. 1h,4h,30m)")
cmd.Flags().StringVarP(&addValue, "value", "v", "", "The value (ie. --scope username --value foobar)")
cmd.Flags().StringVar(&addScope, "scope", types.Ip, "Decision scope (ie. ip,range,username)")
cmd.Flags().StringVarP(&addReason, "reason", "R", "", "Decision reason (ie. scenario-name)")
cmd.Flags().StringVarP(&addType, "type", "t", "ban", "Decision type (ie. ban,captcha,throttle)")
var delFilter = apiclient.DecisionsDeleteOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
TypeEquals: new(string),
IPEquals: new(string),
RangeEquals: new(string),
return cmd
}
func (cli *cliDecisions) newDeleteCmd() *cobra.Command {
delFilter := apiclient.DecisionsDeleteOpts{
ScopeEquals: new(string),
ValueEquals: new(string),
TypeEquals: new(string),
IPEquals: new(string),
RangeEquals: new(string),
ScenarioEquals: new(string),
OriginEquals: new(string),
}
var delDecisionId string
var delDecisionID string
var delDecisionAll bool
var cmdDecisionsDelete = &cobra.Command{
Use: "delete [options]",
Short: "Delete decisions",
contained := new(bool)
cmd := &cobra.Command{
Use: "delete [options]",
Short: "Delete decisions",
DisableAutoGenTag: true,
Aliases: []string{"remove"},
Example: `cscli decisions delete -r 1.2.3.0/24
cscli decisions delete -i 1.2.3.4
cscli decisions delete -s crowdsecurity/ssh-bf
cscli decisions delete --id 42
cscli decisions delete --type captcha
cscli decisions delete --origin lists --scenario list_name
`,
/*TBD : refaire le Long/Example*/
PreRun: func(cmd *cobra.Command, args []string) {
PreRunE: func(cmd *cobra.Command, _ []string) error {
if delDecisionAll {
return
return nil
}
if *delFilter.ScopeEquals == "" && *delFilter.ValueEquals == "" &&
*delFilter.TypeEquals == "" && *delFilter.IPEquals == "" &&
*delFilter.RangeEquals == "" && delDecisionId == "" {
*delFilter.RangeEquals == "" && *delFilter.ScenarioEquals == "" &&
*delFilter.OriginEquals == "" && delDecisionID == "" {
cmd.Usage()
log.Fatalln("At least one filter or --all must be specified")
return errors.New("at least one filter or --all must be specified")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
RunE: func(_ *cobra.Command, _ []string) error {
var err error
var decisions *models.DeleteDecisionResponse
/*take care of shorthand options*/
if err := manageCliDecisionAlerts(delFilter.IPEquals, delFilter.RangeEquals, delFilter.ScopeEquals, delFilter.ValueEquals); err != nil {
log.Fatalf("%s", err)
if err = manageCliDecisionAlerts(delFilter.IPEquals, delFilter.RangeEquals, delFilter.ScopeEquals, delFilter.ValueEquals); err != nil {
return err
}
if *delFilter.ScopeEquals == "" {
delFilter.ScopeEquals = nil
}
if *delFilter.OriginEquals == "" {
delFilter.OriginEquals = nil
}
if *delFilter.ValueEquals == "" {
delFilter.ValueEquals = nil
}
if *delFilter.ScenarioEquals == "" {
delFilter.ScenarioEquals = nil
}
if *delFilter.TypeEquals == "" {
delFilter.TypeEquals = nil
}
if *delFilter.IPEquals == "" {
delFilter.IPEquals = nil
}
if *delFilter.RangeEquals == "" {
delFilter.RangeEquals = nil
}
@ -411,31 +487,37 @@ cscli decisions delete --type captcha
delFilter.Contains = new(bool)
}
if delDecisionId == "" {
if delDecisionID == "" {
decisions, _, err = Client.Decisions.Delete(context.Background(), delFilter)
if err != nil {
log.Fatalf("Unable to delete decisions : %v", err.Error())
return fmt.Errorf("unable to delete decisions: %v", err)
}
} else {
decisions, _, err = Client.Decisions.DeleteOne(context.Background(), delDecisionId)
if _, err = strconv.Atoi(delDecisionID); err != nil {
return fmt.Errorf("id '%s' is not an integer: %v", delDecisionID, err)
}
decisions, _, err = Client.Decisions.DeleteOne(context.Background(), delDecisionID)
if err != nil {
log.Fatalf("Unable to delete decision : %v", err.Error())
return fmt.Errorf("unable to delete decision: %v", err)
}
}
log.Infof("%s decision(s) deleted", decisions.NbDeleted)
return nil
},
}
cmdDecisionsDelete.Flags().SortFlags = false
cmdDecisionsDelete.Flags().StringVarP(delFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
cmdDecisionsDelete.Flags().StringVarP(delFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
cmdDecisionsDelete.Flags().StringVar(&delDecisionId, "id", "", "decision id")
cmdDecisionsDelete.Flags().StringVarP(delFilter.TypeEquals, "type", "t", "", "the decision type (ie. ban,captcha)")
cmdDecisionsDelete.Flags().StringVarP(delFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
cmdDecisionsDelete.Flags().BoolVar(&delDecisionAll, "all", false, "delete all decisions")
cmdDecisionsDelete.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
cmd.Flags().SortFlags = false
cmd.Flags().StringVarP(delFilter.IPEquals, "ip", "i", "", "Source ip (shorthand for --scope ip --value <IP>)")
cmd.Flags().StringVarP(delFilter.RangeEquals, "range", "r", "", "Range source ip (shorthand for --scope range --value <RANGE>)")
cmd.Flags().StringVarP(delFilter.TypeEquals, "type", "t", "", "the decision type (ie. ban,captcha)")
cmd.Flags().StringVarP(delFilter.ValueEquals, "value", "v", "", "the value to match for in the specified scope")
cmd.Flags().StringVarP(delFilter.ScenarioEquals, "scenario", "s", "", "the scenario name (ie. crowdsecurity/ssh-bf)")
cmd.Flags().StringVar(delFilter.OriginEquals, "origin", "", fmt.Sprintf("the value to match for the specified origin (%s ...)", strings.Join(types.GetOrigins(), ",")))
cmdDecisions.AddCommand(cmdDecisionsDelete)
cmd.Flags().StringVar(&delDecisionID, "id", "", "decision id")
cmd.Flags().BoolVar(&delDecisionAll, "all", false, "delete all decisions")
cmd.Flags().BoolVar(contained, "contained", false, "query decisions contained by range")
return cmdDecisions
return cmd
}

View file

@ -0,0 +1,280 @@
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/jszwec/csvutil"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/go-cs-lib/slicetools"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
// decisionRaw is only used to unmarshall json/csv decisions
type decisionRaw struct {
Duration string `csv:"duration,omitempty" json:"duration,omitempty"`
Scenario string `csv:"reason,omitempty" json:"reason,omitempty"`
Scope string `csv:"scope,omitempty" json:"scope,omitempty"`
Type string `csv:"type,omitempty" json:"type,omitempty"`
Value string `csv:"value" json:"value"`
}
func parseDecisionList(content []byte, format string) ([]decisionRaw, error) {
ret := []decisionRaw{}
switch format {
case "values":
log.Infof("Parsing values")
scanner := bufio.NewScanner(bytes.NewReader(content))
for scanner.Scan() {
value := strings.TrimSpace(scanner.Text())
ret = append(ret, decisionRaw{Value: value})
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("unable to parse values: '%s'", err)
}
case "json":
log.Infof("Parsing json")
if err := json.Unmarshal(content, &ret); err != nil {
return nil, err
}
case "csv":
log.Infof("Parsing csv")
if err := csvutil.Unmarshal(content, &ret); err != nil {
return nil, fmt.Errorf("unable to parse csv: '%s'", err)
}
default:
return nil, fmt.Errorf("invalid format '%s', expected one of 'json', 'csv', 'values'", format)
}
return ret, nil
}
func (cli *cliDecisions) runImport(cmd *cobra.Command, args []string) error {
flags := cmd.Flags()
input, err := flags.GetString("input")
if err != nil {
return err
}
defaultDuration, err := flags.GetString("duration")
if err != nil {
return err
}
if defaultDuration == "" {
return errors.New("--duration cannot be empty")
}
defaultScope, err := flags.GetString("scope")
if err != nil {
return err
}
if defaultScope == "" {
return errors.New("--scope cannot be empty")
}
defaultReason, err := flags.GetString("reason")
if err != nil {
return err
}
if defaultReason == "" {
return errors.New("--reason cannot be empty")
}
defaultType, err := flags.GetString("type")
if err != nil {
return err
}
if defaultType == "" {
return errors.New("--type cannot be empty")
}
batchSize, err := flags.GetInt("batch")
if err != nil {
return err
}
format, err := flags.GetString("format")
if err != nil {
return err
}
var (
content []byte
fin *os.File
)
// set format if the file has a json or csv extension
if format == "" {
if strings.HasSuffix(input, ".json") {
format = "json"
} else if strings.HasSuffix(input, ".csv") {
format = "csv"
}
}
if format == "" {
return errors.New("unable to guess format from file extension, please provide a format with --format flag")
}
if input == "-" {
fin = os.Stdin
input = "stdin"
} else {
fin, err = os.Open(input)
if err != nil {
return fmt.Errorf("unable to open %s: %s", input, err)
}
}
content, err = io.ReadAll(fin)
if err != nil {
return fmt.Errorf("unable to read from %s: %s", input, err)
}
decisionsListRaw, err := parseDecisionList(content, format)
if err != nil {
return err
}
decisions := make([]*models.Decision, len(decisionsListRaw))
for i, d := range decisionsListRaw {
if d.Value == "" {
return fmt.Errorf("item %d: missing 'value'", i)
}
if d.Duration == "" {
d.Duration = defaultDuration
log.Debugf("item %d: missing 'duration', using default '%s'", i, defaultDuration)
}
if d.Scenario == "" {
d.Scenario = defaultReason
log.Debugf("item %d: missing 'reason', using default '%s'", i, defaultReason)
}
if d.Type == "" {
d.Type = defaultType
log.Debugf("item %d: missing 'type', using default '%s'", i, defaultType)
}
if d.Scope == "" {
d.Scope = defaultScope
log.Debugf("item %d: missing 'scope', using default '%s'", i, defaultScope)
}
decisions[i] = &models.Decision{
Value: ptr.Of(d.Value),
Duration: ptr.Of(d.Duration),
Origin: ptr.Of(types.CscliImportOrigin),
Scenario: ptr.Of(d.Scenario),
Type: ptr.Of(d.Type),
Scope: ptr.Of(d.Scope),
Simulated: ptr.Of(false),
}
}
if len(decisions) > 1000 {
log.Infof("You are about to add %d decisions, this may take a while", len(decisions))
}
for _, chunk := range slicetools.Chunks(decisions, batchSize) {
log.Debugf("Processing chunk of %d decisions", len(chunk))
importAlert := models.Alert{
CreatedAt: time.Now().UTC().Format(time.RFC3339),
Scenario: ptr.Of(fmt.Sprintf("import %s: %d IPs", input, len(chunk))),
Message: ptr.Of(""),
Events: []*models.Event{},
Source: &models.Source{
Scope: ptr.Of(""),
Value: ptr.Of(""),
},
StartAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
StopAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
Capacity: ptr.Of(int32(0)),
Simulated: ptr.Of(false),
EventsCount: ptr.Of(int32(len(chunk))),
Leakspeed: ptr.Of(""),
ScenarioHash: ptr.Of(""),
ScenarioVersion: ptr.Of(""),
Decisions: chunk,
}
_, _, err = Client.Alerts.Add(context.Background(), models.AddAlertsRequest{&importAlert})
if err != nil {
return err
}
}
log.Infof("Imported %d decisions", len(decisions))
return nil
}
func (cli *cliDecisions) newImportCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "import [options]",
Short: "Import decisions from a file or pipe",
Long: "expected format:\n" +
"csv : any of duration,reason,scope,type,value, with a header line\n" +
"json :" + "`{" + `"duration" : "24h", "reason" : "my_scenario", "scope" : "ip", "type" : "ban", "value" : "x.y.z.z"` + "}`",
Args: cobra.NoArgs,
DisableAutoGenTag: true,
Example: `decisions.csv:
duration,scope,value
24h,ip,1.2.3.4
$ cscli decisions import -i decisions.csv
decisions.json:
[{"duration" : "4h", "scope" : "ip", "type" : "ban", "value" : "1.2.3.4"}]
The file format is detected from the extension, but can be forced with the --format option
which is required when reading from standard input.
Raw values, standard input:
$ echo "1.2.3.4" | cscli decisions import -i - --format values
`,
RunE: cli.runImport,
}
flags := cmd.Flags()
flags.SortFlags = false
flags.StringP("input", "i", "", "Input file")
flags.StringP("duration", "d", "4h", "Decision duration: 1h,4h,30m")
flags.String("scope", types.Ip, "Decision scope: ip,range,username")
flags.StringP("reason", "R", "manual", "Decision reason: <scenario-name>")
flags.StringP("type", "t", "ban", "Decision type: ban,captcha,throttle")
flags.Int("batch", 0, "Split import in batches of N decisions")
flags.String("format", "", "Input format: 'json', 'csv' or 'values' (each line is a value, no headers)")
cmd.MarkFlagRequired("input")
return cmd
}

View file

@ -0,0 +1,50 @@
package main
import (
"fmt"
"io"
"strconv"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
func (cli *cliDecisions) decisionsTable(out io.Writer, alerts *models.GetAlertsResponse, printMachine bool) {
t := newTable(out)
t.SetRowLines(false)
header := []string{"ID", "Source", "Scope:Value", "Reason", "Action", "Country", "AS", "Events", "expiration", "Alert ID"}
if printMachine {
header = append(header, "Machine")
}
t.SetHeaders(header...)
for _, alertItem := range *alerts {
for _, decisionItem := range alertItem.Decisions {
if *alertItem.Simulated {
*decisionItem.Type = fmt.Sprintf("(simul)%s", *decisionItem.Type)
}
row := []string{
strconv.Itoa(int(decisionItem.ID)),
*decisionItem.Origin,
*decisionItem.Scope + ":" + *decisionItem.Value,
*decisionItem.Scenario,
*decisionItem.Type,
alertItem.Source.Cn,
alertItem.Source.GetAsNumberName(),
strconv.Itoa(int(*alertItem.EventsCount)),
*decisionItem.Duration,
strconv.Itoa(int(alertItem.ID)),
}
if printMachine {
row = append(row, alertItem.MachineID)
}
t.AddRow(row...)
}
}
t.Render()
}

51
cmd/crowdsec-cli/doc.go Normal file
View file

@ -0,0 +1,51 @@
package main
import (
"fmt"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
)
type cliDoc struct{}
func NewCLIDoc() *cliDoc {
return &cliDoc{}
}
func (cli cliDoc) NewCommand(rootCmd *cobra.Command) *cobra.Command {
cmd := &cobra.Command{
Use: "doc",
Short: "Generate the documentation in `./doc/`. Directory must exist.",
Args: cobra.ExactArgs(0),
Hidden: true,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
if err := doc.GenMarkdownTreeCustom(rootCmd, "./doc/", cli.filePrepender, cli.linkHandler); err != nil {
return fmt.Errorf("failed to generate cobra doc: %s", err)
}
return nil
},
}
return cmd
}
func (cli cliDoc) filePrepender(filename string) string {
const header = `---
id: %s
title: %s
---
`
name := filepath.Base(filename)
base := strings.TrimSuffix(name, filepath.Ext(name))
return fmt.Sprintf(header, base, strings.ReplaceAll(base, "_", " "))
}
func (cli cliDoc) linkHandler(name string) string {
return fmt.Sprintf("/cscli/%s", name)
}

249
cmd/crowdsec-cli/explain.go Normal file
View file

@ -0,0 +1,249 @@
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/dumps"
"github.com/crowdsecurity/crowdsec/pkg/hubtest"
)
func getLineCountForFile(filepath string) (int, error) {
f, err := os.Open(filepath)
if err != nil {
return 0, err
}
defer f.Close()
lc := 0
fs := bufio.NewReader(f)
for {
input, err := fs.ReadBytes('\n')
if len(input) > 1 {
lc++
}
if err != nil && err == io.EOF {
break
}
}
return lc, nil
}
type cliExplain struct {
cfg configGetter
flags struct {
logFile string
dsn string
logLine string
logType string
details bool
skipOk bool
onlySuccessfulParsers bool
noClean bool
crowdsec string
labels string
}
}
func NewCLIExplain(cfg configGetter) *cliExplain {
return &cliExplain{
cfg: cfg,
}
}
func (cli *cliExplain) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "explain",
Short: "Explain log pipeline",
Long: `
Explain log pipeline
`,
Example: `
cscli explain --file ./myfile.log --type nginx
cscli explain --log "Sep 19 18:33:22 scw-d95986 sshd[24347]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=1.2.3.4" --type syslog
cscli explain --dsn "file://myfile.log" --type nginx
tail -n 5 myfile.log | cscli explain --type nginx -f -
`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.run()
},
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
fileInfo, _ := os.Stdin.Stat()
if cli.flags.logFile == "-" && ((fileInfo.Mode() & os.ModeCharDevice) == os.ModeCharDevice) {
return errors.New("the option -f - is intended to work with pipes")
}
return nil
},
}
flags := cmd.Flags()
flags.StringVarP(&cli.flags.logFile, "file", "f", "", "Log file to test")
flags.StringVarP(&cli.flags.dsn, "dsn", "d", "", "DSN to test")
flags.StringVarP(&cli.flags.logLine, "log", "l", "", "Log line to test")
flags.StringVarP(&cli.flags.logType, "type", "t", "", "Type of the acquisition to test")
flags.StringVar(&cli.flags.labels, "labels", "", "Additional labels to add to the acquisition format (key:value,key2:value2)")
flags.BoolVarP(&cli.flags.details, "verbose", "v", false, "Display individual changes")
flags.BoolVar(&cli.flags.skipOk, "failures", false, "Only show failed lines")
flags.BoolVar(&cli.flags.onlySuccessfulParsers, "only-successful-parsers", false, "Only show successful parsers")
flags.StringVar(&cli.flags.crowdsec, "crowdsec", "crowdsec", "Path to crowdsec")
flags.BoolVar(&cli.flags.noClean, "no-clean", false, "Don't clean runtime environment after tests")
cmd.MarkFlagRequired("type")
cmd.MarkFlagsOneRequired("log", "file", "dsn")
return cmd
}
func (cli *cliExplain) run() error {
logFile := cli.flags.logFile
logLine := cli.flags.logLine
logType := cli.flags.logType
dsn := cli.flags.dsn
labels := cli.flags.labels
crowdsec := cli.flags.crowdsec
opts := dumps.DumpOpts{
Details: cli.flags.details,
SkipOk: cli.flags.skipOk,
ShowNotOkParsers: !cli.flags.onlySuccessfulParsers,
}
var f *os.File
// using empty string fallback to /tmp
dir, err := os.MkdirTemp("", "cscli_explain")
if err != nil {
return fmt.Errorf("couldn't create a temporary directory to store cscli explain result: %w", err)
}
defer func() {
if cli.flags.noClean {
return
}
if _, err := os.Stat(dir); !os.IsNotExist(err) {
if err := os.RemoveAll(dir); err != nil {
log.Errorf("unable to delete temporary directory '%s': %s", dir, err)
}
}
}()
// we create a temporary log file if a log line/stdin has been provided
if logLine != "" || logFile == "-" {
tmpFile := filepath.Join(dir, "cscli_test_tmp.log")
f, err = os.Create(tmpFile)
if err != nil {
return err
}
if logLine != "" {
_, err = f.WriteString(logLine)
if err != nil {
return err
}
} else if logFile == "-" {
reader := bufio.NewReader(os.Stdin)
errCount := 0
for {
input, err := reader.ReadBytes('\n')
if err != nil && errors.Is(err, io.EOF) {
break
}
if len(input) > 1 {
_, err = f.Write(input)
}
if err != nil || len(input) <= 1 {
errCount++
}
}
if errCount > 0 {
log.Warnf("Failed to write %d lines to %s", errCount, tmpFile)
}
}
f.Close()
// this is the file that was going to be read by crowdsec anyway
logFile = tmpFile
}
if logFile != "" {
absolutePath, err := filepath.Abs(logFile)
if err != nil {
return fmt.Errorf("unable to get absolute path of '%s', exiting", logFile)
}
dsn = fmt.Sprintf("file://%s", absolutePath)
lineCount, err := getLineCountForFile(absolutePath)
if err != nil {
return err
}
log.Debugf("file %s has %d lines", absolutePath, lineCount)
if lineCount == 0 {
return fmt.Errorf("the log file is empty: %s", absolutePath)
}
if lineCount > 100 {
log.Warnf("%s contains %d lines. This may take a lot of resources.", absolutePath, lineCount)
}
}
if dsn == "" {
return errors.New("no acquisition (--file or --dsn) provided, can't run cscli test")
}
cmdArgs := []string{"-c", ConfigFilePath, "-type", logType, "-dsn", dsn, "-dump-data", dir, "-no-api"}
if labels != "" {
log.Debugf("adding labels %s", labels)
cmdArgs = append(cmdArgs, "-label", labels)
}
crowdsecCmd := exec.Command(crowdsec, cmdArgs...)
output, err := crowdsecCmd.CombinedOutput()
if err != nil {
fmt.Println(string(output))
return fmt.Errorf("fail to run crowdsec for test: %w", err)
}
parserDumpFile := filepath.Join(dir, hubtest.ParserResultFileName)
bucketStateDumpFile := filepath.Join(dir, hubtest.BucketPourResultFileName)
parserDump, err := dumps.LoadParserDump(parserDumpFile)
if err != nil {
return fmt.Errorf("unable to load parser dump result: %w", err)
}
bucketStateDump, err := dumps.LoadBucketPourDump(bucketStateDumpFile)
if err != nil {
return fmt.Errorf("unable to load bucket dump result: %w", err)
}
dumps.DumpTree(*parserDump, *bucketStateDump, opts)
return nil
}

29
cmd/crowdsec-cli/flag.go Normal file
View file

@ -0,0 +1,29 @@
package main
// Custom types for flag validation and conversion.
import (
"errors"
)
type MachinePassword string
func (p *MachinePassword) String() string {
return string(*p)
}
func (p *MachinePassword) Set(v string) error {
// a password can't be more than 72 characters
// due to bcrypt limitations
if len(v) > 72 {
return errors.New("password too long (max 72 characters)")
}
*p = MachinePassword(v)
return nil
}
func (p *MachinePassword) Type() string {
return "string"
}

View file

@ -1,142 +1,228 @@
package main
import (
"encoding/json"
"fmt"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewHubCmd() *cobra.Command {
/* ---- HUB COMMAND */
var cmdHub = &cobra.Command{
type cliHub struct{
cfg configGetter
}
func NewCLIHub(cfg configGetter) *cliHub {
return &cliHub{
cfg: cfg,
}
}
func (cli *cliHub) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "hub [action]",
Short: "Manage Hub",
Long: `
Hub management
Short: "Manage hub index",
Long: `Hub management
List/update parsers/scenarios/postoverflows/collections from [Crowdsec Hub](https://hub.crowdsec.net).
Hub is manage by cscli, to get latest hub files from [Crowdsec Hub](https://hub.crowdsec.net), you need to update.
`,
Example: `
cscli hub list # List all installed configurations
cscli hub update # Download list of available configurations from the hub
`,
Args: cobra.ExactArgs(0),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if csConfig.Cscli == nil {
return fmt.Errorf("you must configure cli before interacting with hub")
}
The Hub is managed by cscli, to get the latest hub files from [Crowdsec Hub](https://hub.crowdsec.net), you need to update.`,
Example: `cscli hub list
cscli hub update
cscli hub upgrade`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
}
return nil
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newUpdateCmd())
cmd.AddCommand(cli.newUpgradeCmd())
cmd.AddCommand(cli.newTypesCmd())
return cmd
}
func (cli *cliHub) list(all bool) error {
hub, err := require.Hub(cli.cfg(), nil, log.StandardLogger())
if err != nil {
return err
}
for _, v := range hub.Warnings {
log.Info(v)
}
for _, line := range hub.ItemStats() {
log.Info(line)
}
items := make(map[string][]*cwhub.Item)
for _, itemType := range cwhub.ItemTypes {
items[itemType], err = selectItems(hub, itemType, nil, !all)
if err != nil {
return err
}
}
err = listItems(color.Output, cwhub.ItemTypes, items, true)
if err != nil {
return err
}
return nil
}
func (cli *cliHub) newListCmd() *cobra.Command {
var all bool
cmd := &cobra.Command{
Use: "list [-a]",
Short: "List all installed configurations",
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list(all)
},
}
cmdHub.PersistentFlags().StringVarP(&cwhub.HubBranch, "branch", "b", "", "Use given branch from hub")
var cmdHubList = &cobra.Command{
Use: "list [-a]",
Short: "List installed configs",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
flags := cmd.Flags()
flags.BoolVarP(&all, "all", "a", false, "List disabled items as well")
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
//use LocalSync to get warnings about tainted / outdated items
_, warn := cwhub.LocalSync(csConfig.Hub)
for _, v := range warn {
log.Info(v)
}
cwhub.DisplaySummary()
log.Printf("PARSERS:")
ListItem(cwhub.PARSERS, args)
log.Printf("SCENARIOS:")
ListItem(cwhub.SCENARIOS, args)
log.Printf("COLLECTIONS:")
ListItem(cwhub.COLLECTIONS, args)
log.Printf("POSTOVERFLOWS:")
ListItem(cwhub.PARSERS_OVFLW, args)
},
return cmd
}
func (cli *cliHub) update() error {
local := cli.cfg().Hub
remote := require.RemoteHub(cli.cfg())
// don't use require.Hub because if there is no index file, it would fail
hub, err := cwhub.NewHub(local, remote, true, log.StandardLogger())
if err != nil {
return fmt.Errorf("failed to update hub: %w", err)
}
cmdHubList.PersistentFlags().BoolVarP(&all, "all", "a", false, "List as well disabled items")
cmdHub.AddCommand(cmdHubList)
var cmdHubUpdate = &cobra.Command{
for _, v := range hub.Warnings {
log.Info(v)
}
return nil
}
func (cli *cliHub) newUpdateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "update",
Short: "Fetch available configs from hub",
Short: "Download the latest index (catalog of available configurations)",
Long: `
Fetches the [.index.json](https://github.com/crowdsecurity/hub/blob/master/.index.json) file from hub, containing the list of available configs.
Fetches the .index.json file from the hub, containing the list of available configs.
`,
Args: cobra.ExactArgs(0),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if csConfig.Cscli == nil {
return fmt.Errorf("you must configure cli before interacting with hub")
}
if err := setHubBranch(); err != nil {
return fmt.Errorf("error while setting hub branch: %s", err)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.UpdateHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
}
//use LocalSync to get warnings about tainted / outdated items
_, warn := cwhub.LocalSync(csConfig.Hub)
for _, v := range warn {
log.Info(v)
}
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.update()
},
}
cmdHub.AddCommand(cmdHubUpdate)
var cmdHubUpgrade = &cobra.Command{
return cmd
}
func (cli *cliHub) upgrade(force bool) error {
hub, err := require.Hub(cli.cfg(), require.RemoteHub(cli.cfg()), log.StandardLogger())
if err != nil {
return err
}
for _, itemType := range cwhub.ItemTypes {
items, err := hub.GetInstalledItemsByType(itemType)
if err != nil {
return err
}
updated := 0
log.Infof("Upgrading %s", itemType)
for _, item := range items {
didUpdate, err := item.Upgrade(force)
if err != nil {
return err
}
if didUpdate {
updated++
}
}
log.Infof("Upgraded %d %s", updated, itemType)
}
return nil
}
func (cli *cliHub) newUpgradeCmd() *cobra.Command {
var force bool
cmd := &cobra.Command{
Use: "upgrade",
Short: "Upgrade all configs installed from hub",
Short: "Upgrade all configurations to their latest version",
Long: `
Upgrade all configs installed from Crowdsec Hub. Run 'sudo cscli hub update' if you want the latest versions available.
`,
Args: cobra.ExactArgs(0),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if csConfig.Cscli == nil {
return fmt.Errorf("you must configure cli before interacting with hub")
}
if err := setHubBranch(); err != nil {
return fmt.Errorf("error while setting hub branch: %s", err)
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to get Hub index : %v", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
log.Infof("Upgrading collections")
UpgradeConfig(cwhub.COLLECTIONS, "", forceAction)
log.Infof("Upgrading parsers")
UpgradeConfig(cwhub.PARSERS, "", forceAction)
log.Infof("Upgrading scenarios")
UpgradeConfig(cwhub.SCENARIOS, "", forceAction)
log.Infof("Upgrading postoverflows")
UpgradeConfig(cwhub.PARSERS_OVFLW, "", forceAction)
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.upgrade(force)
},
}
cmdHubUpgrade.PersistentFlags().BoolVar(&forceAction, "force", false, "Force upgrade : Overwrite tainted and outdated files")
cmdHub.AddCommand(cmdHubUpgrade)
return cmdHub
flags := cmd.Flags()
flags.BoolVar(&force, "force", false, "Force upgrade: overwrite tainted and outdated files")
return cmd
}
func (cli *cliHub) types() error {
switch cli.cfg().Cscli.Output {
case "human":
s, err := yaml.Marshal(cwhub.ItemTypes)
if err != nil {
return err
}
fmt.Print(string(s))
case "json":
jsonStr, err := json.Marshal(cwhub.ItemTypes)
if err != nil {
return err
}
fmt.Println(string(jsonStr))
case "raw":
for _, itemType := range cwhub.ItemTypes {
fmt.Println(itemType)
}
}
return nil
}
func (cli *cliHub) newTypesCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "types",
Short: "List supported item types",
Long: `
List the types of supported hub items.
`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.types()
},
}
return cmd
}

View file

@ -0,0 +1,123 @@
package main
import (
"fmt"
"os"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/crowdsec/pkg/appsec"
"github.com/crowdsecurity/crowdsec/pkg/appsec/appsec_rule"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLIAppsecConfig(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.APPSEC_CONFIGS,
singular: "appsec-config",
oneOrMore: "appsec-config(s)",
help: cliHelp{
example: `cscli appsec-configs list -a
cscli appsec-configs install crowdsecurity/vpatch
cscli appsec-configs inspect crowdsecurity/vpatch
cscli appsec-configs upgrade crowdsecurity/vpatch
cscli appsec-configs remove crowdsecurity/vpatch
`,
},
installHelp: cliHelp{
example: `cscli appsec-configs install crowdsecurity/vpatch`,
},
removeHelp: cliHelp{
example: `cscli appsec-configs remove crowdsecurity/vpatch`,
},
upgradeHelp: cliHelp{
example: `cscli appsec-configs upgrade crowdsecurity/vpatch`,
},
inspectHelp: cliHelp{
example: `cscli appsec-configs inspect crowdsecurity/vpatch`,
},
listHelp: cliHelp{
example: `cscli appsec-configs list
cscli appsec-configs list -a
cscli appsec-configs list crowdsecurity/vpatch`,
},
}
}
func NewCLIAppsecRule(cfg configGetter) *cliItem {
inspectDetail := func(item *cwhub.Item) error {
// Only show the converted rules in human mode
if csConfig.Cscli.Output != "human" {
return nil
}
appsecRule := appsec.AppsecCollectionConfig{}
yamlContent, err := os.ReadFile(item.State.LocalPath)
if err != nil {
return fmt.Errorf("unable to read file %s: %w", item.State.LocalPath, err)
}
if err := yaml.Unmarshal(yamlContent, &appsecRule); err != nil {
return fmt.Errorf("unable to unmarshal yaml file %s: %w", item.State.LocalPath, err)
}
for _, ruleType := range appsec_rule.SupportedTypes() {
fmt.Printf("\n%s format:\n", cases.Title(language.Und, cases.NoLower).String(ruleType))
for _, rule := range appsecRule.Rules {
convertedRule, _, err := rule.Convert(ruleType, appsecRule.Name)
if err != nil {
return fmt.Errorf("unable to convert rule %s: %w", rule.Name, err)
}
fmt.Println(convertedRule)
}
switch ruleType { //nolint:gocritic
case appsec_rule.ModsecurityRuleType:
for _, rule := range appsecRule.SecLangRules {
fmt.Println(rule)
}
}
}
return nil
}
return &cliItem{
cfg: cfg,
name: "appsec-rules",
singular: "appsec-rule",
oneOrMore: "appsec-rule(s)",
help: cliHelp{
example: `cscli appsec-rules list -a
cscli appsec-rules install crowdsecurity/crs
cscli appsec-rules inspect crowdsecurity/crs
cscli appsec-rules upgrade crowdsecurity/crs
cscli appsec-rules remove crowdsecurity/crs
`,
},
installHelp: cliHelp{
example: `cscli appsec-rules install crowdsecurity/crs`,
},
removeHelp: cliHelp{
example: `cscli appsec-rules remove crowdsecurity/crs`,
},
upgradeHelp: cliHelp{
example: `cscli appsec-rules upgrade crowdsecurity/crs`,
},
inspectHelp: cliHelp{
example: `cscli appsec-rules inspect crowdsecurity/crs`,
},
inspectDetail: inspectDetail,
listHelp: cliHelp{
example: `cscli appsec-rules list
cscli appsec-rules list -a
cscli appsec-rules list crowdsecurity/crs`,
},
}
}

View file

@ -0,0 +1,41 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLICollection(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.COLLECTIONS,
singular: "collection",
oneOrMore: "collection(s)",
help: cliHelp{
example: `cscli collections list -a
cscli collections install crowdsecurity/http-cve crowdsecurity/iptables
cscli collections inspect crowdsecurity/http-cve crowdsecurity/iptables
cscli collections upgrade crowdsecurity/http-cve crowdsecurity/iptables
cscli collections remove crowdsecurity/http-cve crowdsecurity/iptables
`,
},
installHelp: cliHelp{
example: `cscli collections install crowdsecurity/http-cve crowdsecurity/iptables`,
},
removeHelp: cliHelp{
example: `cscli collections remove crowdsecurity/http-cve crowdsecurity/iptables`,
},
upgradeHelp: cliHelp{
example: `cscli collections upgrade crowdsecurity/http-cve crowdsecurity/iptables`,
},
inspectHelp: cliHelp{
example: `cscli collections inspect crowdsecurity/http-cve crowdsecurity/iptables`,
},
listHelp: cliHelp{
example: `cscli collections list
cscli collections list -a
cscli collections list crowdsecurity/http-cve crowdsecurity/iptables
List only enabled collections unless "-a" or names are specified.`,
},
}
}

View file

@ -0,0 +1,41 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLIContext(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.CONTEXTS,
singular: "context",
oneOrMore: "context(s)",
help: cliHelp{
example: `cscli contexts list -a
cscli contexts install crowdsecurity/yyy crowdsecurity/zzz
cscli contexts inspect crowdsecurity/yyy crowdsecurity/zzz
cscli contexts upgrade crowdsecurity/yyy crowdsecurity/zzz
cscli contexts remove crowdsecurity/yyy crowdsecurity/zzz
`,
},
installHelp: cliHelp{
example: `cscli contexts install crowdsecurity/yyy crowdsecurity/zzz`,
},
removeHelp: cliHelp{
example: `cscli contexts remove crowdsecurity/yyy crowdsecurity/zzz`,
},
upgradeHelp: cliHelp{
example: `cscli contexts upgrade crowdsecurity/yyy crowdsecurity/zzz`,
},
inspectHelp: cliHelp{
example: `cscli contexts inspect crowdsecurity/yyy crowdsecurity/zzz`,
},
listHelp: cliHelp{
example: `cscli contexts list
cscli contexts list -a
cscli contexts list crowdsecurity/yyy crowdsecurity/zzz
List only enabled contexts unless "-a" or names are specified.`,
},
}
}

View file

@ -0,0 +1,41 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLIParser(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.PARSERS,
singular: "parser",
oneOrMore: "parser(s)",
help: cliHelp{
example: `cscli parsers list -a
cscli parsers install crowdsecurity/caddy-logs crowdsecurity/sshd-logs
cscli parsers inspect crowdsecurity/caddy-logs crowdsecurity/sshd-logs
cscli parsers upgrade crowdsecurity/caddy-logs crowdsecurity/sshd-logs
cscli parsers remove crowdsecurity/caddy-logs crowdsecurity/sshd-logs
`,
},
installHelp: cliHelp{
example: `cscli parsers install crowdsecurity/caddy-logs crowdsecurity/sshd-logs`,
},
removeHelp: cliHelp{
example: `cscli parsers remove crowdsecurity/caddy-logs crowdsecurity/sshd-logs`,
},
upgradeHelp: cliHelp{
example: `cscli parsers upgrade crowdsecurity/caddy-logs crowdsecurity/sshd-logs`,
},
inspectHelp: cliHelp{
example: `cscli parsers inspect crowdsecurity/httpd-logs crowdsecurity/sshd-logs`,
},
listHelp: cliHelp{
example: `cscli parsers list
cscli parsers list -a
cscli parsers list crowdsecurity/caddy-logs crowdsecurity/sshd-logs
List only enabled parsers unless "-a" or names are specified.`,
},
}
}

View file

@ -0,0 +1,41 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLIPostOverflow(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.POSTOVERFLOWS,
singular: "postoverflow",
oneOrMore: "postoverflow(s)",
help: cliHelp{
example: `cscli postoverflows list -a
cscli postoverflows install crowdsecurity/cdn-whitelist crowdsecurity/rdns
cscli postoverflows inspect crowdsecurity/cdn-whitelist crowdsecurity/rdns
cscli postoverflows upgrade crowdsecurity/cdn-whitelist crowdsecurity/rdns
cscli postoverflows remove crowdsecurity/cdn-whitelist crowdsecurity/rdns
`,
},
installHelp: cliHelp{
example: `cscli postoverflows install crowdsecurity/cdn-whitelist crowdsecurity/rdns`,
},
removeHelp: cliHelp{
example: `cscli postoverflows remove crowdsecurity/cdn-whitelist crowdsecurity/rdns`,
},
upgradeHelp: cliHelp{
example: `cscli postoverflows upgrade crowdsecurity/cdn-whitelist crowdsecurity/rdns`,
},
inspectHelp: cliHelp{
example: `cscli postoverflows inspect crowdsecurity/cdn-whitelist crowdsecurity/rdns`,
},
listHelp: cliHelp{
example: `cscli postoverflows list
cscli postoverflows list -a
cscli postoverflows list crowdsecurity/cdn-whitelist crowdsecurity/rdns
List only enabled postoverflows unless "-a" or names are specified.`,
},
}
}

View file

@ -0,0 +1,41 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func NewCLIScenario(cfg configGetter) *cliItem {
return &cliItem{
cfg: cfg,
name: cwhub.SCENARIOS,
singular: "scenario",
oneOrMore: "scenario(s)",
help: cliHelp{
example: `cscli scenarios list -a
cscli scenarios install crowdsecurity/ssh-bf crowdsecurity/http-probing
cscli scenarios inspect crowdsecurity/ssh-bf crowdsecurity/http-probing
cscli scenarios upgrade crowdsecurity/ssh-bf crowdsecurity/http-probing
cscli scenarios remove crowdsecurity/ssh-bf crowdsecurity/http-probing
`,
},
installHelp: cliHelp{
example: `cscli scenarios install crowdsecurity/ssh-bf crowdsecurity/http-probing`,
},
removeHelp: cliHelp{
example: `cscli scenarios remove crowdsecurity/ssh-bf crowdsecurity/http-probing`,
},
upgradeHelp: cliHelp{
example: `cscli scenarios upgrade crowdsecurity/ssh-bf crowdsecurity/http-probing`,
},
inspectHelp: cliHelp{
example: `cscli scenarios inspect crowdsecurity/ssh-bf crowdsecurity/http-probing`,
},
listHelp: cliHelp{
example: `cscli scenarios list
cscli scenarios list -a
cscli scenarios list crowdsecurity/ssh-bf crowdsecurity/http-probing
List only enabled scenarios unless "-a" or names are specified.`,
},
}
}

721
cmd/crowdsec-cli/hubtest.go Normal file
View file

@ -0,0 +1,721 @@
package main
import (
"encoding/json"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/fatih/color"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/crowdsec/pkg/dumps"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
"github.com/crowdsecurity/crowdsec/pkg/hubtest"
)
var (
HubTest hubtest.HubTest
HubAppsecTests hubtest.HubTest
hubPtr *hubtest.HubTest
isAppsecTest bool
)
type cliHubTest struct {
cfg configGetter
}
func NewCLIHubTest(cfg configGetter) *cliHubTest {
return &cliHubTest{
cfg: cfg,
}
}
func (cli *cliHubTest) NewCommand() *cobra.Command {
var (
hubPath string
crowdsecPath string
cscliPath string
)
cmd := &cobra.Command{
Use: "hubtest",
Short: "Run functional tests on hub configurations",
Long: "Run functional tests on hub configurations (parsers, scenarios, collections...)",
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
var err error
HubTest, err = hubtest.NewHubTest(hubPath, crowdsecPath, cscliPath, false)
if err != nil {
return fmt.Errorf("unable to load hubtest: %+v", err)
}
HubAppsecTests, err = hubtest.NewHubTest(hubPath, crowdsecPath, cscliPath, true)
if err != nil {
return fmt.Errorf("unable to load appsec specific hubtest: %+v", err)
}
// commands will use the hubPtr, will point to the default hubTest object, or the one dedicated to appsec tests
hubPtr = &HubTest
if isAppsecTest {
hubPtr = &HubAppsecTests
}
return nil
},
}
cmd.PersistentFlags().StringVar(&hubPath, "hub", ".", "Path to hub folder")
cmd.PersistentFlags().StringVar(&crowdsecPath, "crowdsec", "crowdsec", "Path to crowdsec")
cmd.PersistentFlags().StringVar(&cscliPath, "cscli", "cscli", "Path to cscli")
cmd.PersistentFlags().BoolVar(&isAppsecTest, "appsec", false, "Command relates to appsec tests")
cmd.AddCommand(cli.NewCreateCmd())
cmd.AddCommand(cli.NewRunCmd())
cmd.AddCommand(cli.NewCleanCmd())
cmd.AddCommand(cli.NewInfoCmd())
cmd.AddCommand(cli.NewListCmd())
cmd.AddCommand(cli.NewCoverageCmd())
cmd.AddCommand(cli.NewEvalCmd())
cmd.AddCommand(cli.NewExplainCmd())
return cmd
}
func (cli *cliHubTest) NewCreateCmd() *cobra.Command {
var (
ignoreParsers bool
labels map[string]string
logType string
)
parsers := []string{}
postoverflows := []string{}
scenarios := []string{}
cmd := &cobra.Command{
Use: "create",
Short: "create [test_name]",
Example: `cscli hubtest create my-awesome-test --type syslog
cscli hubtest create my-nginx-custom-test --type nginx
cscli hubtest create my-scenario-test --parsers crowdsecurity/nginx --scenarios crowdsecurity/http-probing`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
testName := args[0]
testPath := filepath.Join(hubPtr.HubTestPath, testName)
if _, err := os.Stat(testPath); os.IsExist(err) {
return fmt.Errorf("test '%s' already exists in '%s', exiting", testName, testPath)
}
if isAppsecTest {
logType = "appsec"
}
if logType == "" {
return errors.New("please provide a type (--type) for the test")
}
if err := os.MkdirAll(testPath, os.ModePerm); err != nil {
return fmt.Errorf("unable to create folder '%s': %+v", testPath, err)
}
configFilePath := filepath.Join(testPath, "config.yaml")
configFileData := &hubtest.HubTestItemConfig{}
if logType == "appsec" {
// create empty nuclei template file
nucleiFileName := fmt.Sprintf("%s.yaml", testName)
nucleiFilePath := filepath.Join(testPath, nucleiFileName)
nucleiFile, err := os.OpenFile(nucleiFilePath, os.O_RDWR|os.O_CREATE, 0o755)
if err != nil {
return err
}
ntpl := template.Must(template.New("nuclei").Parse(hubtest.TemplateNucleiFile))
if ntpl == nil {
return errors.New("unable to parse nuclei template")
}
ntpl.ExecuteTemplate(nucleiFile, "nuclei", struct{ TestName string }{TestName: testName})
nucleiFile.Close()
configFileData.AppsecRules = []string{"./appsec-rules/<author>/your_rule_here.yaml"}
configFileData.NucleiTemplate = nucleiFileName
fmt.Println()
fmt.Printf(" Test name : %s\n", testName)
fmt.Printf(" Test path : %s\n", testPath)
fmt.Printf(" Config File : %s\n", configFilePath)
fmt.Printf(" Nuclei Template : %s\n", nucleiFilePath)
} else {
// create empty log file
logFileName := fmt.Sprintf("%s.log", testName)
logFilePath := filepath.Join(testPath, logFileName)
logFile, err := os.Create(logFilePath)
if err != nil {
return err
}
logFile.Close()
// create empty parser assertion file
parserAssertFilePath := filepath.Join(testPath, hubtest.ParserAssertFileName)
parserAssertFile, err := os.Create(parserAssertFilePath)
if err != nil {
return err
}
parserAssertFile.Close()
// create empty scenario assertion file
scenarioAssertFilePath := filepath.Join(testPath, hubtest.ScenarioAssertFileName)
scenarioAssertFile, err := os.Create(scenarioAssertFilePath)
if err != nil {
return err
}
scenarioAssertFile.Close()
parsers = append(parsers, "crowdsecurity/syslog-logs")
parsers = append(parsers, "crowdsecurity/dateparse-enrich")
if len(scenarios) == 0 {
scenarios = append(scenarios, "")
}
if len(postoverflows) == 0 {
postoverflows = append(postoverflows, "")
}
configFileData.Parsers = parsers
configFileData.Scenarios = scenarios
configFileData.PostOverflows = postoverflows
configFileData.LogFile = logFileName
configFileData.LogType = logType
configFileData.IgnoreParsers = ignoreParsers
configFileData.Labels = labels
fmt.Println()
fmt.Printf(" Test name : %s\n", testName)
fmt.Printf(" Test path : %s\n", testPath)
fmt.Printf(" Log file : %s (please fill it with logs)\n", logFilePath)
fmt.Printf(" Parser assertion file : %s (please fill it with assertion)\n", parserAssertFilePath)
fmt.Printf(" Scenario assertion file : %s (please fill it with assertion)\n", scenarioAssertFilePath)
fmt.Printf(" Configuration File : %s (please fill it with parsers, scenarios...)\n", configFilePath)
}
fd, err := os.Create(configFilePath)
if err != nil {
return fmt.Errorf("open: %w", err)
}
data, err := yaml.Marshal(configFileData)
if err != nil {
return fmt.Errorf("marshal: %w", err)
}
_, err = fd.Write(data)
if err != nil {
return fmt.Errorf("write: %w", err)
}
if err := fd.Close(); err != nil {
return fmt.Errorf("close: %w", err)
}
return nil
},
}
cmd.PersistentFlags().StringVarP(&logType, "type", "t", "", "Log type of the test")
cmd.Flags().StringSliceVarP(&parsers, "parsers", "p", parsers, "Parsers to add to test")
cmd.Flags().StringSliceVar(&postoverflows, "postoverflows", postoverflows, "Postoverflows to add to test")
cmd.Flags().StringSliceVarP(&scenarios, "scenarios", "s", scenarios, "Scenarios to add to test")
cmd.PersistentFlags().BoolVar(&ignoreParsers, "ignore-parsers", false, "Don't run test on parsers")
return cmd
}
func (cli *cliHubTest) NewRunCmd() *cobra.Command {
var (
noClean bool
runAll bool
forceClean bool
NucleiTargetHost string
AppSecHost string
)
cmd := &cobra.Command{
Use: "run",
Short: "run [test_name]",
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := cli.cfg()
if !runAll && len(args) == 0 {
printHelp(cmd)
return errors.New("please provide test to run or --all flag")
}
hubPtr.NucleiTargetHost = NucleiTargetHost
hubPtr.AppSecHost = AppSecHost
if runAll {
if err := hubPtr.LoadAllTests(); err != nil {
return fmt.Errorf("unable to load all tests: %+v", err)
}
} else {
for _, testName := range args {
_, err := hubPtr.LoadTestItem(testName)
if err != nil {
return fmt.Errorf("unable to load test '%s': %w", testName, err)
}
}
}
// set timezone to avoid DST issues
os.Setenv("TZ", "UTC")
for _, test := range hubPtr.Tests {
if cfg.Cscli.Output == "human" {
log.Infof("Running test '%s'", test.Name)
}
err := test.Run()
if err != nil {
log.Errorf("running test '%s' failed: %+v", test.Name, err)
}
}
return nil
},
PersistentPostRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
success := true
testResult := make(map[string]bool)
for _, test := range hubPtr.Tests {
if test.AutoGen && !isAppsecTest {
if test.ParserAssert.AutoGenAssert {
log.Warningf("Assert file '%s' is empty, generating assertion:", test.ParserAssert.File)
fmt.Println()
fmt.Println(test.ParserAssert.AutoGenAssertData)
}
if test.ScenarioAssert.AutoGenAssert {
log.Warningf("Assert file '%s' is empty, generating assertion:", test.ScenarioAssert.File)
fmt.Println()
fmt.Println(test.ScenarioAssert.AutoGenAssertData)
}
if !noClean {
if err := test.Clean(); err != nil {
return fmt.Errorf("unable to clean test '%s' env: %w", test.Name, err)
}
}
fmt.Printf("\nPlease fill your assert file(s) for test '%s', exiting\n", test.Name)
os.Exit(1)
}
testResult[test.Name] = test.Success
if test.Success {
if cfg.Cscli.Output == "human" {
log.Infof("Test '%s' passed successfully (%d assertions)\n", test.Name, test.ParserAssert.NbAssert+test.ScenarioAssert.NbAssert)
}
if !noClean {
if err := test.Clean(); err != nil {
return fmt.Errorf("unable to clean test '%s' env: %w", test.Name, err)
}
}
} else {
success = false
cleanTestEnv := false
if cfg.Cscli.Output == "human" {
if len(test.ParserAssert.Fails) > 0 {
fmt.Println()
log.Errorf("Parser test '%s' failed (%d errors)\n", test.Name, len(test.ParserAssert.Fails))
for _, fail := range test.ParserAssert.Fails {
fmt.Printf("(L.%d) %s => %s\n", fail.Line, emoji.RedCircle, fail.Expression)
fmt.Printf(" Actual expression values:\n")
for key, value := range fail.Debug {
fmt.Printf(" %s = '%s'\n", key, strings.TrimSuffix(value, "\n"))
}
fmt.Println()
}
}
if len(test.ScenarioAssert.Fails) > 0 {
fmt.Println()
log.Errorf("Scenario test '%s' failed (%d errors)\n", test.Name, len(test.ScenarioAssert.Fails))
for _, fail := range test.ScenarioAssert.Fails {
fmt.Printf("(L.%d) %s => %s\n", fail.Line, emoji.RedCircle, fail.Expression)
fmt.Printf(" Actual expression values:\n")
for key, value := range fail.Debug {
fmt.Printf(" %s = '%s'\n", key, strings.TrimSuffix(value, "\n"))
}
fmt.Println()
}
}
if !forceClean && !noClean {
prompt := &survey.Confirm{
Message: fmt.Sprintf("\nDo you want to remove runtime folder for test '%s'? (default: Yes)", test.Name),
Default: true,
}
if err := survey.AskOne(prompt, &cleanTestEnv); err != nil {
return fmt.Errorf("unable to ask to remove runtime folder: %w", err)
}
}
}
if cleanTestEnv || forceClean {
if err := test.Clean(); err != nil {
return fmt.Errorf("unable to clean test '%s' env: %w", test.Name, err)
}
}
}
}
switch cfg.Cscli.Output {
case "human":
hubTestResultTable(color.Output, testResult)
case "json":
jsonResult := make(map[string][]string, 0)
jsonResult["success"] = make([]string, 0)
jsonResult["fail"] = make([]string, 0)
for testName, success := range testResult {
if success {
jsonResult["success"] = append(jsonResult["success"], testName)
} else {
jsonResult["fail"] = append(jsonResult["fail"], testName)
}
}
jsonStr, err := json.Marshal(jsonResult)
if err != nil {
return fmt.Errorf("unable to json test result: %w", err)
}
fmt.Println(string(jsonStr))
default:
return errors.New("only human/json output modes are supported")
}
if !success {
os.Exit(1)
}
return nil
},
}
cmd.Flags().BoolVar(&noClean, "no-clean", false, "Don't clean runtime environment if test succeed")
cmd.Flags().BoolVar(&forceClean, "clean", false, "Clean runtime environment if test fail")
cmd.Flags().StringVar(&NucleiTargetHost, "target", hubtest.DefaultNucleiTarget, "Target for AppSec Test")
cmd.Flags().StringVar(&AppSecHost, "host", hubtest.DefaultAppsecHost, "Address to expose AppSec for hubtest")
cmd.Flags().BoolVar(&runAll, "all", false, "Run all tests")
return cmd
}
func (cli *cliHubTest) NewCleanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "clean",
Short: "clean [test_name]",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
for _, testName := range args {
test, err := hubPtr.LoadTestItem(testName)
if err != nil {
return fmt.Errorf("unable to load test '%s': %w", testName, err)
}
if err := test.Clean(); err != nil {
return fmt.Errorf("unable to clean test '%s' env: %w", test.Name, err)
}
}
return nil
},
}
return cmd
}
func (cli *cliHubTest) NewInfoCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "info",
Short: "info [test_name]",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
for _, testName := range args {
test, err := hubPtr.LoadTestItem(testName)
if err != nil {
return fmt.Errorf("unable to load test '%s': %w", testName, err)
}
fmt.Println()
fmt.Printf(" Test name : %s\n", test.Name)
fmt.Printf(" Test path : %s\n", test.Path)
if isAppsecTest {
fmt.Printf(" Nuclei Template : %s\n", test.Config.NucleiTemplate)
fmt.Printf(" Appsec Rules : %s\n", strings.Join(test.Config.AppsecRules, ", "))
} else {
fmt.Printf(" Log file : %s\n", filepath.Join(test.Path, test.Config.LogFile))
fmt.Printf(" Parser assertion file : %s\n", filepath.Join(test.Path, hubtest.ParserAssertFileName))
fmt.Printf(" Scenario assertion file : %s\n", filepath.Join(test.Path, hubtest.ScenarioAssertFileName))
}
fmt.Printf(" Configuration File : %s\n", filepath.Join(test.Path, "config.yaml"))
}
return nil
},
}
return cmd
}
func (cli *cliHubTest) NewListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list",
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := hubPtr.LoadAllTests(); err != nil {
return fmt.Errorf("unable to load all tests: %w", err)
}
switch cfg.Cscli.Output {
case "human":
hubTestListTable(color.Output, hubPtr.Tests)
case "json":
j, err := json.MarshalIndent(hubPtr.Tests, " ", " ")
if err != nil {
return err
}
fmt.Println(string(j))
default:
return errors.New("only human/json output modes are supported")
}
return nil
},
}
return cmd
}
func (cli *cliHubTest) NewCoverageCmd() *cobra.Command {
var (
showParserCov bool
showScenarioCov bool
showOnlyPercent bool
showAppsecCov bool
)
cmd := &cobra.Command{
Use: "coverage",
Short: "coverage",
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
// for this one we explicitly don't do for appsec
if err := HubTest.LoadAllTests(); err != nil {
return fmt.Errorf("unable to load all tests: %+v", err)
}
var err error
scenarioCoverage := []hubtest.Coverage{}
parserCoverage := []hubtest.Coverage{}
appsecRuleCoverage := []hubtest.Coverage{}
scenarioCoveragePercent := 0
parserCoveragePercent := 0
appsecRuleCoveragePercent := 0
// if both are false (flag by default), show both
showAll := !showScenarioCov && !showParserCov && !showAppsecCov
if showParserCov || showAll {
parserCoverage, err = HubTest.GetParsersCoverage()
if err != nil {
return fmt.Errorf("while getting parser coverage: %w", err)
}
parserTested := 0
for _, test := range parserCoverage {
if test.TestsCount > 0 {
parserTested++
}
}
parserCoveragePercent = int(math.Round((float64(parserTested) / float64(len(parserCoverage)) * 100)))
}
if showScenarioCov || showAll {
scenarioCoverage, err = HubTest.GetScenariosCoverage()
if err != nil {
return fmt.Errorf("while getting scenario coverage: %w", err)
}
scenarioTested := 0
for _, test := range scenarioCoverage {
if test.TestsCount > 0 {
scenarioTested++
}
}
scenarioCoveragePercent = int(math.Round((float64(scenarioTested) / float64(len(scenarioCoverage)) * 100)))
}
if showAppsecCov || showAll {
appsecRuleCoverage, err = HubTest.GetAppsecCoverage()
if err != nil {
return fmt.Errorf("while getting scenario coverage: %w", err)
}
appsecRuleTested := 0
for _, test := range appsecRuleCoverage {
if test.TestsCount > 0 {
appsecRuleTested++
}
}
appsecRuleCoveragePercent = int(math.Round((float64(appsecRuleTested) / float64(len(appsecRuleCoverage)) * 100)))
}
if showOnlyPercent {
switch {
case showAll:
fmt.Printf("parsers=%d%%\nscenarios=%d%%\nappsec_rules=%d%%", parserCoveragePercent, scenarioCoveragePercent, appsecRuleCoveragePercent)
case showParserCov:
fmt.Printf("parsers=%d%%", parserCoveragePercent)
case showScenarioCov:
fmt.Printf("scenarios=%d%%", scenarioCoveragePercent)
case showAppsecCov:
fmt.Printf("appsec_rules=%d%%", appsecRuleCoveragePercent)
}
os.Exit(0)
}
switch cfg.Cscli.Output {
case "human":
if showParserCov || showAll {
hubTestParserCoverageTable(color.Output, parserCoverage)
}
if showScenarioCov || showAll {
hubTestScenarioCoverageTable(color.Output, scenarioCoverage)
}
if showAppsecCov || showAll {
hubTestAppsecRuleCoverageTable(color.Output, appsecRuleCoverage)
}
fmt.Println()
if showParserCov || showAll {
fmt.Printf("PARSERS : %d%% of coverage\n", parserCoveragePercent)
}
if showScenarioCov || showAll {
fmt.Printf("SCENARIOS : %d%% of coverage\n", scenarioCoveragePercent)
}
if showAppsecCov || showAll {
fmt.Printf("APPSEC RULES : %d%% of coverage\n", appsecRuleCoveragePercent)
}
case "json":
dump, err := json.MarshalIndent(parserCoverage, "", " ")
if err != nil {
return err
}
fmt.Printf("%s", dump)
dump, err = json.MarshalIndent(scenarioCoverage, "", " ")
if err != nil {
return err
}
fmt.Printf("%s", dump)
dump, err = json.MarshalIndent(appsecRuleCoverage, "", " ")
if err != nil {
return err
}
fmt.Printf("%s", dump)
default:
return errors.New("only human/json output modes are supported")
}
return nil
},
}
cmd.PersistentFlags().BoolVar(&showOnlyPercent, "percent", false, "Show only percentages of coverage")
cmd.PersistentFlags().BoolVar(&showParserCov, "parsers", false, "Show only parsers coverage")
cmd.PersistentFlags().BoolVar(&showScenarioCov, "scenarios", false, "Show only scenarios coverage")
cmd.PersistentFlags().BoolVar(&showAppsecCov, "appsec", false, "Show only appsec coverage")
return cmd
}
func (cli *cliHubTest) NewEvalCmd() *cobra.Command {
var evalExpression string
cmd := &cobra.Command{
Use: "eval",
Short: "eval [test_name]",
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
for _, testName := range args {
test, err := hubPtr.LoadTestItem(testName)
if err != nil {
return fmt.Errorf("can't load test: %+v", err)
}
err = test.ParserAssert.LoadTest(test.ParserResultFile)
if err != nil {
return fmt.Errorf("can't load test results from '%s': %+v", test.ParserResultFile, err)
}
output, err := test.ParserAssert.EvalExpression(evalExpression)
if err != nil {
return err
}
fmt.Print(output)
}
return nil
},
}
cmd.PersistentFlags().StringVarP(&evalExpression, "expr", "e", "", "Expression to eval")
return cmd
}
func (cli *cliHubTest) NewExplainCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "explain",
Short: "explain [test_name]",
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
for _, testName := range args {
test, err := HubTest.LoadTestItem(testName)
if err != nil {
return fmt.Errorf("can't load test: %+v", err)
}
err = test.ParserAssert.LoadTest(test.ParserResultFile)
if err != nil {
if err = test.Run(); err != nil {
return fmt.Errorf("running test '%s' failed: %+v", test.Name, err)
}
if err = test.ParserAssert.LoadTest(test.ParserResultFile); err != nil {
return fmt.Errorf("unable to load parser result after run: %w", err)
}
}
err = test.ScenarioAssert.LoadTest(test.ScenarioResultFile, test.BucketPourResultFile)
if err != nil {
if err = test.Run(); err != nil {
return fmt.Errorf("running test '%s' failed: %+v", test.Name, err)
}
if err = test.ScenarioAssert.LoadTest(test.ScenarioResultFile, test.BucketPourResultFile); err != nil {
return fmt.Errorf("unable to load scenario result after run: %w", err)
}
}
opts := dumps.DumpOpts{}
dumps.DumpTree(*test.ParserAssert.TestData, *test.ScenarioAssert.PourData, opts)
}
return nil
},
}
return cmd
}

View file

@ -0,0 +1,105 @@
package main
import (
"fmt"
"io"
"github.com/aquasecurity/table"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
"github.com/crowdsecurity/crowdsec/pkg/hubtest"
)
func hubTestResultTable(out io.Writer, testResult map[string]bool) {
t := newLightTable(out)
t.SetHeaders("Test", "Result")
t.SetHeaderAlignment(table.AlignLeft)
t.SetAlignment(table.AlignLeft)
for testName, success := range testResult {
status := emoji.CheckMarkButton
if !success {
status = emoji.CrossMark
}
t.AddRow(testName, status)
}
t.Render()
}
func hubTestListTable(out io.Writer, tests []*hubtest.HubTestItem) {
t := newLightTable(out)
t.SetHeaders("Name", "Path")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft)
for _, test := range tests {
t.AddRow(test.Name, test.Path)
}
t.Render()
}
func hubTestParserCoverageTable(out io.Writer, coverage []hubtest.Coverage) {
t := newLightTable(out)
t.SetHeaders("Parser", "Status", "Number of tests")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
parserTested := 0
for _, test := range coverage {
status := emoji.RedCircle
if test.TestsCount > 0 {
status = emoji.GreenCircle
parserTested++
}
t.AddRow(test.Name, status, fmt.Sprintf("%d times (across %d tests)", test.TestsCount, len(test.PresentIn)))
}
t.Render()
}
func hubTestAppsecRuleCoverageTable(out io.Writer, coverage []hubtest.Coverage) {
t := newLightTable(out)
t.SetHeaders("Appsec Rule", "Status", "Number of tests")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
parserTested := 0
for _, test := range coverage {
status := emoji.RedCircle
if test.TestsCount > 0 {
status = emoji.GreenCircle
parserTested++
}
t.AddRow(test.Name, status, fmt.Sprintf("%d times (across %d tests)", test.TestsCount, len(test.PresentIn)))
}
t.Render()
}
func hubTestScenarioCoverageTable(out io.Writer, coverage []hubtest.Coverage) {
t := newLightTable(out)
t.SetHeaders("Scenario", "Status", "Number of tests")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
parserTested := 0
for _, test := range coverage {
status := emoji.RedCircle
if test.TestsCount > 0 {
status = emoji.GreenCircle
parserTested++
}
t.AddRow(test.Name, status, fmt.Sprintf("%d times (across %d tests)", test.TestsCount, len(test.PresentIn)))
}
t.Render()
}

View file

@ -0,0 +1,327 @@
package main
import (
"fmt"
"math"
"net/http"
"strconv"
"strings"
"time"
"github.com/fatih/color"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/go-cs-lib/trace"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
func ShowMetrics(hubItem *cwhub.Item) error {
switch hubItem.Type {
case cwhub.PARSERS:
metrics := GetParserMetric(csConfig.Cscli.PrometheusUrl, hubItem.Name)
parserMetricsTable(color.Output, hubItem.Name, metrics)
case cwhub.SCENARIOS:
metrics := GetScenarioMetric(csConfig.Cscli.PrometheusUrl, hubItem.Name)
scenarioMetricsTable(color.Output, hubItem.Name, metrics)
case cwhub.COLLECTIONS:
for _, sub := range hubItem.SubItems() {
if err := ShowMetrics(sub); err != nil {
return err
}
}
case cwhub.APPSEC_RULES:
metrics := GetAppsecRuleMetric(csConfig.Cscli.PrometheusUrl, hubItem.Name)
appsecMetricsTable(color.Output, hubItem.Name, metrics)
default: // no metrics for this item type
}
return nil
}
// GetParserMetric is a complete rip from prom2json
func GetParserMetric(url string, itemName string) map[string]map[string]int {
stats := make(map[string]map[string]int)
result := GetPrometheusMetric(url)
for idx, fam := range result {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
}
log.Tracef("round %d", idx)
for _, m := range fam.Metrics {
metric, ok := m.(prom2json.Metric)
if !ok {
log.Debugf("failed to convert metric to prom2json.Metric")
continue
}
name, ok := metric.Labels["name"]
if !ok {
log.Debugf("no name in Metric %v", metric.Labels)
}
if name != itemName {
continue
}
source, ok := metric.Labels["source"]
if !ok {
log.Debugf("no source in Metric %v", metric.Labels)
} else {
if srctype, ok := metric.Labels["type"]; ok {
source = srctype + ":" + source
}
}
value := m.(prom2json.Metric).Value
fval, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Errorf("Unexpected int value %s : %s", value, err)
continue
}
ival := int(fval)
switch fam.Name {
case "cs_reader_hits_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
stats[source]["parsed"] = 0
stats[source]["reads"] = 0
stats[source]["unparsed"] = 0
stats[source]["hits"] = 0
}
stats[source]["reads"] += ival
case "cs_parser_hits_ok_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
}
stats[source]["parsed"] += ival
case "cs_parser_hits_ko_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
}
stats[source]["unparsed"] += ival
case "cs_node_hits_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
}
stats[source]["hits"] += ival
case "cs_node_hits_ok_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
}
stats[source]["parsed"] += ival
case "cs_node_hits_ko_total":
if _, ok := stats[source]; !ok {
stats[source] = make(map[string]int)
}
stats[source]["unparsed"] += ival
default:
continue
}
}
}
return stats
}
func GetScenarioMetric(url string, itemName string) map[string]int {
stats := make(map[string]int)
stats["instantiation"] = 0
stats["curr_count"] = 0
stats["overflow"] = 0
stats["pour"] = 0
stats["underflow"] = 0
result := GetPrometheusMetric(url)
for idx, fam := range result {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
}
log.Tracef("round %d", idx)
for _, m := range fam.Metrics {
metric, ok := m.(prom2json.Metric)
if !ok {
log.Debugf("failed to convert metric to prom2json.Metric")
continue
}
name, ok := metric.Labels["name"]
if !ok {
log.Debugf("no name in Metric %v", metric.Labels)
}
if name != itemName {
continue
}
value := m.(prom2json.Metric).Value
fval, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Errorf("Unexpected int value %s : %s", value, err)
continue
}
ival := int(fval)
switch fam.Name {
case "cs_bucket_created_total":
stats["instantiation"] += ival
case "cs_buckets":
stats["curr_count"] += ival
case "cs_bucket_overflowed_total":
stats["overflow"] += ival
case "cs_bucket_poured_total":
stats["pour"] += ival
case "cs_bucket_underflowed_total":
stats["underflow"] += ival
default:
continue
}
}
}
return stats
}
func GetAppsecRuleMetric(url string, itemName string) map[string]int {
stats := make(map[string]int)
stats["inband_hits"] = 0
stats["outband_hits"] = 0
results := GetPrometheusMetric(url)
for idx, fam := range results {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
}
log.Tracef("round %d", idx)
for _, m := range fam.Metrics {
metric, ok := m.(prom2json.Metric)
if !ok {
log.Debugf("failed to convert metric to prom2json.Metric")
continue
}
name, ok := metric.Labels["rule_name"]
if !ok {
log.Debugf("no rule_name in Metric %v", metric.Labels)
}
if name != itemName {
continue
}
band, ok := metric.Labels["type"]
if !ok {
log.Debugf("no type in Metric %v", metric.Labels)
}
value := m.(prom2json.Metric).Value
fval, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Errorf("Unexpected int value %s : %s", value, err)
continue
}
ival := int(fval)
switch fam.Name {
case "cs_appsec_rule_hits":
switch band {
case "inband":
stats["inband_hits"] += ival
case "outband":
stats["outband_hits"] += ival
default:
continue
}
default:
continue
}
}
}
return stats
}
func GetPrometheusMetric(url string) []*prom2json.Family {
mfChan := make(chan *dto.MetricFamily, 1024)
// Start with the DefaultTransport for sane defaults.
transport := http.DefaultTransport.(*http.Transport).Clone()
// Conservatively disable HTTP keep-alives as this program will only
// ever need a single HTTP request.
transport.DisableKeepAlives = true
// Timeout early if the server doesn't even return the headers.
transport.ResponseHeaderTimeout = time.Minute
go func() {
defer trace.CatchPanic("crowdsec/GetPrometheusMetric")
err := prom2json.FetchMetricFamilies(url, mfChan, transport)
if err != nil {
log.Fatalf("failed to fetch prometheus metrics : %v", err)
}
}()
result := []*prom2json.Family{}
for mf := range mfChan {
result = append(result, prom2json.NewFamily(mf))
}
log.Debugf("Finished reading prometheus output, %d entries", len(result))
return result
}
type unit struct {
value int64
symbol string
}
var ranges = []unit{
{value: 1e18, symbol: "E"},
{value: 1e15, symbol: "P"},
{value: 1e12, symbol: "T"},
{value: 1e9, symbol: "G"},
{value: 1e6, symbol: "M"},
{value: 1e3, symbol: "k"},
{value: 1, symbol: ""},
}
func formatNumber(num int) string {
goodUnit := unit{}
for _, u := range ranges {
if int64(num) >= u.value {
goodUnit = u
break
}
}
if goodUnit.value == 1 {
return fmt.Sprintf("%d%s", num, goodUnit.symbol)
}
res := math.Round(float64(num)/float64(goodUnit.value)*100) / 100
return fmt.Sprintf("%.2f%s", res, goodUnit.symbol)
}

View file

@ -0,0 +1,85 @@
package main
import (
"fmt"
"slices"
"strings"
"github.com/agext/levenshtein"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
// suggestNearestMessage returns a message with the most similar item name, if one is found
func suggestNearestMessage(hub *cwhub.Hub, itemType string, itemName string) string {
const maxDistance = 7
score := 100
nearest := ""
for _, item := range hub.GetItemMap(itemType) {
d := levenshtein.Distance(itemName, item.Name, nil)
if d < score {
score = d
nearest = item.Name
}
}
msg := fmt.Sprintf("can't find '%s' in %s", itemName, itemType)
if score < maxDistance {
msg += fmt.Sprintf(", did you mean '%s'?", nearest)
}
return msg
}
func compAllItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
hub, err := require.Hub(csConfig, nil, nil)
if err != nil {
return nil, cobra.ShellCompDirectiveDefault
}
comp := make([]string, 0)
for _, item := range hub.GetItemMap(itemType) {
if !slices.Contains(args, item.Name) && strings.Contains(item.Name, toComplete) {
comp = append(comp, item.Name)
}
}
cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true)
return comp, cobra.ShellCompDirectiveNoFileComp
}
func compInstalledItems(itemType string, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
hub, err := require.Hub(csConfig, nil, nil)
if err != nil {
return nil, cobra.ShellCompDirectiveDefault
}
items, err := hub.GetInstalledNamesByType(itemType)
if err != nil {
cobra.CompDebugln(fmt.Sprintf("list installed %s err: %s", itemType, err), true)
return nil, cobra.ShellCompDirectiveDefault
}
comp := make([]string, 0)
if toComplete != "" {
for _, item := range items {
if strings.Contains(item, toComplete) {
comp = append(comp, item)
}
}
} else {
comp = items
}
cobra.CompDebugln(fmt.Sprintf("%s: %+v", itemType, comp), true)
return comp, cobra.ShellCompDirectiveNoFileComp
}

546
cmd/crowdsec-cli/itemcli.go Normal file
View file

@ -0,0 +1,546 @@
package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/fatih/color"
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
"github.com/hexops/gotextdiff/span"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/go-cs-lib/coalesce"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
type cliHelp struct {
// Example is required, the others have a default value
// generated from the item type
use string
short string
long string
example string
}
type cliItem struct {
cfg configGetter
name string // plural, as used in the hub index
singular string
oneOrMore string // parenthetical pluralizaion: "parser(s)"
help cliHelp
installHelp cliHelp
removeHelp cliHelp
upgradeHelp cliHelp
inspectHelp cliHelp
inspectDetail func(item *cwhub.Item) error
listHelp cliHelp
}
func (cli cliItem) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: coalesce.String(cli.help.use, fmt.Sprintf("%s <action> [item]...", cli.name)),
Short: coalesce.String(cli.help.short, fmt.Sprintf("Manage hub %s", cli.name)),
Long: cli.help.long,
Example: cli.help.example,
Args: cobra.MinimumNArgs(1),
Aliases: []string{cli.singular},
DisableAutoGenTag: true,
}
cmd.AddCommand(cli.newInstallCmd())
cmd.AddCommand(cli.newRemoveCmd())
cmd.AddCommand(cli.newUpgradeCmd())
cmd.AddCommand(cli.newInspectCmd())
cmd.AddCommand(cli.newListCmd())
return cmd
}
func (cli cliItem) install(args []string, downloadOnly bool, force bool, ignoreError bool) error {
cfg := cli.cfg()
hub, err := require.Hub(cfg, require.RemoteHub(cfg), log.StandardLogger())
if err != nil {
return err
}
for _, name := range args {
item := hub.GetItem(cli.name, name)
if item == nil {
msg := suggestNearestMessage(hub, cli.name, name)
if !ignoreError {
return errors.New(msg)
}
log.Errorf(msg)
continue
}
if err := item.Install(force, downloadOnly); err != nil {
if !ignoreError {
return fmt.Errorf("error while installing '%s': %w", item.Name, err)
}
log.Errorf("Error while installing '%s': %s", item.Name, err)
}
}
log.Infof(ReloadMessage())
return nil
}
func (cli cliItem) newInstallCmd() *cobra.Command {
var (
downloadOnly bool
force bool
ignoreError bool
)
cmd := &cobra.Command{
Use: coalesce.String(cli.installHelp.use, "install [item]..."),
Short: coalesce.String(cli.installHelp.short, fmt.Sprintf("Install given %s", cli.oneOrMore)),
Long: coalesce.String(cli.installHelp.long, fmt.Sprintf("Fetch and install one or more %s from the hub", cli.name)),
Example: cli.installHelp.example,
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compAllItems(cli.name, args, toComplete)
},
RunE: func(_ *cobra.Command, args []string) error {
return cli.install(args, downloadOnly, force, ignoreError)
},
}
flags := cmd.Flags()
flags.BoolVarP(&downloadOnly, "download-only", "d", false, "Only download packages, don't enable")
flags.BoolVar(&force, "force", false, "Force install: overwrite tainted and outdated files")
flags.BoolVar(&ignoreError, "ignore", false, fmt.Sprintf("Ignore errors when installing multiple %s", cli.name))
return cmd
}
// return the names of the installed parents of an item, used to check if we can remove it
func istalledParentNames(item *cwhub.Item) []string {
ret := make([]string, 0)
for _, parent := range item.Ancestors() {
if parent.State.Installed {
ret = append(ret, parent.Name)
}
}
return ret
}
func (cli cliItem) remove(args []string, purge bool, force bool, all bool) error {
hub, err := require.Hub(cli.cfg(), nil, log.StandardLogger())
if err != nil {
return err
}
if all {
getter := hub.GetInstalledItemsByType
if purge {
getter = hub.GetItemsByType
}
items, err := getter(cli.name)
if err != nil {
return err
}
removed := 0
for _, item := range items {
didRemove, err := item.Remove(purge, force)
if err != nil {
return err
}
if didRemove {
log.Infof("Removed %s", item.Name)
removed++
}
}
log.Infof("Removed %d %s", removed, cli.name)
if removed > 0 {
log.Infof(ReloadMessage())
}
return nil
}
if len(args) == 0 {
return fmt.Errorf("specify at least one %s to remove or '--all'", cli.singular)
}
removed := 0
for _, itemName := range args {
item := hub.GetItem(cli.name, itemName)
if item == nil {
return fmt.Errorf("can't find '%s' in %s", itemName, cli.name)
}
parents := istalledParentNames(item)
if !force && len(parents) > 0 {
log.Warningf("%s belongs to collections: %s", item.Name, parents)
log.Warningf("Run 'sudo cscli %s remove %s --force' if you want to force remove this %s", item.Type, item.Name, cli.singular)
continue
}
didRemove, err := item.Remove(purge, force)
if err != nil {
return err
}
if didRemove {
log.Infof("Removed %s", item.Name)
removed++
}
}
log.Infof("Removed %d %s", removed, cli.name)
if removed > 0 {
log.Infof(ReloadMessage())
}
return nil
}
func (cli cliItem) newRemoveCmd() *cobra.Command {
var (
purge bool
force bool
all bool
)
cmd := &cobra.Command{
Use: coalesce.String(cli.removeHelp.use, "remove [item]..."),
Short: coalesce.String(cli.removeHelp.short, fmt.Sprintf("Remove given %s", cli.oneOrMore)),
Long: coalesce.String(cli.removeHelp.long, fmt.Sprintf("Remove one or more %s", cli.name)),
Example: cli.removeHelp.example,
Aliases: []string{"delete"},
DisableAutoGenTag: true,
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstalledItems(cli.name, args, toComplete)
},
RunE: func(_ *cobra.Command, args []string) error {
return cli.remove(args, purge, force, all)
},
}
flags := cmd.Flags()
flags.BoolVar(&purge, "purge", false, "Delete source file too")
flags.BoolVar(&force, "force", false, "Force remove: remove tainted and outdated files")
flags.BoolVar(&all, "all", false, fmt.Sprintf("Remove all the %s", cli.name))
return cmd
}
func (cli cliItem) upgrade(args []string, force bool, all bool) error {
cfg := cli.cfg()
hub, err := require.Hub(cfg, require.RemoteHub(cfg), log.StandardLogger())
if err != nil {
return err
}
if all {
items, err := hub.GetInstalledItemsByType(cli.name)
if err != nil {
return err
}
updated := 0
for _, item := range items {
didUpdate, err := item.Upgrade(force)
if err != nil {
return err
}
if didUpdate {
updated++
}
}
log.Infof("Updated %d %s", updated, cli.name)
if updated > 0 {
log.Infof(ReloadMessage())
}
return nil
}
if len(args) == 0 {
return fmt.Errorf("specify at least one %s to upgrade or '--all'", cli.singular)
}
updated := 0
for _, itemName := range args {
item := hub.GetItem(cli.name, itemName)
if item == nil {
return fmt.Errorf("can't find '%s' in %s", itemName, cli.name)
}
didUpdate, err := item.Upgrade(force)
if err != nil {
return err
}
if didUpdate {
log.Infof("Updated %s", item.Name)
updated++
}
}
if updated > 0 {
log.Infof(ReloadMessage())
}
return nil
}
func (cli cliItem) newUpgradeCmd() *cobra.Command {
var (
all bool
force bool
)
cmd := &cobra.Command{
Use: coalesce.String(cli.upgradeHelp.use, "upgrade [item]..."),
Short: coalesce.String(cli.upgradeHelp.short, fmt.Sprintf("Upgrade given %s", cli.oneOrMore)),
Long: coalesce.String(cli.upgradeHelp.long, fmt.Sprintf("Fetch and upgrade one or more %s from the hub", cli.name)),
Example: cli.upgradeHelp.example,
DisableAutoGenTag: true,
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstalledItems(cli.name, args, toComplete)
},
RunE: func(_ *cobra.Command, args []string) error {
return cli.upgrade(args, force, all)
},
}
flags := cmd.Flags()
flags.BoolVarP(&all, "all", "a", false, fmt.Sprintf("Upgrade all the %s", cli.name))
flags.BoolVar(&force, "force", false, "Force upgrade: overwrite tainted and outdated files")
return cmd
}
func (cli cliItem) inspect(args []string, url string, diff bool, rev bool, noMetrics bool) error {
cfg := cli.cfg()
if rev && !diff {
return errors.New("--rev can only be used with --diff")
}
if url != "" {
cfg.Cscli.PrometheusUrl = url
}
remote := (*cwhub.RemoteHubCfg)(nil)
if diff {
remote = require.RemoteHub(cfg)
}
hub, err := require.Hub(cfg, remote, log.StandardLogger())
if err != nil {
return err
}
for _, name := range args {
item := hub.GetItem(cli.name, name)
if item == nil {
return fmt.Errorf("can't find '%s' in %s", name, cli.name)
}
if diff {
fmt.Println(cli.whyTainted(hub, item, rev))
continue
}
if err = inspectItem(item, !noMetrics); err != nil {
return err
}
if cli.inspectDetail != nil {
if err = cli.inspectDetail(item); err != nil {
return err
}
}
}
return nil
}
func (cli cliItem) newInspectCmd() *cobra.Command {
var (
url string
diff bool
rev bool
noMetrics bool
)
cmd := &cobra.Command{
Use: coalesce.String(cli.inspectHelp.use, "inspect [item]..."),
Short: coalesce.String(cli.inspectHelp.short, fmt.Sprintf("Inspect given %s", cli.oneOrMore)),
Long: coalesce.String(cli.inspectHelp.long, fmt.Sprintf("Inspect the state of one or more %s", cli.name)),
Example: cli.inspectHelp.example,
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
ValidArgsFunction: func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return compInstalledItems(cli.name, args, toComplete)
},
RunE: func(_ *cobra.Command, args []string) error {
return cli.inspect(args, url, diff, rev, noMetrics)
},
}
flags := cmd.Flags()
flags.StringVarP(&url, "url", "u", "", "Prometheus url")
flags.BoolVar(&diff, "diff", false, "Show diff with latest version (for tainted items)")
flags.BoolVar(&rev, "rev", false, "Reverse diff output")
flags.BoolVar(&noMetrics, "no-metrics", false, "Don't show metrics (when cscli.output=human)")
return cmd
}
func (cli cliItem) list(args []string, all bool) error {
hub, err := require.Hub(cli.cfg(), nil, log.StandardLogger())
if err != nil {
return err
}
items := make(map[string][]*cwhub.Item)
items[cli.name], err = selectItems(hub, cli.name, args, !all)
if err != nil {
return err
}
if err = listItems(color.Output, []string{cli.name}, items, false); err != nil {
return err
}
return nil
}
func (cli cliItem) newListCmd() *cobra.Command {
var all bool
cmd := &cobra.Command{
Use: coalesce.String(cli.listHelp.use, "list [item... | -a]"),
Short: coalesce.String(cli.listHelp.short, fmt.Sprintf("List %s", cli.oneOrMore)),
Long: coalesce.String(cli.listHelp.long, fmt.Sprintf("List of installed/available/specified %s", cli.name)),
Example: cli.listHelp.example,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
return cli.list(args, all)
},
}
flags := cmd.Flags()
flags.BoolVarP(&all, "all", "a", false, "List disabled items as well")
return cmd
}
// return the diff between the installed version and the latest version
func (cli cliItem) itemDiff(item *cwhub.Item, reverse bool) (string, error) {
if !item.State.Installed {
return "", fmt.Errorf("'%s' is not installed", item.FQName())
}
latestContent, remoteURL, err := item.FetchLatest()
if err != nil {
return "", err
}
localContent, err := os.ReadFile(item.State.LocalPath)
if err != nil {
return "", fmt.Errorf("while reading %s: %w", item.State.LocalPath, err)
}
file1 := item.State.LocalPath
file2 := remoteURL
content1 := string(localContent)
content2 := string(latestContent)
if reverse {
file1, file2 = file2, file1
content1, content2 = content2, content1
}
edits := myers.ComputeEdits(span.URIFromPath(file1), content1, content2)
diff := gotextdiff.ToUnified(file1, file2, content1, edits)
return fmt.Sprintf("%s", diff), nil
}
func (cli cliItem) whyTainted(hub *cwhub.Hub, item *cwhub.Item, reverse bool) string {
if !item.State.Installed {
return fmt.Sprintf("# %s is not installed", item.FQName())
}
if !item.State.Tainted {
return fmt.Sprintf("# %s is not tainted", item.FQName())
}
if len(item.State.TaintedBy) == 0 {
return fmt.Sprintf("# %s is tainted but we don't know why. please report this as a bug", item.FQName())
}
ret := []string{
fmt.Sprintf("# Let's see why %s is tainted.", item.FQName()),
}
for _, fqsub := range item.State.TaintedBy {
ret = append(ret, fmt.Sprintf("\n-> %s\n", fqsub))
sub, err := hub.GetItemFQ(fqsub)
if err != nil {
ret = append(ret, err.Error())
}
diff, err := cli.itemDiff(sub, reverse)
if err != nil {
ret = append(ret, err.Error())
}
if diff != "" {
ret = append(ret, diff)
} else if len(sub.State.TaintedBy) > 0 {
taintList := strings.Join(sub.State.TaintedBy, ", ")
if sub.FQName() == taintList {
// hack: avoid message "item is tainted by itself"
continue
}
ret = append(ret, fmt.Sprintf("# %s is tainted by %s", sub.FQName(), taintList))
}
}
return strings.Join(ret, "\n")
}

183
cmd/crowdsec-cli/items.go Normal file
View file

@ -0,0 +1,183 @@
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)
// selectItems returns a slice of items of a given type, selected by name and sorted by case-insensitive name
func selectItems(hub *cwhub.Hub, itemType string, args []string, installedOnly bool) ([]*cwhub.Item, error) {
itemNames := hub.GetNamesByType(itemType)
notExist := []string{}
if len(args) > 0 {
for _, arg := range args {
if !slices.Contains(itemNames, arg) {
notExist = append(notExist, arg)
}
}
}
if len(notExist) > 0 {
return nil, fmt.Errorf("item(s) '%s' not found in %s", strings.Join(notExist, ", "), itemType)
}
if len(args) > 0 {
itemNames = args
installedOnly = false
}
items := make([]*cwhub.Item, 0, len(itemNames))
for _, itemName := range itemNames {
item := hub.GetItem(itemType, itemName)
if installedOnly && !item.State.Installed {
continue
}
items = append(items, item)
}
cwhub.SortItemSlice(items)
return items, nil
}
func listItems(out io.Writer, itemTypes []string, items map[string][]*cwhub.Item, omitIfEmpty bool) error {
switch csConfig.Cscli.Output {
case "human":
nothingToDisplay := true
for _, itemType := range itemTypes {
if omitIfEmpty && len(items[itemType]) == 0 {
continue
}
listHubItemTable(out, "\n"+strings.ToUpper(itemType), items[itemType])
nothingToDisplay = false
}
if nothingToDisplay {
fmt.Println("No items to display")
}
case "json":
type itemHubStatus struct {
Name string `json:"name"`
LocalVersion string `json:"local_version"`
LocalPath string `json:"local_path"`
Description string `json:"description"`
UTF8Status string `json:"utf8_status"`
Status string `json:"status"`
}
hubStatus := make(map[string][]itemHubStatus)
for _, itemType := range itemTypes {
// empty slice in case there are no items of this type
hubStatus[itemType] = make([]itemHubStatus, len(items[itemType]))
for i, item := range items[itemType] {
status := item.State.Text()
statusEmo := item.State.Emoji()
hubStatus[itemType][i] = itemHubStatus{
Name: item.Name,
LocalVersion: item.State.LocalVersion,
LocalPath: item.State.LocalPath,
Description: item.Description,
Status: status,
UTF8Status: fmt.Sprintf("%v %s", statusEmo, status),
}
}
}
x, err := json.MarshalIndent(hubStatus, "", " ")
if err != nil {
return fmt.Errorf("failed to unmarshal: %w", err)
}
out.Write(x)
case "raw":
csvwriter := csv.NewWriter(out)
header := []string{"name", "status", "version", "description"}
if len(itemTypes) > 1 {
header = append(header, "type")
}
if err := csvwriter.Write(header); err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
for _, itemType := range itemTypes {
for _, item := range items[itemType] {
row := []string{
item.Name,
item.State.Text(),
item.State.LocalVersion,
item.Description,
}
if len(itemTypes) > 1 {
row = append(row, itemType)
}
if err := csvwriter.Write(row); err != nil {
return fmt.Errorf("failed to write raw output: %w", err)
}
}
}
csvwriter.Flush()
}
return nil
}
func inspectItem(item *cwhub.Item, showMetrics bool) error {
switch csConfig.Cscli.Output {
case "human", "raw":
enc := yaml.NewEncoder(os.Stdout)
enc.SetIndent(2)
if err := enc.Encode(item); err != nil {
return fmt.Errorf("unable to encode item: %w", err)
}
case "json":
b, err := json.MarshalIndent(*item, "", " ")
if err != nil {
return fmt.Errorf("unable to marshal item: %w", err)
}
fmt.Print(string(b))
}
if csConfig.Cscli.Output != "human" {
return nil
}
if item.State.Tainted {
fmt.Println()
fmt.Printf(`This item is tainted. Use "%s %s inspect --diff %s" to see why.`, filepath.Base(os.Args[0]), item.Type, item.Name)
fmt.Println()
}
if showMetrics {
fmt.Printf("\nCurrent metrics: \n")
if err := ShowMetrics(item); err != nil {
return err
}
}
return nil
}

View file

@ -2,180 +2,631 @@ package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net/http/httputil"
"net/url"
"os"
"slices"
"sort"
"strings"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/alertcontext"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/exprhelpers"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/parser"
)
var LAPIURLPrefix string = "v1"
var lapiUser string
const LAPIURLPrefix = "v1"
func NewLapiCmd() *cobra.Command {
var cmdLapi = &cobra.Command{
Use: "lapi [action]",
Short: "Manage interaction with Local API (LAPI)",
Args: cobra.MinimumNArgs(1),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := csConfig.LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %s", err.Error())
}
if csConfig.API.Client == nil {
log.Fatalln("There is no API->client configuration")
}
if csConfig.API.Client.Credentials == nil {
log.Fatalf("no configuration for crowdsec API in '%s'", *csConfig.FilePath)
type cliLapi struct {
cfg configGetter
}
func NewCLILapi(cfg configGetter) *cliLapi {
return &cliLapi{
cfg: cfg,
}
}
func (cli *cliLapi) status() error {
cfg := cli.cfg()
password := strfmt.Password(cfg.API.Client.Credentials.Password)
login := cfg.API.Client.Credentials.Login
origURL := cfg.API.Client.Credentials.URL
apiURL, err := url.Parse(origURL)
if err != nil {
return fmt.Errorf("parsing api url: %w", err)
}
hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}
scenarios, err := hub.GetInstalledNamesByType(cwhub.SCENARIOS)
if err != nil {
return fmt.Errorf("failed to get scenarios: %w", err)
}
Client, err = apiclient.NewDefaultClient(apiURL,
LAPIURLPrefix,
fmt.Sprintf("crowdsec/%s", version.String()),
nil)
if err != nil {
return fmt.Errorf("init default client: %w", err)
}
t := models.WatcherAuthRequest{
MachineID: &login,
Password: &password,
Scenarios: scenarios,
}
log.Infof("Loaded credentials from %s", cfg.API.Client.CredentialsFilePath)
// use the original string because apiURL would print 'http://unix/'
log.Infof("Trying to authenticate with username %s on %s", login, origURL)
_, _, err = Client.Auth.AuthenticateWatcher(context.Background(), t)
if err != nil {
return fmt.Errorf("failed to authenticate to Local API (LAPI): %w", err)
}
log.Infof("You can successfully interact with Local API (LAPI)")
return nil
}
func (cli *cliLapi) register(apiURL string, outputFile string, machine string) error {
var err error
lapiUser := machine
cfg := cli.cfg()
if lapiUser == "" {
lapiUser, err = generateID("")
if err != nil {
return fmt.Errorf("unable to generate machine id: %w", err)
}
}
password := strfmt.Password(generatePassword(passwordLength))
apiurl, err := prepareAPIURL(cfg.API.Client, apiURL)
if err != nil {
return fmt.Errorf("parsing api url: %w", err)
}
_, err = apiclient.RegisterClient(&apiclient.Config{
MachineID: lapiUser,
Password: password,
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiurl,
VersionPrefix: LAPIURLPrefix,
}, nil)
if err != nil {
return fmt.Errorf("api client register: %w", err)
}
log.Printf("Successfully registered to Local API (LAPI)")
var dumpFile string
if outputFile != "" {
dumpFile = outputFile
} else if cfg.API.Client.CredentialsFilePath != "" {
dumpFile = cfg.API.Client.CredentialsFilePath
} else {
dumpFile = ""
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: lapiUser,
Password: password.String(),
URL: apiURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
return fmt.Errorf("unable to marshal api credentials: %w", err)
}
if dumpFile != "" {
err = os.WriteFile(dumpFile, apiConfigDump, 0o600)
if err != nil {
return fmt.Errorf("write api credentials to '%s' failed: %w", dumpFile, err)
}
log.Printf("Local API credentials written to '%s'", dumpFile)
} else {
fmt.Printf("%s\n", string(apiConfigDump))
}
log.Warning(ReloadMessage())
return nil
}
// prepareAPIURL checks/fixes a LAPI connection url (http, https or socket) and returns an URL struct
func prepareAPIURL(clientCfg *csconfig.LocalApiClientCfg, apiURL string) (*url.URL, error) {
if apiURL == "" {
if clientCfg == nil || clientCfg.Credentials == nil || clientCfg.Credentials.URL == "" {
return nil, errors.New("no Local API URL. Please provide it in your configuration or with the -u parameter")
}
apiURL = clientCfg.Credentials.URL
}
// URL needs to end with /, but user doesn't care
if !strings.HasSuffix(apiURL, "/") {
apiURL += "/"
}
// URL needs to start with http://, but user doesn't care
if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") && !strings.HasPrefix(apiURL, "/") {
apiURL = "http://" + apiURL
}
return url.Parse(apiURL)
}
func (cli *cliLapi) newStatusCmd() *cobra.Command {
cmdLapiStatus := &cobra.Command{
Use: "status",
Short: "Check authentication to Local API (LAPI)",
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.status()
},
}
return cmdLapiStatus
}
func (cli *cliLapi) newRegisterCmd() *cobra.Command {
var (
apiURL string
outputFile string
machine string
)
cmd := &cobra.Command{
Use: "register",
Short: "Register a machine to Local API (LAPI)",
Long: `Register your machine to the Local API (LAPI).
Keep in mind the machine needs to be validated by an administrator on LAPI side to be effective.`,
Args: cobra.MinimumNArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.register(apiURL, outputFile, machine)
},
}
flags := cmd.Flags()
flags.StringVarP(&apiURL, "url", "u", "", "URL of the API (ie. http://127.0.0.1)")
flags.StringVarP(&outputFile, "file", "f", "", "output file destination")
flags.StringVar(&machine, "machine", "", "Name of the machine to register with")
return cmd
}
func (cli *cliLapi) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "lapi [action]",
Short: "Manage interaction with Local API (LAPI)",
Args: cobra.MinimumNArgs(1),
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
if err := cli.cfg().LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %w", err)
}
return nil
},
}
var cmdLapiRegister = &cobra.Command{
Use: "register",
Short: "Register a machine to Local API (LAPI)",
Long: `Register you machine to the Local API (LAPI).
Keep in mind the machine needs to be validated by an administrator on LAPI side to be effective.`,
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var err error
if lapiUser == "" {
lapiUser, err = generateID()
if err != nil {
log.Fatalf("unable to generate machine id: %s", err)
}
}
password := strfmt.Password(generatePassword(passwordLength))
if apiURL == "" {
if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
apiURL = csConfig.API.Client.Credentials.URL
} else {
log.Fatalf("No Local API URL. Please provide it in your configuration or with the -u parameter")
}
}
/*URL needs to end with /, but user doesn't care*/
if !strings.HasSuffix(apiURL, "/") {
apiURL += "/"
}
/*URL needs to start with http://, but user doesn't care*/
if !strings.HasPrefix(apiURL, "http://") && !strings.HasPrefix(apiURL, "https://") {
apiURL = "http://" + apiURL
}
apiurl, err := url.Parse(apiURL)
if err != nil {
log.Fatalf("parsing api url: %s", err)
}
_, err = apiclient.RegisterClient(&apiclient.Config{
MachineID: lapiUser,
Password: password,
UserAgent: fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
URL: apiurl,
VersionPrefix: LAPIURLPrefix,
}, nil)
cmd.AddCommand(cli.newRegisterCmd())
cmd.AddCommand(cli.newStatusCmd())
cmd.AddCommand(cli.newContextCmd())
if err != nil {
log.Fatalf("api client register: %s", err)
}
log.Printf("Successfully registered to Local API (LAPI)")
var dumpFile string
if outputFile != "" {
dumpFile = outputFile
} else if csConfig.API.Client.CredentialsFilePath != "" {
dumpFile = csConfig.API.Client.CredentialsFilePath
} else {
dumpFile = ""
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: lapiUser,
Password: password.String(),
URL: apiURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
log.Fatalf("unable to marshal api credentials: %s", err)
}
if dumpFile != "" {
err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
if err != nil {
log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
}
log.Printf("Local API credentials dumped to '%s'", dumpFile)
} else {
fmt.Printf("%s\n", string(apiConfigDump))
}
log.Warningf(ReloadMessage())
},
}
cmdLapiRegister.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the API (ie. http://127.0.0.1)")
cmdLapiRegister.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination")
cmdLapiRegister.Flags().StringVar(&lapiUser, "machine", "", "Name of the machine to register with")
cmdLapi.AddCommand(cmdLapiRegister)
var cmdLapiStatus = &cobra.Command{
Use: "status",
Short: "Check authentication to Local API (LAPI)",
Args: cobra.MinimumNArgs(0),
Run: func(cmd *cobra.Command, args []string) {
var err error
password := strfmt.Password(csConfig.API.Client.Credentials.Password)
apiurl, err := url.Parse(csConfig.API.Client.Credentials.URL)
login := csConfig.API.Client.Credentials.Login
if err != nil {
log.Fatalf("parsing api url ('%s'): %s", apiurl, err)
}
if err := csConfig.LoadHub(); err != nil {
log.Fatalf(err.Error())
}
if err := cwhub.GetHubIdx(csConfig.Hub); err != nil {
log.Fatalf("Failed to load hub index : %s", err)
log.Infoln("Run 'sudo cscli hub update' to get the hub index")
}
scenarios, err := cwhub.GetUpstreamInstalledScenariosAsString()
if err != nil {
log.Fatalf("failed to get scenarios : %s", err.Error())
}
Client, err = apiclient.NewDefaultClient(apiurl,
LAPIURLPrefix,
fmt.Sprintf("crowdsec/%s", cwversion.VersionStr()),
nil)
if err != nil {
log.Fatalf("init default client: %s", err)
}
t := models.WatcherAuthRequest{
MachineID: &login,
Password: &password,
Scenarios: scenarios,
}
log.Infof("Loaded credentials from %s", csConfig.API.Client.CredentialsFilePath)
log.Infof("Trying to authenticate with username %s on %s", login, apiurl)
resp, err := Client.Auth.AuthenticateWatcher(context.Background(), t)
if err != nil {
log.Fatalf("Failed to authenticate to Local API (LAPI) : %s", err)
} else {
log.Infof("You can successfully interact with Local API (LAPI)")
}
for k, v := range resp.Response.Header {
log.Debugf("[headers] %s : %s", k, v)
}
dump, _ := httputil.DumpResponse(resp.Response, true)
log.Debugf("Response: %s", string(dump))
},
}
cmdLapi.AddCommand(cmdLapiStatus)
return cmdLapi
return cmd
}
func (cli *cliLapi) addContext(key string, values []string) error {
cfg := cli.cfg()
if err := alertcontext.ValidateContextExpr(key, values); err != nil {
return fmt.Errorf("invalid context configuration: %w", err)
}
if _, ok := cfg.Crowdsec.ContextToSend[key]; !ok {
cfg.Crowdsec.ContextToSend[key] = make([]string, 0)
log.Infof("key '%s' added", key)
}
data := cfg.Crowdsec.ContextToSend[key]
for _, val := range values {
if !slices.Contains(data, val) {
log.Infof("value '%s' added to key '%s'", val, key)
data = append(data, val)
}
cfg.Crowdsec.ContextToSend[key] = data
}
if err := cfg.Crowdsec.DumpContextConfigFile(); err != nil {
return err
}
return nil
}
func (cli *cliLapi) newContextAddCmd() *cobra.Command {
var (
keyToAdd string
valuesToAdd []string
)
cmd := &cobra.Command{
Use: "add",
Short: "Add context to send with alerts. You must specify the output key with the expr value you want",
Example: `cscli lapi context add --key source_ip --value evt.Meta.source_ip
cscli lapi context add --key file_source --value evt.Line.Src
cscli lapi context add --value evt.Meta.source_ip --value evt.Meta.target_user
`,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
hub, err := require.Hub(cli.cfg(), nil, nil)
if err != nil {
return err
}
if err = alertcontext.LoadConsoleContext(cli.cfg(), hub); err != nil {
return fmt.Errorf("while loading context: %w", err)
}
if keyToAdd != "" {
if err := cli.addContext(keyToAdd, valuesToAdd); err != nil {
return err
}
return nil
}
for _, v := range valuesToAdd {
keySlice := strings.Split(v, ".")
key := keySlice[len(keySlice)-1]
value := []string{v}
if err := cli.addContext(key, value); err != nil {
return err
}
}
return nil
},
}
flags := cmd.Flags()
flags.StringVarP(&keyToAdd, "key", "k", "", "The key of the different values to send")
flags.StringSliceVar(&valuesToAdd, "value", []string{}, "The expr fields to associate with the key")
cmd.MarkFlagRequired("value")
return cmd
}
func (cli *cliLapi) newContextStatusCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "List context to send with alerts",
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}
if err = alertcontext.LoadConsoleContext(cfg, hub); err != nil {
return fmt.Errorf("while loading context: %w", err)
}
if len(cfg.Crowdsec.ContextToSend) == 0 {
fmt.Println("No context found on this agent. You can use 'cscli lapi context add' to add context to your alerts.")
return nil
}
dump, err := yaml.Marshal(cfg.Crowdsec.ContextToSend)
if err != nil {
return fmt.Errorf("unable to show context status: %w", err)
}
fmt.Print(string(dump))
return nil
},
}
return cmd
}
func (cli *cliLapi) newContextDetectCmd() *cobra.Command {
var detectAll bool
cmd := &cobra.Command{
Use: "detect",
Short: "Detect available fields from the installed parsers",
Example: `cscli lapi context detect --all
cscli lapi context detect crowdsecurity/sshd-logs
`,
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
cfg := cli.cfg()
if !detectAll && len(args) == 0 {
log.Infof("Please provide parsers to detect or --all flag.")
printHelp(cmd)
}
// to avoid all the log.Info from the loaders functions
log.SetLevel(log.WarnLevel)
if err := exprhelpers.Init(nil); err != nil {
return fmt.Errorf("failed to init expr helpers: %w", err)
}
hub, err := require.Hub(cfg, nil, nil)
if err != nil {
return err
}
csParsers := parser.NewParsers(hub)
if csParsers, err = parser.LoadParsers(cfg, csParsers); err != nil {
return fmt.Errorf("unable to load parsers: %w", err)
}
fieldByParsers := make(map[string][]string)
for _, node := range csParsers.Nodes {
if !detectAll && !slices.Contains(args, node.Name) {
continue
}
if !detectAll {
args = removeFromSlice(node.Name, args)
}
fieldByParsers[node.Name] = make([]string, 0)
fieldByParsers[node.Name] = detectNode(node, *csParsers.Ctx)
subNodeFields := detectSubNode(node, *csParsers.Ctx)
for _, field := range subNodeFields {
if !slices.Contains(fieldByParsers[node.Name], field) {
fieldByParsers[node.Name] = append(fieldByParsers[node.Name], field)
}
}
}
fmt.Printf("Acquisition :\n\n")
fmt.Printf(" - evt.Line.Module\n")
fmt.Printf(" - evt.Line.Raw\n")
fmt.Printf(" - evt.Line.Src\n")
fmt.Println()
parsersKey := make([]string, 0)
for k := range fieldByParsers {
parsersKey = append(parsersKey, k)
}
sort.Strings(parsersKey)
for _, k := range parsersKey {
if len(fieldByParsers[k]) == 0 {
continue
}
fmt.Printf("%s :\n\n", k)
values := fieldByParsers[k]
sort.Strings(values)
for _, value := range values {
fmt.Printf(" - %s\n", value)
}
fmt.Println()
}
if len(args) > 0 {
for _, parserNotFound := range args {
log.Errorf("parser '%s' not found, can't detect fields", parserNotFound)
}
}
return nil
},
}
cmd.Flags().BoolVarP(&detectAll, "all", "a", false, "Detect evt field for all installed parser")
return cmd
}
func (cli *cliLapi) newContextDeleteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "delete",
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
filePath := cli.cfg().Crowdsec.ConsoleContextPath
if filePath == "" {
filePath = "the context file"
}
fmt.Printf("Command 'delete' is deprecated, please manually edit %s.", filePath)
return nil
},
}
return cmd
}
func (cli *cliLapi) newContextCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "context [command]",
Short: "Manage context to send with alerts",
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := cfg.LoadCrowdsec(); err != nil {
fileNotFoundMessage := fmt.Sprintf("failed to open context file: open %s: no such file or directory", cfg.Crowdsec.ConsoleContextPath)
if err.Error() != fileNotFoundMessage {
return fmt.Errorf("unable to load CrowdSec agent configuration: %w", err)
}
}
if cfg.DisableAgent {
return errors.New("agent is disabled and lapi context can only be used on the agent")
}
return nil
},
Run: func(cmd *cobra.Command, _ []string) {
printHelp(cmd)
},
}
cmd.AddCommand(cli.newContextAddCmd())
cmd.AddCommand(cli.newContextStatusCmd())
cmd.AddCommand(cli.newContextDetectCmd())
cmd.AddCommand(cli.newContextDeleteCmd())
return cmd
}
func detectStaticField(grokStatics []parser.ExtraField) []string {
ret := make([]string, 0)
for _, static := range grokStatics {
if static.Parsed != "" {
fieldName := fmt.Sprintf("evt.Parsed.%s", static.Parsed)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
if static.Meta != "" {
fieldName := fmt.Sprintf("evt.Meta.%s", static.Meta)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
if static.TargetByName != "" {
fieldName := static.TargetByName
if !strings.HasPrefix(fieldName, "evt.") {
fieldName = "evt." + fieldName
}
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
}
return ret
}
func detectNode(node parser.Node, parserCTX parser.UnixParserCtx) []string {
ret := make([]string, 0)
if node.Grok.RunTimeRegexp != nil {
for _, capturedField := range node.Grok.RunTimeRegexp.Names() {
fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
}
if node.Grok.RegexpName != "" {
grokCompiled, err := parserCTX.Grok.Get(node.Grok.RegexpName)
// ignore error (parser does not exist?)
if err == nil {
for _, capturedField := range grokCompiled.Names() {
fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
}
}
if len(node.Grok.Statics) > 0 {
staticsField := detectStaticField(node.Grok.Statics)
for _, staticField := range staticsField {
if !slices.Contains(ret, staticField) {
ret = append(ret, staticField)
}
}
}
if len(node.Statics) > 0 {
staticsField := detectStaticField(node.Statics)
for _, staticField := range staticsField {
if !slices.Contains(ret, staticField) {
ret = append(ret, staticField)
}
}
}
return ret
}
func detectSubNode(node parser.Node, parserCTX parser.UnixParserCtx) []string {
ret := make([]string, 0)
for _, subnode := range node.LeavesNodes {
if subnode.Grok.RunTimeRegexp != nil {
for _, capturedField := range subnode.Grok.RunTimeRegexp.Names() {
fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
}
if subnode.Grok.RegexpName != "" {
grokCompiled, err := parserCTX.Grok.Get(subnode.Grok.RegexpName)
if err == nil {
// ignore error (parser does not exist?)
for _, capturedField := range grokCompiled.Names() {
fieldName := fmt.Sprintf("evt.Parsed.%s", capturedField)
if !slices.Contains(ret, fieldName) {
ret = append(ret, fieldName)
}
}
}
}
if len(subnode.Grok.Statics) > 0 {
staticsField := detectStaticField(subnode.Grok.Statics)
for _, staticField := range staticsField {
if !slices.Contains(ret, staticField) {
ret = append(ret, staticField)
}
}
}
if len(subnode.Statics) > 0 {
staticsField := detectStaticField(subnode.Statics)
for _, staticField := range staticsField {
if !slices.Contains(ret, staticField) {
ret = append(ret, staticField)
}
}
}
}
return ret
}

View file

@ -0,0 +1,49 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
)
func TestPrepareAPIURL_NoProtocol(t *testing.T) {
url, err := prepareAPIURL(nil, "localhost:81")
require.NoError(t, err)
assert.Equal(t, "http://localhost:81/", url.String())
}
func TestPrepareAPIURL_Http(t *testing.T) {
url, err := prepareAPIURL(nil, "http://localhost:81")
require.NoError(t, err)
assert.Equal(t, "http://localhost:81/", url.String())
}
func TestPrepareAPIURL_Https(t *testing.T) {
url, err := prepareAPIURL(nil, "https://localhost:81")
require.NoError(t, err)
assert.Equal(t, "https://localhost:81/", url.String())
}
func TestPrepareAPIURL_UnixSocket(t *testing.T) {
url, err := prepareAPIURL(nil, "/path/socket")
require.NoError(t, err)
assert.Equal(t, "/path/socket/", url.String())
}
func TestPrepareAPIURL_Empty(t *testing.T) {
_, err := prepareAPIURL(nil, "")
require.Error(t, err)
}
func TestPrepareAPIURL_Empty_ConfigOverride(t *testing.T) {
url, err := prepareAPIURL(&csconfig.LocalApiClientCfg{
Credentials: &csconfig.ApiCredentialsCfg{
URL: "localhost:80",
},
}, "")
require.NoError(t, err)
assert.Equal(t, "http://localhost:80/", url.String())
}

View file

@ -2,310 +2,504 @@ package main
import (
saferand "crypto/rand"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"slices"
"strings"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/denisbrodbeck/machineid"
"github.com/enescakir/emoji"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
"github.com/olekukonko/tablewriter"
"github.com/pkg/errors"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v2"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/machineid"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
var machineID string
var machinePassword string
var interactive bool
var apiURL string
var outputFile string
var forceAdd bool
var autoAdd bool
var (
passwordLength = 64
upper = "ABCDEFGHIJKLMNOPQRSTUVWXY"
lower = "abcdefghijklmnopqrstuvwxyz"
digits = "0123456789"
)
const (
uuid = "/proc/sys/kernel/random/uuid"
)
const passwordLength = 64
func generatePassword(length int) string {
upper := "ABCDEFGHIJKLMNOPQRSTUVWXY"
lower := "abcdefghijklmnopqrstuvwxyz"
digits := "0123456789"
charset := upper + lower + digits
charsetLength := len(charset)
buf := make([]byte, length)
for i := 0; i < length; i++ {
rInt, err := saferand.Int(saferand.Reader, big.NewInt(int64(charsetLength)))
if err != nil {
log.Fatalf("failed getting data from prng for password generation : %s", err)
}
buf[i] = charset[rInt.Int64()]
}
return string(buf)
}
func generateID() (string, error) {
id, err := machineid.ID()
if err != nil {
log.Debugf("failed to get machine-id with usual files : %s", err)
// Returns a unique identifier for each crowdsec installation, using an
// identifier of the OS installation where available, otherwise a random
// string.
func generateIDPrefix() (string, error) {
prefix, err := machineid.ID()
if err == nil {
return prefix, nil
}
if id == "" || err != nil {
bID, err := ioutil.ReadFile(uuid)
if err != nil {
return "", errors.Wrap(err, "generating machine id")
}
id = string(bID)
log.Debugf("failed to get machine-id with usual files: %s", err)
bID, err := uuid.NewRandom()
if err == nil {
return bID.String(), nil
}
id = strings.ReplaceAll(id, "-", "")[:32]
id = fmt.Sprintf("%s%s", id, generatePassword(16))
return id, nil
return "", fmt.Errorf("generating machine id: %w", err)
}
func NewMachinesCmd() *cobra.Command {
/* ---- DECISIONS COMMAND */
var cmdMachines = &cobra.Command{
// Generate a unique identifier, composed by a prefix and a random suffix.
// The prefix can be provided by a parameter to use in test environments.
func generateID(prefix string) (string, error) {
var err error
if prefix == "" {
prefix, err = generateIDPrefix()
}
if err != nil {
return "", err
}
prefix = strings.ReplaceAll(prefix, "-", "")[:32]
suffix := generatePassword(16)
return prefix + suffix, nil
}
// getLastHeartbeat returns the last heartbeat timestamp of a machine
// and a boolean indicating if the machine is considered active or not.
func getLastHeartbeat(m *ent.Machine) (string, bool) {
if m.LastHeartbeat == nil {
return "-", false
}
elapsed := time.Now().UTC().Sub(*m.LastHeartbeat)
hb := elapsed.Truncate(time.Second).String()
if elapsed > 2*time.Minute {
return hb, false
}
return hb, true
}
type cliMachines struct {
db *database.Client
cfg configGetter
}
func NewCLIMachines(cfg configGetter) *cliMachines {
return &cliMachines{
cfg: cfg,
}
}
func (cli *cliMachines) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "machines [action]",
Short: "Manage local API machines [requires local API]",
Long: `To list/add/delete/validate machines.
Long: `To list/add/delete/validate/prune machines.
Note: This command requires database direct access, so is intended to be run on the local API machine.
`,
Example: `cscli machines [action]`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
if err := csConfig.LoadAPIServer(); err != nil || csConfig.DisableAPI {
log.Fatal("Local API is disabled, please run this command on the local API machine")
}
if err := csConfig.LoadDBConfig(); err != nil {
log.Errorf("This command requires direct database access (must be run on the local API machine)")
log.Fatalf(err.Error())
}
},
}
var cmdMachinesList = &cobra.Command{
Use: "list",
Short: "List machines",
Long: `List `,
Example: `cscli machines list`,
Args: cobra.MaximumNArgs(1),
PreRun: func(cmd *cobra.Command, args []string) {
Example: `cscli machines [action]`,
DisableAutoGenTag: true,
Aliases: []string{"machine"},
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
var err error
dbClient, err = database.NewClient(csConfig.DbConfig)
if err != nil {
log.Fatalf("unable to create new database client: %s", err)
if err = require.LAPI(cli.cfg()); err != nil {
return err
}
},
Run: func(cmd *cobra.Command, args []string) {
machines, err := dbClient.ListMachines()
cli.db, err = database.NewClient(cli.cfg().DbConfig)
if err != nil {
log.Errorf("unable to list blockers: %s", err)
return fmt.Errorf("unable to create new database client: %w", err)
}
if csConfig.Cscli.Output == "human" {
table := tablewriter.NewWriter(os.Stdout)
table.SetCenterSeparator("")
table.SetColumnSeparator("")
table.SetHeaderAlignment(tablewriter.ALIGN_LEFT)
table.SetAlignment(tablewriter.ALIGN_LEFT)
table.SetHeader([]string{"Name", "IP Address", "Last Update", "Status", "Version"})
for _, w := range machines {
var validated string
if w.IsValidated {
validated = fmt.Sprintf("%s", emoji.CheckMark)
} else {
validated = fmt.Sprintf("%s", emoji.Prohibited)
}
table.Append([]string{w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version})
}
table.Render()
} else if csConfig.Cscli.Output == "json" {
x, err := json.MarshalIndent(machines, "", " ")
if err != nil {
log.Fatalf("failed to unmarshal")
}
fmt.Printf("%s", string(x))
} else if csConfig.Cscli.Output == "raw" {
for _, w := range machines {
var validated string
if w.IsValidated {
validated = "true"
} else {
validated = "false"
}
fmt.Printf("%s,%s,%s,%s,%s\n", w.MachineId, w.IpAddress, w.UpdatedAt.Format(time.RFC3339), validated, w.Version)
}
} else {
log.Errorf("unknown output '%s'", csConfig.Cscli.Output)
}
return nil
},
}
cmdMachines.AddCommand(cmdMachinesList)
var cmdMachinesAdd = &cobra.Command{
Use: "add",
Short: "add machine to the database.",
Long: `Register a new machine in the database. cscli should be on the same machine as LAPI.`,
Example: `
cscli machines add --auto
cmd.AddCommand(cli.newListCmd())
cmd.AddCommand(cli.newAddCmd())
cmd.AddCommand(cli.newDeleteCmd())
cmd.AddCommand(cli.newValidateCmd())
cmd.AddCommand(cli.newPruneCmd())
return cmd
}
func (cli *cliMachines) list() error {
out := color.Output
machines, err := cli.db.ListMachines()
if err != nil {
return fmt.Errorf("unable to list machines: %w", err)
}
switch cli.cfg().Cscli.Output {
case "human":
getAgentsTable(out, machines)
case "json":
enc := json.NewEncoder(out)
enc.SetIndent("", " ")
if err := enc.Encode(machines); err != nil {
return errors.New("failed to marshal")
}
return nil
case "raw":
csvwriter := csv.NewWriter(out)
err := csvwriter.Write([]string{"machine_id", "ip_address", "updated_at", "validated", "version", "auth_type", "last_heartbeat"})
if err != nil {
return fmt.Errorf("failed to write header: %w", err)
}
for _, m := range machines {
validated := "false"
if m.IsValidated {
validated = "true"
}
hb, _ := getLastHeartbeat(m)
if err := csvwriter.Write([]string{m.MachineId, m.IpAddress, m.UpdatedAt.Format(time.RFC3339), validated, m.Version, m.AuthType, hb}); err != nil {
return fmt.Errorf("failed to write raw output: %w", err)
}
}
csvwriter.Flush()
}
return nil
}
func (cli *cliMachines) newListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list all machines in the database",
Long: `list all machines in the database with their status and last heartbeat`,
Example: `cscli machines list`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list()
},
}
return cmd
}
func (cli *cliMachines) newAddCmd() *cobra.Command {
var (
password MachinePassword
dumpFile string
apiURL string
interactive bool
autoAdd bool
force bool
)
cmd := &cobra.Command{
Use: "add",
Short: "add a single machine to the database",
DisableAutoGenTag: true,
Long: `Register a new machine in the database. cscli should be on the same machine as LAPI.`,
Example: `cscli machines add --auto
cscli machines add MyTestMachine --auto
cscli machines add MyTestMachine --password MyPassword
`,
PreRun: func(cmd *cobra.Command, args []string) {
var err error
dbClient, err = database.NewClient(csConfig.DbConfig)
if err != nil {
log.Fatalf("unable to create new database client: %s", err)
}
},
Run: func(cmd *cobra.Command, args []string) {
var dumpFile string
var err error
// create machineID if doesn't specified by user
if len(args) == 0 {
if !autoAdd {
err = cmd.Help()
if err != nil {
log.Fatalf("unable to print help(): %s", err)
}
return
}
machineID, err = generateID()
if err != nil {
log.Fatalf("unable to generate machine id : %s", err)
}
} else {
machineID = args[0]
}
/*check if file already exists*/
if outputFile != "" {
dumpFile = outputFile
} else if csConfig.API.Client.CredentialsFilePath != "" {
dumpFile = csConfig.API.Client.CredentialsFilePath
}
// create password if doesn't specified by user
if machinePassword == "" && !interactive {
if !autoAdd {
err = cmd.Help()
if err != nil {
log.Fatalf("unable to print help(): %s", err)
}
return
}
machinePassword = generatePassword(passwordLength)
} else if machinePassword == "" && interactive {
qs := &survey.Password{
Message: "Please provide a password for the machine",
}
survey.AskOne(qs, &machinePassword)
}
password := strfmt.Password(machinePassword)
_, err = dbClient.CreateMachine(&machineID, &password, "", true, forceAdd)
if err != nil {
log.Fatalf("unable to create machine: %s", err)
}
log.Infof("Machine '%s' successfully added to the local API", machineID)
if apiURL == "" {
if csConfig.API.Client != nil && csConfig.API.Client.Credentials != nil && csConfig.API.Client.Credentials.URL != "" {
apiURL = csConfig.API.Client.Credentials.URL
} else if csConfig.API.Server != nil && csConfig.API.Server.ListenURI != "" {
apiURL = "http://" + csConfig.API.Server.ListenURI
} else {
log.Fatalf("unable to dump an api URL. Please provide it in your configuration or with the -u parameter")
}
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: machineID,
Password: password.String(),
URL: apiURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
log.Fatalf("unable to marshal api credentials: %s", err)
}
if dumpFile != "" {
err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
if err != nil {
log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
}
log.Printf("API credentials dumped to '%s'", dumpFile)
} else {
fmt.Printf("%s\n", string(apiConfigDump))
}
cscli machines add -f- --auto > /tmp/mycreds.yaml`,
RunE: func(_ *cobra.Command, args []string) error {
return cli.add(args, string(password), dumpFile, apiURL, interactive, autoAdd, force)
},
}
cmdMachinesAdd.Flags().StringVarP(&machinePassword, "password", "p", "", "machine password to login to the API")
cmdMachinesAdd.Flags().StringVarP(&outputFile, "file", "f", "", "output file destination (defaults to /etc/crowdsec/local_api_credentials.yaml)")
cmdMachinesAdd.Flags().StringVarP(&apiURL, "url", "u", "", "URL of the local API")
cmdMachinesAdd.Flags().BoolVarP(&interactive, "interactive", "i", false, "interfactive mode to enter the password")
cmdMachinesAdd.Flags().BoolVarP(&autoAdd, "auto", "a", false, "automatically generate password (and username if not provided)")
cmdMachinesAdd.Flags().BoolVar(&forceAdd, "force", false, "will force add the machine if it already exist")
cmdMachines.AddCommand(cmdMachinesAdd)
var cmdMachinesDelete = &cobra.Command{
Use: "delete --machine MyTestMachine",
Short: "delete machines",
Example: `cscli machines delete <machine_name>`,
Args: cobra.ExactArgs(1),
PreRun: func(cmd *cobra.Command, args []string) {
var err error
dbClient, err = database.NewClient(csConfig.DbConfig)
if err != nil {
log.Fatalf("unable to create new database client: %s", err)
}
},
Run: func(cmd *cobra.Command, args []string) {
machineID = args[0]
err := dbClient.DeleteWatcher(machineID)
if err != nil {
log.Errorf("unable to delete machine: %s", err)
return
}
log.Infof("machine '%s' deleted successfully", machineID)
},
}
cmdMachinesDelete.Flags().StringVarP(&machineID, "machine", "m", "", "machine to delete")
cmdMachines.AddCommand(cmdMachinesDelete)
flags := cmd.Flags()
flags.VarP(&password, "password", "p", "machine password to login to the API")
flags.StringVarP(&dumpFile, "file", "f", "", "output file destination (defaults to "+csconfig.DefaultConfigPath("local_api_credentials.yaml")+")")
flags.StringVarP(&apiURL, "url", "u", "", "URL of the local API")
flags.BoolVarP(&interactive, "interactive", "i", false, "interfactive mode to enter the password")
flags.BoolVarP(&autoAdd, "auto", "a", false, "automatically generate password (and username if not provided)")
flags.BoolVar(&force, "force", false, "will force add the machine if it already exist")
var cmdMachinesValidate = &cobra.Command{
Use: "validate",
Short: "validate a machine to access the local API",
Long: `validate a machine to access the local API.`,
Example: `cscli machines validate <machine_name>`,
Args: cobra.ExactArgs(1),
PreRun: func(cmd *cobra.Command, args []string) {
var err error
dbClient, err = database.NewClient(csConfig.DbConfig)
if err != nil {
log.Fatalf("unable to create new database client: %s", err)
}
},
Run: func(cmd *cobra.Command, args []string) {
machineID = args[0]
if err := dbClient.ValidateMachine(machineID); err != nil {
log.Fatalf("unable to validate machine '%s': %s", machineID, err)
}
log.Infof("machine '%s' validated successfuly", machineID)
},
}
cmdMachines.AddCommand(cmdMachinesValidate)
return cmdMachines
return cmd
}
func (cli *cliMachines) add(args []string, machinePassword string, dumpFile string, apiURL string, interactive bool, autoAdd bool, force bool) error {
var (
err error
machineID string
)
// create machineID if not specified by user
if len(args) == 0 {
if !autoAdd {
return errors.New("please specify a machine name to add, or use --auto")
}
machineID, err = generateID("")
if err != nil {
return fmt.Errorf("unable to generate machine id: %w", err)
}
} else {
machineID = args[0]
}
clientCfg := cli.cfg().API.Client
serverCfg := cli.cfg().API.Server
/*check if file already exists*/
if dumpFile == "" && clientCfg != nil && clientCfg.CredentialsFilePath != "" {
credFile := clientCfg.CredentialsFilePath
// use the default only if the file does not exist
_, err = os.Stat(credFile)
switch {
case os.IsNotExist(err) || force:
dumpFile = credFile
case err != nil:
return fmt.Errorf("unable to stat '%s': %w", credFile, err)
default:
return fmt.Errorf(`credentials file '%s' already exists: please remove it, use "--force" or specify a different file with "-f" ("-f -" for standard output)`, credFile)
}
}
if dumpFile == "" {
return errors.New(`please specify a file to dump credentials to, with -f ("-f -" for standard output)`)
}
// create a password if it's not specified by user
if machinePassword == "" && !interactive {
if !autoAdd {
return errors.New("please specify a password with --password or use --auto")
}
machinePassword = generatePassword(passwordLength)
} else if machinePassword == "" && interactive {
qs := &survey.Password{
Message: "Please provide a password for the machine:",
}
survey.AskOne(qs, &machinePassword)
}
password := strfmt.Password(machinePassword)
_, err = cli.db.CreateMachine(&machineID, &password, "", true, force, types.PasswordAuthType)
if err != nil {
return fmt.Errorf("unable to create machine: %w", err)
}
fmt.Fprintf(os.Stderr, "Machine '%s' successfully added to the local API.\n", machineID)
if apiURL == "" {
if clientCfg != nil && clientCfg.Credentials != nil && clientCfg.Credentials.URL != "" {
apiURL = clientCfg.Credentials.URL
} else if serverCfg.ClientURL() != "" {
apiURL = serverCfg.ClientURL()
} else {
return errors.New("unable to dump an api URL. Please provide it in your configuration or with the -u parameter")
}
}
apiCfg := csconfig.ApiCredentialsCfg{
Login: machineID,
Password: password.String(),
URL: apiURL,
}
apiConfigDump, err := yaml.Marshal(apiCfg)
if err != nil {
return fmt.Errorf("unable to marshal api credentials: %w", err)
}
if dumpFile != "" && dumpFile != "-" {
if err = os.WriteFile(dumpFile, apiConfigDump, 0o600); err != nil {
return fmt.Errorf("write api credentials in '%s' failed: %w", dumpFile, err)
}
fmt.Fprintf(os.Stderr, "API credentials written to '%s'.\n", dumpFile)
} else {
fmt.Print(string(apiConfigDump))
}
return nil
}
func (cli *cliMachines) deleteValid(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
machines, err := cli.db.ListMachines()
if err != nil {
cobra.CompError("unable to list machines " + err.Error())
}
ret := []string{}
for _, machine := range machines {
if strings.Contains(machine.MachineId, toComplete) && !slices.Contains(args, machine.MachineId) {
ret = append(ret, machine.MachineId)
}
}
return ret, cobra.ShellCompDirectiveNoFileComp
}
func (cli *cliMachines) delete(machines []string) error {
for _, machineID := range machines {
if err := cli.db.DeleteWatcher(machineID); err != nil {
log.Errorf("unable to delete machine '%s': %s", machineID, err)
return nil
}
log.Infof("machine '%s' deleted successfully", machineID)
}
return nil
}
func (cli *cliMachines) newDeleteCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "delete [machine_name]...",
Short: "delete machine(s) by name",
Example: `cscli machines delete "machine1" "machine2"`,
Args: cobra.MinimumNArgs(1),
Aliases: []string{"remove"},
DisableAutoGenTag: true,
ValidArgsFunction: cli.deleteValid,
RunE: func(_ *cobra.Command, args []string) error {
return cli.delete(args)
},
}
return cmd
}
func (cli *cliMachines) prune(duration time.Duration, notValidOnly bool, force bool) error {
if duration < 2*time.Minute && !notValidOnly {
if yes, err := askYesNo(
"The duration you provided is less than 2 minutes. " +
"This can break installations if the machines are only temporarily disconnected. Continue?", false); err != nil {
return err
} else if !yes {
fmt.Println("User aborted prune. No changes were made.")
return nil
}
}
machines := []*ent.Machine{}
if pending, err := cli.db.QueryPendingMachine(); err == nil {
machines = append(machines, pending...)
}
if !notValidOnly {
if pending, err := cli.db.QueryLastValidatedHeartbeatLT(time.Now().UTC().Add(-duration)); err == nil {
machines = append(machines, pending...)
}
}
if len(machines) == 0 {
fmt.Println("No machines to prune.")
return nil
}
getAgentsTable(color.Output, machines)
if !force {
if yes, err := askYesNo(
"You are about to PERMANENTLY remove the above machines from the database. " +
"These will NOT be recoverable. Continue?", false); err != nil {
return err
} else if !yes {
fmt.Println("User aborted prune. No changes were made.")
return nil
}
}
deleted, err := cli.db.BulkDeleteWatchers(machines)
if err != nil {
return fmt.Errorf("unable to prune machines: %w", err)
}
fmt.Fprintf(os.Stderr, "successfully delete %d machines\n", deleted)
return nil
}
func (cli *cliMachines) newPruneCmd() *cobra.Command {
var (
duration time.Duration
notValidOnly bool
force bool
)
const defaultDuration = 10 * time.Minute
cmd := &cobra.Command{
Use: "prune",
Short: "prune multiple machines from the database",
Long: `prune multiple machines that are not validated or have not connected to the local API in a given duration.`,
Example: `cscli machines prune
cscli machines prune --duration 1h
cscli machines prune --not-validated-only --force`,
Args: cobra.NoArgs,
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.prune(duration, notValidOnly, force)
},
}
flags := cmd.Flags()
flags.DurationVarP(&duration, "duration", "d", defaultDuration, "duration of time since validated machine last heartbeat")
flags.BoolVar(&notValidOnly, "not-validated-only", false, "only prune machines that are not validated")
flags.BoolVar(&force, "force", false, "force prune without asking for confirmation")
return cmd
}
func (cli *cliMachines) validate(machineID string) error {
if err := cli.db.ValidateMachine(machineID); err != nil {
return fmt.Errorf("unable to validate machine '%s': %w", machineID, err)
}
log.Infof("machine '%s' validated successfully", machineID)
return nil
}
func (cli *cliMachines) newValidateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "validate",
Short: "validate a machine to access the local API",
Long: `validate a machine to access the local API.`,
Example: `cscli machines validate "machine_name"`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
return cli.validate(args[0])
},
}
return cmd
}

View file

@ -0,0 +1,34 @@
package main
import (
"io"
"time"
"github.com/aquasecurity/table"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/emoji"
)
func getAgentsTable(out io.Writer, machines []*ent.Machine) {
t := newLightTable(out)
t.SetHeaders("Name", "IP Address", "Last Update", "Status", "Version", "Auth Type", "Last Heartbeat")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
for _, m := range machines {
validated := emoji.Prohibited
if m.IsValidated {
validated = emoji.CheckMark
}
hb, active := getLastHeartbeat(m)
if !active {
hb = emoji.Warning + " " + hb
}
t.AddRow(m.MachineId, m.IpAddress, m.UpdatedAt.Format(time.RFC3339), validated, m.Version, m.AuthType, hb)
}
t.Render()
}

View file

@ -1,73 +1,137 @@
package main
import (
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/database"
"fmt"
"os"
"path/filepath"
"slices"
"time"
"github.com/fatih/color"
cc "github.com/ivanpirog/coloredcobra"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/cobra/doc"
"github.com/crowdsecurity/go-cs-lib/trace"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
)
var trace_lvl, dbg_lvl, nfo_lvl, wrn_lvl, err_lvl bool
var (
ConfigFilePath string
csConfig *csconfig.Config
dbClient *database.Client
)
var ConfigFilePath string
var csConfig *csconfig.Config
var dbClient *database.Client
type configGetter func() *csconfig.Config
var OutputFormat string
var mergedConfig string
var downloadOnly bool
var forceAction bool
var purge bool
var all bool
var restoreOldBackup bool
type cliRoot struct {
logTrace bool
logDebug bool
logInfo bool
logWarn bool
logErr bool
outputColor string
outputFormat string
// flagBranch overrides the value in csConfig.Cscli.HubBranch
flagBranch string
}
var prometheusURL string
func newCliRoot() *cliRoot {
return &cliRoot{}
}
func initConfig() {
var err error
if trace_lvl {
log.SetLevel(log.TraceLevel)
} else if dbg_lvl {
log.SetLevel(log.DebugLevel)
} else if nfo_lvl {
log.SetLevel(log.InfoLevel)
} else if wrn_lvl {
log.SetLevel(log.WarnLevel)
} else if err_lvl {
log.SetLevel(log.ErrorLevel)
// cfg() is a helper function to get the configuration loaded from config.yaml,
// we pass it to subcommands because the file is not read until the Execute() call
func (cli *cliRoot) cfg() *csconfig.Config {
return csConfig
}
// wantedLogLevel returns the log level requested in the command line flags.
func (cli *cliRoot) wantedLogLevel() log.Level {
switch {
case cli.logTrace:
return log.TraceLevel
case cli.logDebug:
return log.DebugLevel
case cli.logInfo:
return log.InfoLevel
case cli.logWarn:
return log.WarnLevel
case cli.logErr:
return log.ErrorLevel
default:
return log.InfoLevel
}
logFormatter := &log.TextFormatter{TimestampFormat: "02-01-2006 03:04:05 PM", FullTimestamp: true}
log.SetFormatter(logFormatter)
csConfig, err = csconfig.NewConfig(ConfigFilePath, false, false)
if err != nil {
log.Fatalf(err.Error())
}
log.Debugf("Using %s as configuration file", ConfigFilePath)
if err := csConfig.LoadCSCLI(); err != nil {
log.Fatalf(err.Error())
}
// loadConfigFor loads the configuration file for the given sub-command.
// If the sub-command does not need it, it returns a default configuration.
func loadConfigFor(command string) (*csconfig.Config, string, error) {
noNeedConfig := []string{
"doc",
"help",
"completion",
"version",
"hubtest",
}
if csConfig.Cscli == nil {
log.Fatalf("missing 'cscli' configuration in '%s', exiting", ConfigFilePath)
}
if !slices.Contains(noNeedConfig, command) {
log.Debugf("Using %s as configuration file", ConfigFilePath)
if cwhub.HubBranch == "" && csConfig.Cscli.HubBranch != "" {
cwhub.HubBranch = csConfig.Cscli.HubBranch
}
if OutputFormat != "" {
csConfig.Cscli.Output = OutputFormat
if OutputFormat != "json" && OutputFormat != "raw" && OutputFormat != "human" {
log.Fatalf("output format %s unknown", OutputFormat)
config, merged, err := csconfig.NewConfig(ConfigFilePath, false, false, true)
if err != nil {
return nil, "", err
}
// set up directory for trace files
if err := trace.Init(filepath.Join(config.ConfigPaths.DataDir, "trace")); err != nil {
return nil, "", fmt.Errorf("while setting up trace directory: %w", err)
}
return config, merged, nil
}
return csconfig.NewDefaultConfig(), "", nil
}
// initialize is called before the subcommand is executed.
func (cli *cliRoot) initialize() {
var err error
log.SetLevel(cli.wantedLogLevel())
csConfig, mergedConfig, err = loadConfigFor(os.Args[1])
if err != nil {
log.Fatal(err)
}
// recap of the enabled feature flags, because logging
// was not enabled when we set them from envvars
if fflist := csconfig.ListFeatureFlags(); fflist != "" {
log.Debugf("Enabled feature flags: %s", fflist)
}
if cli.flagBranch != "" {
csConfig.Cscli.HubBranch = cli.flagBranch
}
if cli.outputFormat != "" {
csConfig.Cscli.Output = cli.outputFormat
}
if csConfig.Cscli.Output == "" {
csConfig.Cscli.Output = "human"
}
if csConfig.Cscli.Output != "human" && csConfig.Cscli.Output != "json" && csConfig.Cscli.Output != "raw" {
log.Fatalf("output format '%s' not supported: must be one of human, json, raw", csConfig.Cscli.Output)
}
if csConfig.Cscli.Output == "json" {
log.SetFormatter(&log.JSONFormatter{})
log.SetLevel(log.ErrorLevel)
@ -75,83 +139,145 @@ func initConfig() {
log.SetLevel(log.ErrorLevel)
}
if cli.outputColor != "" {
csConfig.Cscli.Color = cli.outputColor
if cli.outputColor != "yes" && cli.outputColor != "no" && cli.outputColor != "auto" {
log.Fatalf("output color %s unknown", cli.outputColor)
}
}
}
// list of valid subcommands for the shell completion
var validArgs = []string{
"scenarios", "parsers", "collections", "capi", "lapi", "postoverflows", "machines",
"metrics", "bouncers", "alerts", "decisions", "simulation", "hub", "dashboard",
"config", "completion", "version", "console",
"alerts", "appsec-configs", "appsec-rules", "bouncers", "capi", "collections",
"completion", "config", "console", "contexts", "dashboard", "decisions", "explain",
"hub", "hubtest", "lapi", "machines", "metrics", "notifications", "parsers",
"postoverflows", "scenarios", "simulation", "support", "version",
}
func main() {
func (cli *cliRoot) colorize(cmd *cobra.Command) {
cc.Init(&cc.Config{
RootCmd: cmd,
Headings: cc.Yellow,
Commands: cc.Green + cc.Bold,
CmdShortDescr: cc.Cyan,
Example: cc.Italic,
ExecName: cc.Bold,
Aliases: cc.Bold + cc.Italic,
FlagsDataType: cc.White,
Flags: cc.Green,
FlagsDescr: cc.Cyan,
NoExtraNewlines: true,
NoBottomNewline: true,
})
cmd.SetOut(color.Output)
}
var rootCmd = &cobra.Command{
func (cli *cliRoot) NewCommand() *cobra.Command {
// set the formatter asap and worry about level later
logFormatter := &log.TextFormatter{TimestampFormat: time.RFC3339, FullTimestamp: true}
log.SetFormatter(logFormatter)
if err := fflag.RegisterAllFeatures(); err != nil {
log.Fatalf("failed to register features: %s", err)
}
if err := csconfig.LoadFeatureFlagsEnv(log.StandardLogger()); err != nil {
log.Fatalf("failed to set feature flags from env: %s", err)
}
cmd := &cobra.Command{
Use: "cscli",
Short: "cscli allows you to manage crowdsec",
Long: `cscli is the main command to interact with your crowdsec service, scenarios & db.
It is meant to allow you to manage bans, parsers/scenarios/etc, api and generally manage you crowdsec setup.`,
ValidArgs: validArgs,
ValidArgs: validArgs,
DisableAutoGenTag: true,
SilenceErrors: true,
SilenceUsage: true,
/*TBD examples*/
}
var cmdDocGen = &cobra.Command{
Use: "doc",
Short: "Generate the documentation in `./doc/`. Directory must exist.",
Args: cobra.ExactArgs(0),
Hidden: true,
Run: func(cmd *cobra.Command, args []string) {
if err := doc.GenMarkdownTree(rootCmd, "./doc/"); err != nil {
log.Fatalf("Failed to generate cobra doc: %s", err.Error())
}
},
}
rootCmd.AddCommand(cmdDocGen)
/*usage*/
var cmdVersion = &cobra.Command{
Use: "version",
Short: "Display version and exit.",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
cwversion.Show()
},
}
rootCmd.AddCommand(cmdVersion)
rootCmd.PersistentFlags().StringVarP(&ConfigFilePath, "config", "c", "/etc/crowdsec/config.yaml", "path to crowdsec config file")
rootCmd.PersistentFlags().StringVarP(&OutputFormat, "output", "o", "", "Output format : human, json, raw.")
rootCmd.PersistentFlags().BoolVar(&dbg_lvl, "debug", false, "Set logging to debug.")
rootCmd.PersistentFlags().BoolVar(&nfo_lvl, "info", false, "Set logging to info.")
rootCmd.PersistentFlags().BoolVar(&wrn_lvl, "warning", false, "Set logging to warning.")
rootCmd.PersistentFlags().BoolVar(&err_lvl, "error", false, "Set logging to error.")
rootCmd.PersistentFlags().BoolVar(&trace_lvl, "trace", false, "Set logging to trace.")
cli.colorize(cmd)
rootCmd.PersistentFlags().StringVar(&cwhub.HubBranch, "branch", "", "Override hub branch on github")
if err := rootCmd.PersistentFlags().MarkHidden("branch"); err != nil {
log.Fatalf("failed to make branch hidden : %s", err)
}
cobra.OnInitialize(initConfig)
/*don't sort flags so we can enforce order*/
rootCmd.Flags().SortFlags = false
rootCmd.PersistentFlags().SortFlags = false
cmd.Flags().SortFlags = false
rootCmd.AddCommand(NewConfigCmd())
rootCmd.AddCommand(NewHubCmd())
rootCmd.AddCommand(NewMetricsCmd())
rootCmd.AddCommand(NewDashboardCmd())
rootCmd.AddCommand(NewDecisionsCmd())
rootCmd.AddCommand(NewAlertsCmd())
// rootCmd.AddCommand(NewInspectCmd())
rootCmd.AddCommand(NewSimulationCmds())
rootCmd.AddCommand(NewBouncersCmd())
rootCmd.AddCommand(NewMachinesCmd())
rootCmd.AddCommand(NewParsersCmd())
rootCmd.AddCommand(NewScenariosCmd())
rootCmd.AddCommand(NewCollectionsCmd())
rootCmd.AddCommand(NewPostOverflowsCmd())
rootCmd.AddCommand(NewCapiCmd())
rootCmd.AddCommand(NewLapiCmd())
rootCmd.AddCommand(NewCompletionCmd())
rootCmd.AddCommand(NewConsoleCmd())
if err := rootCmd.Execute(); err != nil {
log.Fatalf("While executing root command : %s", err)
pflags := cmd.PersistentFlags()
pflags.SortFlags = false
pflags.StringVarP(&ConfigFilePath, "config", "c", csconfig.DefaultConfigPath("config.yaml"), "path to crowdsec config file")
pflags.StringVarP(&cli.outputFormat, "output", "o", "", "Output format: human, json, raw")
pflags.StringVarP(&cli.outputColor, "color", "", "auto", "Output color: yes, no, auto")
pflags.BoolVar(&cli.logDebug, "debug", false, "Set logging to debug")
pflags.BoolVar(&cli.logInfo, "info", false, "Set logging to info")
pflags.BoolVar(&cli.logWarn, "warning", false, "Set logging to warning")
pflags.BoolVar(&cli.logErr, "error", false, "Set logging to error")
pflags.BoolVar(&cli.logTrace, "trace", false, "Set logging to trace")
pflags.StringVar(&cli.flagBranch, "branch", "", "Override hub branch on github")
if err := pflags.MarkHidden("branch"); err != nil {
log.Fatalf("failed to hide flag: %s", err)
}
// Look for "-c /path/to/config.yaml"
// This duplicates the logic in cobra, but we need to do it before
// because feature flags can change which subcommands are available.
for i, arg := range os.Args {
if arg == "-c" || arg == "--config" {
if len(os.Args) > i+1 {
ConfigFilePath = os.Args[i+1]
}
}
}
if err := csconfig.LoadFeatureFlagsFile(ConfigFilePath, log.StandardLogger()); err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 {
cobra.OnInitialize(cli.initialize)
}
cmd.AddCommand(NewCLIDoc().NewCommand(cmd))
cmd.AddCommand(NewCLIVersion().NewCommand())
cmd.AddCommand(NewCLIConfig(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIHub(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIMetrics(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIDashboard(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIDecisions(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIAlerts(cli.cfg).NewCommand())
cmd.AddCommand(NewCLISimulation(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIBouncers(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIMachines(cli.cfg).NewCommand())
cmd.AddCommand(NewCLICapi(cli.cfg).NewCommand())
cmd.AddCommand(NewCLILapi(cli.cfg).NewCommand())
cmd.AddCommand(NewCompletionCmd())
cmd.AddCommand(NewCLIConsole(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIExplain(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIHubTest(cli.cfg).NewCommand())
cmd.AddCommand(NewCLINotifications(cli.cfg).NewCommand())
cmd.AddCommand(NewCLISupport().NewCommand())
cmd.AddCommand(NewCLIPapi(cli.cfg).NewCommand())
cmd.AddCommand(NewCLICollection(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIParser(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIScenario(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIPostOverflow(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIContext(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIAppsecConfig(cli.cfg).NewCommand())
cmd.AddCommand(NewCLIAppsecRule(cli.cfg).NewCommand())
if fflag.CscliSetup.IsEnabled() {
cmd.AddCommand(NewSetupCmd())
}
return cmd
}
func main() {
cmd := newCliRoot().NewCommand()
if err := cmd.Execute(); err != nil {
log.Fatal(err)
}
}

View file

@ -5,21 +5,19 @@ import (
"runtime"
)
const (
ReloadMessageFormat = `Run '%s' for the new configuration to be effective.`
ReloadCmdLinux = `sudo systemctl reload crowdsec`
ReloadCmdFreebsd = `sudo service crowdsec reload`
)
// ReloadMessage returns a description of the task required to reload
// the crowdsec configuration, according to the operating system.
func ReloadMessage() string {
var msg string
var reloadCmd string
if runtime.GOOS == "freebsd" {
reloadCmd = ReloadCmdFreebsd
} else {
reloadCmd = ReloadCmdLinux
switch runtime.GOOS {
case "windows":
msg = "Please restart the crowdsec service"
case "freebsd":
msg = `Run 'sudo service crowdsec reload'`
default:
msg = `Run 'sudo systemctl reload crowdsec'`
}
return fmt.Sprintf(ReloadMessageFormat, reloadCmd)
return fmt.Sprintf("%s for the new configuration to be effective.", msg)
}

View file

@ -2,91 +2,80 @@ package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"sort"
"strconv"
"strings"
"time"
"github.com/crowdsecurity/crowdsec/pkg/types"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/olekukonko/tablewriter"
"github.com/fatih/color"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/prom2json"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/go-cs-lib/maptools"
"github.com/crowdsecurity/go-cs-lib/trace"
)
func lapiMetricsToTable(table *tablewriter.Table, stats map[string]map[string]map[string]int) error {
//stats : machine -> route -> method -> count
/*we want consistant display order*/
machineKeys := []string{}
for k := range stats {
machineKeys = append(machineKeys, k)
type (
statAcquis map[string]map[string]int
statParser map[string]map[string]int
statBucket map[string]map[string]int
statWhitelist map[string]map[string]map[string]int
statLapi map[string]map[string]int
statLapiMachine map[string]map[string]map[string]int
statLapiBouncer map[string]map[string]map[string]int
statLapiDecision map[string]struct {
NonEmpty int
Empty int
}
sort.Strings(machineKeys)
for _, machine := range machineKeys {
//oneRow : route -> method -> count
machineRow := stats[machine]
for routeName, route := range machineRow {
for methodName, count := range route {
row := []string{}
row = append(row, machine)
row = append(row, routeName)
row = append(row, methodName)
if count != 0 {
row = append(row, fmt.Sprintf("%d", count))
} else {
row = append(row, "-")
}
table.Append(row)
}
}
statDecision map[string]map[string]map[string]int
statAppsecEngine map[string]map[string]int
statAppsecRule map[string]map[string]map[string]int
statAlert map[string]int
statStash map[string]struct {
Type string
Count int
}
return nil
)
var (
ErrMissingConfig = errors.New("prometheus section missing, can't show metrics")
ErrMetricsDisabled = errors.New("prometheus is not enabled, can't show metrics")
)
type metricSection interface {
Table(out io.Writer, noUnit bool, showEmpty bool)
Description() (string, string)
}
func metricsToTable(table *tablewriter.Table, stats map[string]map[string]int, keys []string) error {
type metricStore map[string]metricSection
var sortedKeys []string
if table == nil {
return fmt.Errorf("nil table")
func NewMetricStore() metricStore {
return metricStore{
"acquisition": statAcquis{},
"scenarios": statBucket{},
"parsers": statParser{},
"lapi": statLapi{},
"lapi-machine": statLapiMachine{},
"lapi-bouncer": statLapiBouncer{},
"lapi-decisions": statLapiDecision{},
"decisions": statDecision{},
"alerts": statAlert{},
"stash": statStash{},
"appsec-engine": statAppsecEngine{},
"appsec-rule": statAppsecRule{},
"whitelists": statWhitelist{},
}
//sort keys to keep consistent order when printing
sortedKeys = []string{}
for akey := range stats {
sortedKeys = append(sortedKeys, akey)
}
sort.Strings(sortedKeys)
//
for _, alabel := range sortedKeys {
astats, ok := stats[alabel]
if !ok {
continue
}
row := []string{}
row = append(row, alabel) //name
for _, sl := range keys {
if v, ok := astats[sl]; ok && v != 0 {
row = append(row, fmt.Sprintf("%d", v))
} else {
row = append(row, "-")
}
}
table.Append(row)
}
return nil
}
/*This is a complete rip from prom2json*/
func ShowPrometheus(url string) {
func (ms metricStore) Fetch(url string) error {
mfChan := make(chan *dto.MetricFamily, 1024)
errChan := make(chan error, 1)
// Start with the DefaultTransport for sane defaults.
transport := http.DefaultTransport.(*http.Transport).Clone()
@ -95,43 +84,62 @@ func ShowPrometheus(url string) {
transport.DisableKeepAlives = true
// Timeout early if the server doesn't even return the headers.
transport.ResponseHeaderTimeout = time.Minute
go func() {
defer types.CatchPanic("crowdsec/ShowPrometheus")
defer trace.CatchPanic("crowdsec/ShowPrometheus")
err := prom2json.FetchMetricFamilies(url, mfChan, transport)
if err != nil {
log.Fatalf("failed to fetch prometheus metrics : %v", err)
errChan <- fmt.Errorf("failed to fetch metrics: %w", err)
return
}
errChan <- nil
}()
result := []*prom2json.Family{}
for mf := range mfChan {
result = append(result, prom2json.NewFamily(mf))
}
log.Debugf("Finished reading prometheus output, %d entries", len(result))
if err := <-errChan; err != nil {
return err
}
log.Debugf("Finished reading metrics output, %d entries", len(result))
/*walk*/
lapi_decisions_stats := map[string]struct {
NonEmpty int
Empty int
}{}
acquis_stats := map[string]map[string]int{}
parsers_stats := map[string]map[string]int{}
buckets_stats := map[string]map[string]int{}
lapi_stats := map[string]map[string]int{}
lapi_machine_stats := map[string]map[string]map[string]int{}
lapi_bouncer_stats := map[string]map[string]map[string]int{}
mAcquis := ms["acquisition"].(statAcquis)
mParser := ms["parsers"].(statParser)
mBucket := ms["scenarios"].(statBucket)
mLapi := ms["lapi"].(statLapi)
mLapiMachine := ms["lapi-machine"].(statLapiMachine)
mLapiBouncer := ms["lapi-bouncer"].(statLapiBouncer)
mLapiDecision := ms["lapi-decisions"].(statLapiDecision)
mDecision := ms["decisions"].(statDecision)
mAppsecEngine := ms["appsec-engine"].(statAppsecEngine)
mAppsecRule := ms["appsec-rule"].(statAppsecRule)
mAlert := ms["alerts"].(statAlert)
mStash := ms["stash"].(statStash)
mWhitelist := ms["whitelists"].(statWhitelist)
for idx, fam := range result {
if !strings.HasPrefix(fam.Name, "cs_") {
continue
}
log.Tracef("round %d", idx)
for _, m := range fam.Metrics {
metric := m.(prom2json.Metric)
metric, ok := m.(prom2json.Metric)
if !ok {
log.Debugf("failed to convert metric to prom2json.Metric")
continue
}
name, ok := metric.Labels["name"]
if !ok {
log.Debugf("no name in Metric %v", metric.Labels)
}
source, ok := metric.Labels["source"]
if !ok {
log.Debugf("no source in Metric %v for %s", metric.Labels, fam.Name)
@ -148,261 +156,342 @@ func ShowPrometheus(url string) {
route := metric.Labels["route"]
method := metric.Labels["method"]
reason := metric.Labels["reason"]
origin := metric.Labels["origin"]
action := metric.Labels["action"]
appsecEngine := metric.Labels["appsec_engine"]
appsecRule := metric.Labels["rule_name"]
mtype := metric.Labels["type"]
fval, err := strconv.ParseFloat(value, 32)
if err != nil {
log.Errorf("Unexpected int value %s : %s", value, err)
}
ival := int(fval)
switch fam.Name {
/*buckets*/
//
// buckets
//
case "cs_bucket_created_total":
if _, ok := buckets_stats[name]; !ok {
buckets_stats[name] = make(map[string]int)
}
buckets_stats[name]["instanciation"] += ival
mBucket.Process(name, "instantiation", ival)
case "cs_buckets":
if _, ok := buckets_stats[name]; !ok {
buckets_stats[name] = make(map[string]int)
}
buckets_stats[name]["curr_count"] += ival
mBucket.Process(name, "curr_count", ival)
case "cs_bucket_overflowed_total":
if _, ok := buckets_stats[name]; !ok {
buckets_stats[name] = make(map[string]int)
}
buckets_stats[name]["overflow"] += ival
mBucket.Process(name, "overflow", ival)
case "cs_bucket_poured_total":
if _, ok := buckets_stats[name]; !ok {
buckets_stats[name] = make(map[string]int)
}
if _, ok := acquis_stats[source]; !ok {
acquis_stats[source] = make(map[string]int)
}
buckets_stats[name]["pour"] += ival
acquis_stats[source]["pour"] += ival
mBucket.Process(name, "pour", ival)
mAcquis.Process(source, "pour", ival)
case "cs_bucket_underflowed_total":
if _, ok := buckets_stats[name]; !ok {
buckets_stats[name] = make(map[string]int)
}
buckets_stats[name]["underflow"] += ival
/*acquis*/
mBucket.Process(name, "underflow", ival)
//
// parsers
//
case "cs_parser_hits_total":
if _, ok := acquis_stats[source]; !ok {
acquis_stats[source] = make(map[string]int)
}
acquis_stats[source]["reads"] += ival
mAcquis.Process(source, "reads", ival)
case "cs_parser_hits_ok_total":
if _, ok := acquis_stats[source]; !ok {
acquis_stats[source] = make(map[string]int)
}
acquis_stats[source]["parsed"] += ival
mAcquis.Process(source, "parsed", ival)
case "cs_parser_hits_ko_total":
if _, ok := acquis_stats[source]; !ok {
acquis_stats[source] = make(map[string]int)
}
acquis_stats[source]["unparsed"] += ival
mAcquis.Process(source, "unparsed", ival)
case "cs_node_hits_total":
if _, ok := parsers_stats[name]; !ok {
parsers_stats[name] = make(map[string]int)
}
parsers_stats[name]["hits"] += ival
mParser.Process(name, "hits", ival)
case "cs_node_hits_ok_total":
if _, ok := parsers_stats[name]; !ok {
parsers_stats[name] = make(map[string]int)
}
parsers_stats[name]["parsed"] += ival
mParser.Process(name, "parsed", ival)
case "cs_node_hits_ko_total":
if _, ok := parsers_stats[name]; !ok {
parsers_stats[name] = make(map[string]int)
}
parsers_stats[name]["unparsed"] += ival
mParser.Process(name, "unparsed", ival)
//
// whitelists
//
case "cs_node_wl_hits_total":
mWhitelist.Process(name, reason, "hits", ival)
case "cs_node_wl_hits_ok_total":
mWhitelist.Process(name, reason, "whitelisted", ival)
// track as well whitelisted lines at acquis level
mAcquis.Process(source, "whitelisted", ival)
//
// lapi
//
case "cs_lapi_route_requests_total":
if _, ok := lapi_stats[route]; !ok {
lapi_stats[route] = make(map[string]int)
}
lapi_stats[route][method] += ival
mLapi.Process(route, method, ival)
case "cs_lapi_machine_requests_total":
if _, ok := lapi_machine_stats[machine]; !ok {
lapi_machine_stats[machine] = make(map[string]map[string]int)
}
if _, ok := lapi_machine_stats[machine][route]; !ok {
lapi_machine_stats[machine][route] = make(map[string]int)
}
lapi_machine_stats[machine][route][method] += ival
mLapiMachine.Process(machine, route, method, ival)
case "cs_lapi_bouncer_requests_total":
if _, ok := lapi_bouncer_stats[bouncer]; !ok {
lapi_bouncer_stats[bouncer] = make(map[string]map[string]int)
}
if _, ok := lapi_bouncer_stats[bouncer][route]; !ok {
lapi_bouncer_stats[bouncer][route] = make(map[string]int)
}
lapi_bouncer_stats[bouncer][route][method] += ival
mLapiBouncer.Process(bouncer, route, method, ival)
case "cs_lapi_decisions_ko_total", "cs_lapi_decisions_ok_total":
if _, ok := lapi_decisions_stats[bouncer]; !ok {
lapi_decisions_stats[bouncer] = struct {
NonEmpty int
Empty int
}{}
}
x := lapi_decisions_stats[bouncer]
if fam.Name == "cs_lapi_decisions_ko_total" {
x.Empty += ival
} else if fam.Name == "cs_lapi_decisions_ok_total" {
x.NonEmpty += ival
}
lapi_decisions_stats[bouncer] = x
mLapiDecision.Process(bouncer, fam.Name, ival)
//
// decisions
//
case "cs_active_decisions":
mDecision.Process(reason, origin, action, ival)
case "cs_alerts":
mAlert.Process(reason, ival)
//
// stash
//
case "cs_cache_size":
mStash.Process(name, mtype, ival)
//
// appsec
//
case "cs_appsec_reqs_total":
mAppsecEngine.Process(appsecEngine, "processed", ival)
case "cs_appsec_block_total":
mAppsecEngine.Process(appsecEngine, "blocked", ival)
case "cs_appsec_rule_hits":
mAppsecRule.Process(appsecEngine, appsecRule, "triggered", ival)
default:
log.Debugf("unknown: %+v", fam.Name)
continue
}
}
}
if csConfig.Cscli.Output == "human" {
acquisTable := tablewriter.NewWriter(os.Stdout)
acquisTable.SetHeader([]string{"Source", "Lines read", "Lines parsed", "Lines unparsed", "Lines poured to bucket"})
keys := []string{"reads", "parsed", "unparsed", "pour"}
if err := metricsToTable(acquisTable, acquis_stats, keys); err != nil {
log.Warningf("while collecting acquis stats : %s", err)
}
bucketsTable := tablewriter.NewWriter(os.Stdout)
bucketsTable.SetHeader([]string{"Bucket", "Current Count", "Overflows", "Instanciated", "Poured", "Expired"})
keys = []string{"curr_count", "overflow", "instanciation", "pour", "underflow"}
if err := metricsToTable(bucketsTable, buckets_stats, keys); err != nil {
log.Warningf("while collecting acquis stats : %s", err)
}
return nil
}
parsersTable := tablewriter.NewWriter(os.Stdout)
parsersTable.SetHeader([]string{"Parsers", "Hits", "Parsed", "Unparsed"})
keys = []string{"hits", "parsed", "unparsed"}
if err := metricsToTable(parsersTable, parsers_stats, keys); err != nil {
log.Warningf("while collecting acquis stats : %s", err)
}
type cliMetrics struct {
cfg configGetter
}
lapiMachinesTable := tablewriter.NewWriter(os.Stdout)
lapiMachinesTable.SetHeader([]string{"Machine", "Route", "Method", "Hits"})
if err := lapiMetricsToTable(lapiMachinesTable, lapi_machine_stats); err != nil {
log.Warningf("while collecting machine lapi stats : %s", err)
}
//lapiMetricsToTable
lapiBouncersTable := tablewriter.NewWriter(os.Stdout)
lapiBouncersTable.SetHeader([]string{"Bouncer", "Route", "Method", "Hits"})
if err := lapiMetricsToTable(lapiBouncersTable, lapi_bouncer_stats); err != nil {
log.Warningf("while collecting bouncer lapi stats : %s", err)
}
lapiDecisionsTable := tablewriter.NewWriter(os.Stdout)
lapiDecisionsTable.SetHeader([]string{"Bouncer", "Empty answers", "Non-empty answers"})
for bouncer, hits := range lapi_decisions_stats {
row := []string{}
row = append(row, bouncer)
row = append(row, fmt.Sprintf("%d", hits.Empty))
row = append(row, fmt.Sprintf("%d", hits.NonEmpty))
lapiDecisionsTable.Append(row)
}
/*unfortunately, we can't reuse metricsToTable as the structure is too different :/*/
lapiTable := tablewriter.NewWriter(os.Stdout)
lapiTable.SetHeader([]string{"Route", "Method", "Hits"})
sortedKeys := []string{}
for akey := range lapi_stats {
sortedKeys = append(sortedKeys, akey)
}
sort.Strings(sortedKeys)
for _, alabel := range sortedKeys {
astats := lapi_stats[alabel]
subKeys := []string{}
for skey := range astats {
subKeys = append(subKeys, skey)
}
sort.Strings(subKeys)
for _, sl := range subKeys {
row := []string{}
row = append(row, alabel)
row = append(row, sl)
row = append(row, fmt.Sprintf("%d", astats[sl]))
lapiTable.Append(row)
}
}
if bucketsTable.NumLines() > 0 {
log.Printf("Buckets Metrics:")
bucketsTable.Render()
}
if acquisTable.NumLines() > 0 {
log.Printf("Acquisition Metrics:")
acquisTable.Render()
}
if parsersTable.NumLines() > 0 {
log.Printf("Parser Metrics:")
parsersTable.Render()
}
if lapiTable.NumLines() > 0 {
log.Printf("Local Api Metrics:")
lapiTable.Render()
}
if lapiMachinesTable.NumLines() > 0 {
log.Printf("Local Api Machines Metrics:")
lapiMachinesTable.Render()
}
if lapiBouncersTable.NumLines() > 0 {
log.Printf("Local Api Bouncers Metrics:")
lapiBouncersTable.Render()
}
if lapiDecisionsTable.NumLines() > 0 {
log.Printf("Local Api Bouncers Decisions:")
lapiDecisionsTable.Render()
}
} else if csConfig.Cscli.Output == "json" {
for _, val := range []interface{}{acquis_stats, parsers_stats, buckets_stats, lapi_stats, lapi_bouncer_stats, lapi_machine_stats, lapi_decisions_stats} {
x, err := json.MarshalIndent(val, "", " ")
if err != nil {
log.Fatalf("failed to unmarshal metrics : %v", err)
}
fmt.Printf("%s\n", string(x))
}
} else if csConfig.Cscli.Output == "raw" {
for _, val := range []interface{}{acquis_stats, parsers_stats, buckets_stats, lapi_stats, lapi_bouncer_stats, lapi_machine_stats, lapi_decisions_stats} {
x, err := yaml.Marshal(val)
if err != nil {
log.Fatalf("failed to unmarshal metrics : %v", err)
}
fmt.Printf("%s\n", string(x))
}
func NewCLIMetrics(cfg configGetter) *cliMetrics {
return &cliMetrics{
cfg: cfg,
}
}
func NewMetricsCmd() *cobra.Command {
/* ---- UPDATE COMMAND */
var cmdMetrics = &cobra.Command{
func (ms metricStore) Format(out io.Writer, sections []string, formatType string, noUnit bool) error {
// copy only the sections we want
want := map[string]metricSection{}
// if explicitly asking for sections, we want to show empty tables
showEmpty := len(sections) > 0
// if no sections are specified, we want all of them
if len(sections) == 0 {
sections = maptools.SortedKeys(ms)
}
for _, section := range sections {
want[section] = ms[section]
}
switch formatType {
case "human":
for _, section := range maptools.SortedKeys(want) {
want[section].Table(out, noUnit, showEmpty)
}
case "json":
x, err := json.MarshalIndent(want, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal metrics: %w", err)
}
out.Write(x)
case "raw":
x, err := yaml.Marshal(want)
if err != nil {
return fmt.Errorf("failed to marshal metrics: %w", err)
}
out.Write(x)
default:
return fmt.Errorf("unknown format type %s", formatType)
}
return nil
}
func (cli *cliMetrics) show(sections []string, url string, noUnit bool) error {
cfg := cli.cfg()
if url != "" {
cfg.Cscli.PrometheusUrl = url
}
if cfg.Prometheus == nil {
return ErrMissingConfig
}
if !cfg.Prometheus.Enabled {
return ErrMetricsDisabled
}
ms := NewMetricStore()
if err := ms.Fetch(cfg.Cscli.PrometheusUrl); err != nil {
return err
}
// any section that we don't have in the store is an error
for _, section := range sections {
if _, ok := ms[section]; !ok {
return fmt.Errorf("unknown metrics type: %s", section)
}
}
if err := ms.Format(color.Output, sections, cfg.Cscli.Output, noUnit); err != nil {
return err
}
return nil
}
func (cli *cliMetrics) NewCommand() *cobra.Command {
var (
url string
noUnit bool
)
cmd := &cobra.Command{
Use: "metrics",
Short: "Display crowdsec prometheus metrics.",
Long: `Fetch metrics from the prometheus server and display them in a human-friendly way`,
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
if err := csConfig.LoadPrometheus(); err != nil {
log.Fatalf(err.Error())
}
if !csConfig.Prometheus.Enabled {
log.Warningf("Prometheus is not enabled, can't show metrics")
os.Exit(1)
}
Long: `Fetch metrics from a Local API server and display them`,
Example: `# Show all Metrics, skip empty tables (same as "cecli metrics show")
cscli metrics
if prometheusURL == "" {
prometheusURL = csConfig.Cscli.PrometheusUrl
}
# Show only some metrics, connect to a different url
cscli metrics --url http://lapi.local:6060/metrics show acquisition parsers
if prometheusURL == "" {
log.Errorf("No prometheus url, please specify in %s or via -u", *csConfig.FilePath)
os.Exit(1)
}
ShowPrometheus(prometheusURL + "/metrics")
# List available metric types
cscli metrics list`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.show(nil, url, noUnit)
},
}
cmdMetrics.PersistentFlags().StringVarP(&prometheusURL, "url", "u", "", "Prometheus url (http://<ip>:<port>/metrics)")
return cmdMetrics
flags := cmd.Flags()
flags.StringVarP(&url, "url", "u", "", "Prometheus url (http://<ip>:<port>/metrics)")
flags.BoolVar(&noUnit, "no-unit", false, "Show the real number instead of formatted with units")
cmd.AddCommand(cli.newShowCmd())
cmd.AddCommand(cli.newListCmd())
return cmd
}
// expandAlias returns a list of sections. The input can be a list of sections or alias.
func (cli *cliMetrics) expandAlias(args []string) []string {
ret := []string{}
for _, section := range args {
switch section {
case "engine":
ret = append(ret, "acquisition", "parsers", "scenarios", "stash", "whitelists")
case "lapi":
ret = append(ret, "alerts", "decisions", "lapi", "lapi-bouncer", "lapi-decisions", "lapi-machine")
case "appsec":
ret = append(ret, "appsec-engine", "appsec-rule")
default:
ret = append(ret, section)
}
}
return ret
}
func (cli *cliMetrics) newShowCmd() *cobra.Command {
var (
url string
noUnit bool
)
cmd := &cobra.Command{
Use: "show [type]...",
Short: "Display all or part of the available metrics.",
Long: `Fetch metrics from a Local API server and display them, optionally filtering on specific types.`,
Example: `# Show all Metrics, skip empty tables
cscli metrics show
# Use an alias: "engine", "lapi" or "appsec" to show a group of metrics
cscli metrics show engine
# Show some specific metrics, show empty tables, connect to a different url
cscli metrics show acquisition parsers scenarios stash --url http://lapi.local:6060/metrics
# To list available metric types, use "cscli metrics list"
cscli metrics list; cscli metrics list -o json
# Show metrics in json format
cscli metrics show acquisition parsers scenarios stash -o json`,
// Positional args are optional
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
args = cli.expandAlias(args)
return cli.show(args, url, noUnit)
},
}
flags := cmd.Flags()
flags.StringVarP(&url, "url", "u", "", "Metrics url (http://<ip>:<port>/metrics)")
flags.BoolVar(&noUnit, "no-unit", false, "Show the real number instead of formatted with units")
return cmd
}
func (cli *cliMetrics) list() error {
type metricType struct {
Type string `json:"type" yaml:"type"`
Title string `json:"title" yaml:"title"`
Description string `json:"description" yaml:"description"`
}
var allMetrics []metricType
ms := NewMetricStore()
for _, section := range maptools.SortedKeys(ms) {
title, description := ms[section].Description()
allMetrics = append(allMetrics, metricType{
Type: section,
Title: title,
Description: description,
})
}
switch cli.cfg().Cscli.Output {
case "human":
t := newTable(color.Output)
t.SetRowLines(true)
t.SetHeaders("Type", "Title", "Description")
for _, metric := range allMetrics {
t.AddRow(metric.Type, metric.Title, metric.Description)
}
t.Render()
case "json":
x, err := json.MarshalIndent(allMetrics, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal metric types: %w", err)
}
fmt.Println(string(x))
case "raw":
x, err := yaml.Marshal(allMetrics)
if err != nil {
return fmt.Errorf("failed to marshal metric types: %w", err)
}
fmt.Println(string(x))
}
return nil
}
func (cli *cliMetrics) newListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List available types of metrics.",
Long: `List available types of metrics.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
return cli.list()
},
}
return cmd
}

View file

@ -0,0 +1,615 @@
package main
import (
"errors"
"fmt"
"io"
"sort"
"strconv"
"github.com/aquasecurity/table"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/go-cs-lib/maptools"
)
// ErrNilTable means a nil pointer was passed instead of a table instance. This is a programming error.
var ErrNilTable = errors.New("nil table")
func lapiMetricsToTable(t *table.Table, stats map[string]map[string]map[string]int) int {
// stats: machine -> route -> method -> count
// sort keys to keep consistent order when printing
machineKeys := []string{}
for k := range stats {
machineKeys = append(machineKeys, k)
}
sort.Strings(machineKeys)
numRows := 0
for _, machine := range machineKeys {
// oneRow: route -> method -> count
machineRow := stats[machine]
for routeName, route := range machineRow {
for methodName, count := range route {
row := []string{
machine,
routeName,
methodName,
}
if count != 0 {
row = append(row, strconv.Itoa(count))
} else {
row = append(row, "-")
}
t.AddRow(row...)
numRows++
}
}
}
return numRows
}
func wlMetricsToTable(t *table.Table, stats map[string]map[string]map[string]int, noUnit bool) (int, error) {
if t == nil {
return 0, ErrNilTable
}
numRows := 0
for _, name := range maptools.SortedKeys(stats) {
for _, reason := range maptools.SortedKeys(stats[name]) {
row := []string{
name,
reason,
"-",
"-",
}
for _, action := range maptools.SortedKeys(stats[name][reason]) {
value := stats[name][reason][action]
switch action {
case "whitelisted":
row[3] = strconv.Itoa(value)
case "hits":
row[2] = strconv.Itoa(value)
default:
log.Debugf("unexpected counter '%s' for whitelists = %d", action, value)
}
}
t.AddRow(row...)
numRows++
}
}
return numRows, nil
}
func metricsToTable(t *table.Table, stats map[string]map[string]int, keys []string, noUnit bool) (int, error) {
if t == nil {
return 0, ErrNilTable
}
numRows := 0
for _, alabel := range maptools.SortedKeys(stats) {
astats, ok := stats[alabel]
if !ok {
continue
}
row := []string{
alabel,
}
for _, sl := range keys {
if v, ok := astats[sl]; ok && v != 0 {
numberToShow := strconv.Itoa(v)
if !noUnit {
numberToShow = formatNumber(v)
}
row = append(row, numberToShow)
} else {
row = append(row, "-")
}
}
t.AddRow(row...)
numRows++
}
return numRows, nil
}
func (s statBucket) Description() (string, string) {
return "Scenario Metrics",
`Measure events in different scenarios. Current count is the number of buckets during metrics collection. ` +
`Overflows are past event-producing buckets, while Expired are the ones that didnt receive enough events to Overflow.`
}
func (s statBucket) Process(bucket, metric string, val int) {
if _, ok := s[bucket]; !ok {
s[bucket] = make(map[string]int)
}
s[bucket][metric] += val
}
func (s statBucket) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Scenario", "Current Count", "Overflows", "Instantiated", "Poured", "Expired")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
keys := []string{"curr_count", "overflow", "instantiation", "pour", "underflow"}
if numRows, err := metricsToTable(t, s, keys, noUnit); err != nil {
log.Warningf("while collecting scenario stats: %s", err)
} else if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statAcquis) Description() (string, string) {
return "Acquisition Metrics",
`Measures the lines read, parsed, and unparsed per datasource. ` +
`Zero read lines indicate a misconfigured or inactive datasource. ` +
`Zero parsed lines mean the parser(s) failed. ` +
`Non-zero parsed lines are fine as crowdsec selects relevant lines.`
}
func (s statAcquis) Process(source, metric string, val int) {
if _, ok := s[source]; !ok {
s[source] = make(map[string]int)
}
s[source][metric] += val
}
func (s statAcquis) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Source", "Lines read", "Lines parsed", "Lines unparsed", "Lines poured to bucket", "Lines whitelisted")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
keys := []string{"reads", "parsed", "unparsed", "pour", "whitelisted"}
if numRows, err := metricsToTable(t, s, keys, noUnit); err != nil {
log.Warningf("while collecting acquis stats: %s", err)
} else if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statAppsecEngine) Description() (string, string) {
return "Appsec Metrics",
`Measures the number of parsed and blocked requests by the AppSec Component.`
}
func (s statAppsecEngine) Process(appsecEngine, metric string, val int) {
if _, ok := s[appsecEngine]; !ok {
s[appsecEngine] = make(map[string]int)
}
s[appsecEngine][metric] += val
}
func (s statAppsecEngine) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Appsec Engine", "Processed", "Blocked")
t.SetAlignment(table.AlignLeft, table.AlignLeft)
keys := []string{"processed", "blocked"}
if numRows, err := metricsToTable(t, s, keys, noUnit); err != nil {
log.Warningf("while collecting appsec stats: %s", err)
} else if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statAppsecRule) Description() (string, string) {
return "Appsec Rule Metrics",
`Provides “per AppSec Component” information about the number of matches for loaded AppSec Rules.`
}
func (s statAppsecRule) Process(appsecEngine, appsecRule string, metric string, val int) {
if _, ok := s[appsecEngine]; !ok {
s[appsecEngine] = make(map[string]map[string]int)
}
if _, ok := s[appsecEngine][appsecRule]; !ok {
s[appsecEngine][appsecRule] = make(map[string]int)
}
s[appsecEngine][appsecRule][metric] += val
}
func (s statAppsecRule) Table(out io.Writer, noUnit bool, showEmpty bool) {
for appsecEngine, appsecEngineRulesStats := range s {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Rule ID", "Triggered")
t.SetAlignment(table.AlignLeft, table.AlignLeft)
keys := []string{"triggered"}
if numRows, err := metricsToTable(t, appsecEngineRulesStats, keys, noUnit); err != nil {
log.Warningf("while collecting appsec rules stats: %s", err)
} else if numRows > 0 || showEmpty {
renderTableTitle(out, fmt.Sprintf("\nAppsec '%s' Rules Metrics:", appsecEngine))
t.Render()
}
}
}
func (s statWhitelist) Description() (string, string) {
return "Whitelist Metrics",
`Tracks the number of events processed and possibly whitelisted by each parser whitelist.`
}
func (s statWhitelist) Process(whitelist, reason, metric string, val int) {
if _, ok := s[whitelist]; !ok {
s[whitelist] = make(map[string]map[string]int)
}
if _, ok := s[whitelist][reason]; !ok {
s[whitelist][reason] = make(map[string]int)
}
s[whitelist][reason][metric] += val
}
func (s statWhitelist) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Whitelist", "Reason", "Hits", "Whitelisted")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
if numRows, err := wlMetricsToTable(t, s, noUnit); err != nil {
log.Warningf("while collecting parsers stats: %s", err)
} else if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statParser) Description() (string, string) {
return "Parser Metrics",
`Tracks the number of events processed by each parser and indicates success of failure. ` +
`Zero parsed lines means the parer(s) failed. ` +
`Non-zero unparsed lines are fine as crowdsec select relevant lines.`
}
func (s statParser) Process(parser, metric string, val int) {
if _, ok := s[parser]; !ok {
s[parser] = make(map[string]int)
}
s[parser][metric] += val
}
func (s statParser) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Parsers", "Hits", "Parsed", "Unparsed")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
keys := []string{"hits", "parsed", "unparsed"}
if numRows, err := metricsToTable(t, s, keys, noUnit); err != nil {
log.Warningf("while collecting parsers stats: %s", err)
} else if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statStash) Description() (string, string) {
return "Parser Stash Metrics",
`Tracks the status of stashes that might be created by various parsers and scenarios.`
}
func (s statStash) Process(name, mtype string, val int) {
s[name] = struct {
Type string
Count int
}{
Type: mtype,
Count: val,
}
}
func (s statStash) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Name", "Type", "Items")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
// unfortunately, we can't reuse metricsToTable as the structure is too different :/
numRows := 0
for _, alabel := range maptools.SortedKeys(s) {
astats := s[alabel]
row := []string{
alabel,
astats.Type,
strconv.Itoa(astats.Count),
}
t.AddRow(row...)
numRows++
}
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statLapi) Description() (string, string) {
return "Local API Metrics",
`Monitors the requests made to local API routes.`
}
func (s statLapi) Process(route, method string, val int) {
if _, ok := s[route]; !ok {
s[route] = make(map[string]int)
}
s[route][method] += val
}
func (s statLapi) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Route", "Method", "Hits")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
// unfortunately, we can't reuse metricsToTable as the structure is too different :/
numRows := 0
for _, alabel := range maptools.SortedKeys(s) {
astats := s[alabel]
subKeys := []string{}
for skey := range astats {
subKeys = append(subKeys, skey)
}
sort.Strings(subKeys)
for _, sl := range subKeys {
row := []string{
alabel,
sl,
strconv.Itoa(astats[sl]),
}
t.AddRow(row...)
numRows++
}
}
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statLapiMachine) Description() (string, string) {
return "Local API Machines Metrics",
`Tracks the number of calls to the local API from each registered machine.`
}
func (s statLapiMachine) Process(machine, route, method string, val int) {
if _, ok := s[machine]; !ok {
s[machine] = make(map[string]map[string]int)
}
if _, ok := s[machine][route]; !ok {
s[machine][route] = make(map[string]int)
}
s[machine][route][method] += val
}
func (s statLapiMachine) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Machine", "Route", "Method", "Hits")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
numRows := lapiMetricsToTable(t, s)
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statLapiBouncer) Description() (string, string) {
return "Local API Bouncers Metrics",
`Tracks total hits to remediation component related API routes.`
}
func (s statLapiBouncer) Process(bouncer, route, method string, val int) {
if _, ok := s[bouncer]; !ok {
s[bouncer] = make(map[string]map[string]int)
}
if _, ok := s[bouncer][route]; !ok {
s[bouncer][route] = make(map[string]int)
}
s[bouncer][route][method] += val
}
func (s statLapiBouncer) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Bouncer", "Route", "Method", "Hits")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
numRows := lapiMetricsToTable(t, s)
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statLapiDecision) Description() (string, string) {
return "Local API Bouncers Decisions",
`Tracks the number of empty/non-empty answers from LAPI to bouncers that are working in "live" mode.`
}
func (s statLapiDecision) Process(bouncer, fam string, val int) {
if _, ok := s[bouncer]; !ok {
s[bouncer] = struct {
NonEmpty int
Empty int
}{}
}
x := s[bouncer]
switch fam {
case "cs_lapi_decisions_ko_total":
x.Empty += val
case "cs_lapi_decisions_ok_total":
x.NonEmpty += val
}
s[bouncer] = x
}
func (s statLapiDecision) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Bouncer", "Empty answers", "Non-empty answers")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft)
numRows := 0
for bouncer, hits := range s {
t.AddRow(
bouncer,
strconv.Itoa(hits.Empty),
strconv.Itoa(hits.NonEmpty),
)
numRows++
}
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statDecision) Description() (string, string) {
return "Local API Decisions",
`Provides information about all currently active decisions. ` +
`Includes both local (crowdsec) and global decisions (CAPI), and lists subscriptions (lists).`
}
func (s statDecision) Process(reason, origin, action string, val int) {
if _, ok := s[reason]; !ok {
s[reason] = make(map[string]map[string]int)
}
if _, ok := s[reason][origin]; !ok {
s[reason][origin] = make(map[string]int)
}
s[reason][origin][action] += val
}
func (s statDecision) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Reason", "Origin", "Action", "Count")
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
numRows := 0
for reason, origins := range s {
for origin, actions := range origins {
for action, hits := range actions {
t.AddRow(
reason,
origin,
action,
strconv.Itoa(hits),
)
numRows++
}
}
}
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}
func (s statAlert) Description() (string, string) {
return "Local API Alerts",
`Tracks the total number of past and present alerts for the installed scenarios.`
}
func (s statAlert) Process(reason string, val int) {
s[reason] += val
}
func (s statAlert) Table(out io.Writer, noUnit bool, showEmpty bool) {
t := newTable(out)
t.SetRowLines(false)
t.SetHeaders("Reason", "Count")
t.SetAlignment(table.AlignLeft, table.AlignLeft)
numRows := 0
for scenario, hits := range s {
t.AddRow(
scenario,
strconv.Itoa(hits),
)
numRows++
}
if numRows > 0 || showEmpty {
title, _ := s.Description()
renderTableTitle(out, "\n"+title+":")
t.Render()
}
}

View file

@ -0,0 +1,462 @@
package main
import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/tomb.v2"
"gopkg.in/yaml.v3"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/csplugin"
"github.com/crowdsecurity/crowdsec/pkg/csprofiles"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
type NotificationsCfg struct {
Config csplugin.PluginConfig `json:"plugin_config"`
Profiles []*csconfig.ProfileCfg `json:"associated_profiles"`
ids []uint
}
type cliNotifications struct {
cfg configGetter
}
func NewCLINotifications(cfg configGetter) *cliNotifications {
return &cliNotifications{
cfg: cfg,
}
}
func (cli *cliNotifications) NewCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "notifications [action]",
Short: "Helper for notification plugin configuration",
Long: "To list/inspect/test notification template",
Args: cobra.MinimumNArgs(1),
Aliases: []string{"notifications", "notification"},
DisableAutoGenTag: true,
PersistentPreRunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
if err := require.LAPI(cfg); err != nil {
return err
}
if err := cfg.LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %w", err)
}
if err := require.Notifications(cfg); err != nil {
return err
}
return nil
},
}
cmd.AddCommand(cli.NewListCmd())
cmd.AddCommand(cli.NewInspectCmd())
cmd.AddCommand(cli.NewReinjectCmd())
cmd.AddCommand(cli.NewTestCmd())
return cmd
}
func (cli *cliNotifications) getPluginConfigs() (map[string]csplugin.PluginConfig, error) {
cfg := cli.cfg()
pcfgs := map[string]csplugin.PluginConfig{}
wf := func(path string, info fs.FileInfo, err error) error {
if info == nil {
return fmt.Errorf("error while traversing directory %s: %w", path, err)
}
name := filepath.Join(cfg.ConfigPaths.NotificationDir, info.Name()) // Avoid calling info.Name() twice
if (strings.HasSuffix(name, "yaml") || strings.HasSuffix(name, "yml")) && !(info.IsDir()) {
ts, err := csplugin.ParsePluginConfigFile(name)
if err != nil {
return fmt.Errorf("loading notifification plugin configuration with %s: %w", name, err)
}
for _, t := range ts {
csplugin.SetRequiredFields(&t)
pcfgs[t.Name] = t
}
}
return nil
}
if err := filepath.Walk(cfg.ConfigPaths.NotificationDir, wf); err != nil {
return nil, fmt.Errorf("while loading notifification plugin configuration: %w", err)
}
return pcfgs, nil
}
func (cli *cliNotifications) getProfilesConfigs() (map[string]NotificationsCfg, error) {
cfg := cli.cfg()
// A bit of a tricky stuf now: reconcile profiles and notification plugins
pcfgs, err := cli.getPluginConfigs()
if err != nil {
return nil, err
}
ncfgs := map[string]NotificationsCfg{}
for _, pc := range pcfgs {
ncfgs[pc.Name] = NotificationsCfg{
Config: pc,
}
}
profiles, err := csprofiles.NewProfile(cfg.API.Server.Profiles)
if err != nil {
return nil, fmt.Errorf("while extracting profiles from configuration: %w", err)
}
for profileID, profile := range profiles {
for _, notif := range profile.Cfg.Notifications {
pc, ok := pcfgs[notif]
if !ok {
return nil, fmt.Errorf("notification plugin '%s' does not exist", notif)
}
tmp, ok := ncfgs[pc.Name]
if !ok {
return nil, fmt.Errorf("notification plugin '%s' does not exist", pc.Name)
}
tmp.Profiles = append(tmp.Profiles, profile.Cfg)
tmp.ids = append(tmp.ids, uint(profileID))
ncfgs[pc.Name] = tmp
}
}
return ncfgs, nil
}
func (cli *cliNotifications) NewListCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "list active notifications plugins",
Long: `list active notifications plugins`,
Example: `cscli notifications list`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, _ []string) error {
cfg := cli.cfg()
ncfgs, err := cli.getProfilesConfigs()
if err != nil {
return fmt.Errorf("can't build profiles configuration: %w", err)
}
if cfg.Cscli.Output == "human" {
notificationListTable(color.Output, ncfgs)
} else if cfg.Cscli.Output == "json" {
x, err := json.MarshalIndent(ncfgs, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal notification configuration: %w", err)
}
fmt.Printf("%s", string(x))
} else if cfg.Cscli.Output == "raw" {
csvwriter := csv.NewWriter(os.Stdout)
err := csvwriter.Write([]string{"Name", "Type", "Profile name"})
if err != nil {
return fmt.Errorf("failed to write raw header: %w", err)
}
for _, b := range ncfgs {
profilesList := []string{}
for _, p := range b.Profiles {
profilesList = append(profilesList, p.Name)
}
err := csvwriter.Write([]string{b.Config.Name, b.Config.Type, strings.Join(profilesList, ", ")})
if err != nil {
return fmt.Errorf("failed to write raw content: %w", err)
}
}
csvwriter.Flush()
}
return nil
},
}
return cmd
}
func (cli *cliNotifications) NewInspectCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "inspect",
Short: "Inspect active notifications plugin configuration",
Long: `Inspect active notifications plugin and show configuration`,
Example: `cscli notifications inspect <plugin_name>`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
RunE: func(_ *cobra.Command, args []string) error {
cfg := cli.cfg()
ncfgs, err := cli.getProfilesConfigs()
if err != nil {
return fmt.Errorf("can't build profiles configuration: %w", err)
}
ncfg, ok := ncfgs[args[0]]
if !ok {
return fmt.Errorf("plugin '%s' does not exist or is not active", args[0])
}
if cfg.Cscli.Output == "human" || cfg.Cscli.Output == "raw" {
fmt.Printf(" - %15s: %15s\n", "Type", ncfg.Config.Type)
fmt.Printf(" - %15s: %15s\n", "Name", ncfg.Config.Name)
fmt.Printf(" - %15s: %15s\n", "Timeout", ncfg.Config.TimeOut)
fmt.Printf(" - %15s: %15s\n", "Format", ncfg.Config.Format)
for k, v := range ncfg.Config.Config {
fmt.Printf(" - %15s: %15v\n", k, v)
}
} else if cfg.Cscli.Output == "json" {
x, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal notification configuration: %w", err)
}
fmt.Printf("%s", string(x))
}
return nil
},
}
return cmd
}
func (cli *cliNotifications) NewTestCmd() *cobra.Command {
var (
pluginBroker csplugin.PluginBroker
pluginTomb tomb.Tomb
alertOverride string
)
cmd := &cobra.Command{
Use: "test [plugin name]",
Short: "send a generic test alert to notification plugin",
Long: `send a generic test alert to a notification plugin to test configuration even if is not active`,
Example: `cscli notifications test [plugin_name]`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
PreRunE: func(_ *cobra.Command, args []string) error {
cfg := cli.cfg()
pconfigs, err := cli.getPluginConfigs()
if err != nil {
return fmt.Errorf("can't build profiles configuration: %w", err)
}
pcfg, ok := pconfigs[args[0]]
if !ok {
return fmt.Errorf("plugin name: '%s' does not exist", args[0])
}
// Create a single profile with plugin name as notification name
return pluginBroker.Init(cfg.PluginConfig, []*csconfig.ProfileCfg{
{
Notifications: []string{
pcfg.Name,
},
},
}, cfg.ConfigPaths)
},
RunE: func(_ *cobra.Command, _ []string) error {
pluginTomb.Go(func() error {
pluginBroker.Run(&pluginTomb)
return nil
})
alert := &models.Alert{
Capacity: ptr.Of(int32(0)),
Decisions: []*models.Decision{{
Duration: ptr.Of("4h"),
Scope: ptr.Of("Ip"),
Value: ptr.Of("10.10.10.10"),
Type: ptr.Of("ban"),
Scenario: ptr.Of("test alert"),
Origin: ptr.Of(types.CscliOrigin),
}},
Events: []*models.Event{},
EventsCount: ptr.Of(int32(1)),
Leakspeed: ptr.Of("0"),
Message: ptr.Of("test alert"),
ScenarioHash: ptr.Of(""),
Scenario: ptr.Of("test alert"),
ScenarioVersion: ptr.Of(""),
Simulated: ptr.Of(false),
Source: &models.Source{
AsName: "",
AsNumber: "",
Cn: "",
IP: "10.10.10.10",
Range: "",
Scope: ptr.Of("Ip"),
Value: ptr.Of("10.10.10.10"),
},
StartAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
StopAt: ptr.Of(time.Now().UTC().Format(time.RFC3339)),
CreatedAt: time.Now().UTC().Format(time.RFC3339),
}
if err := yaml.Unmarshal([]byte(alertOverride), alert); err != nil {
return fmt.Errorf("failed to unmarshal alert override: %w", err)
}
pluginBroker.PluginChannel <- csplugin.ProfileAlert{
ProfileID: uint(0),
Alert: alert,
}
// time.Sleep(2 * time.Second) // There's no mechanism to ensure notification has been sent
pluginTomb.Kill(errors.New("terminating"))
pluginTomb.Wait()
return nil
},
}
cmd.Flags().StringVarP(&alertOverride, "alert", "a", "", "JSON string used to override alert fields in the generic alert (see crowdsec/pkg/models/alert.go in the source tree for the full definition of the object)")
return cmd
}
func (cli *cliNotifications) NewReinjectCmd() *cobra.Command {
var (
alertOverride string
alert *models.Alert
)
cmd := &cobra.Command{
Use: "reinject",
Short: "reinject an alert into profiles to trigger notifications",
Long: `reinject an alert into profiles to be evaluated by the filter and sent to matched notifications plugins`,
Example: `
cscli notifications reinject <alert_id>
cscli notifications reinject <alert_id> -a '{"remediation": false,"scenario":"notification/test"}'
cscli notifications reinject <alert_id> -a '{"remediation": true,"scenario":"notification/test"}'
`,
Args: cobra.ExactArgs(1),
DisableAutoGenTag: true,
PreRunE: func(_ *cobra.Command, args []string) error {
var err error
alert, err = cli.fetchAlertFromArgString(args[0])
if err != nil {
return err
}
return nil
},
RunE: func(_ *cobra.Command, _ []string) error {
var (
pluginBroker csplugin.PluginBroker
pluginTomb tomb.Tomb
)
cfg := cli.cfg()
if alertOverride != "" {
if err := json.Unmarshal([]byte(alertOverride), alert); err != nil {
return fmt.Errorf("can't unmarshal data in the alert flag: %w", err)
}
}
err := pluginBroker.Init(cfg.PluginConfig, cfg.API.Server.Profiles, cfg.ConfigPaths)
if err != nil {
return fmt.Errorf("can't initialize plugins: %w", err)
}
pluginTomb.Go(func() error {
pluginBroker.Run(&pluginTomb)
return nil
})
profiles, err := csprofiles.NewProfile(cfg.API.Server.Profiles)
if err != nil {
return fmt.Errorf("cannot extract profiles from configuration: %w", err)
}
for id, profile := range profiles {
_, matched, err := profile.EvaluateProfile(alert)
if err != nil {
return fmt.Errorf("can't evaluate profile %s: %w", profile.Cfg.Name, err)
}
if !matched {
log.Infof("The profile %s didn't match", profile.Cfg.Name)
continue
}
log.Infof("The profile %s matched, sending to its configured notification plugins", profile.Cfg.Name)
loop:
for {
select {
case pluginBroker.PluginChannel <- csplugin.ProfileAlert{
ProfileID: uint(id),
Alert: alert,
}:
break loop
default:
time.Sleep(50 * time.Millisecond)
log.Info("sleeping\n")
}
}
if profile.Cfg.OnSuccess == "break" {
log.Infof("The profile %s contains a 'on_success: break' so bailing out", profile.Cfg.Name)
break
}
}
// time.Sleep(2 * time.Second) // There's no mechanism to ensure notification has been sent
pluginTomb.Kill(errors.New("terminating"))
pluginTomb.Wait()
return nil
},
}
cmd.Flags().StringVarP(&alertOverride, "alert", "a", "", "JSON string used to override alert fields in the reinjected alert (see crowdsec/pkg/models/alert.go in the source tree for the full definition of the object)")
return cmd
}
func (cli *cliNotifications) fetchAlertFromArgString(toParse string) (*models.Alert, error) {
cfg := cli.cfg()
id, err := strconv.Atoi(toParse)
if err != nil {
return nil, fmt.Errorf("bad alert id %s", toParse)
}
apiURL, err := url.Parse(cfg.API.Client.Credentials.URL)
if err != nil {
return nil, fmt.Errorf("error parsing the URL of the API: %w", err)
}
client, err := apiclient.NewClient(&apiclient.Config{
MachineID: cfg.API.Client.Credentials.Login,
Password: strfmt.Password(cfg.API.Client.Credentials.Password),
UserAgent: fmt.Sprintf("crowdsec/%s", version.String()),
URL: apiURL,
VersionPrefix: "v1",
})
if err != nil {
return nil, fmt.Errorf("error creating the client for the API: %w", err)
}
alert, _, err := client.Alerts.GetByID(context.Background(), id)
if err != nil {
return nil, fmt.Errorf("can't find alert with id %d: %w", id, err)
}
return alert, nil
}

Some files were not shown because too many files have changed in this diff Show more