Compare commits

...

141 Commits

Author SHA1 Message Date
Federico Di Pierro
2804d60bd2 update(changelog): updated changelog for 0.39.1.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-10-08 12:54:09 +02:00
Luca Guerra
7c8209ed8e update(tests): add tests for plugin init_config
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-10-08 12:54:09 +02:00
Luca Guerra
3c4b315ff2 fix(engine): allow null init_config for plugin info
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-10-08 12:54:09 +02:00
Luca Guerra
92d6c4bab6 fix(engine): disable comma separated vectors in cxxopts
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-10-08 12:54:09 +02:00
Federico Di Pierro
51a19ea6cb fix(userspace/falco): fix event set selection for plugin with parsing capability.
In live mode we need to use the source_info inspectors instead of the offline inspector.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-10-08 12:54:09 +02:00
Aldo Lacuku
88d73505b0 update(changelog): add changelog for falco 0.39.0
Signed-off-by: Aldo Lacuku <aldo@lacuku.eu>
2024-10-01 09:58:36 +02:00
Luca Guerra
f2d23af415 fix(falco): allow disable_cri_async from both CLI and config
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-30 16:10:32 +02:00
Luca Guerra
10f87e515e cleanup(falco): ignore lint commit
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-30 16:10:32 +02:00
Poiana
82016080d0 chore(falco): apply code formatting
Signed-off-by: Poiana <poiana.bot@gmail.com>
2024-09-30 16:10:32 +02:00
Andrea Terzolo
bbb4d6e9b6 update: ignore_some_files
Signed-off-by: Andrea Terzolo <andreaterzolo3@gmail.com>
2024-09-30 16:10:32 +02:00
Leonardo Di Giovanna
e34507c739 feat(stats): add host_netinfo networking information stats family
Introduce host_netinfo stats family to hold information regarding host
networking. At the moment, it only provides ipv4 and ipv6 addresses
list for each interface available on the host. The naming schema for
the introduced stats is
falco.host_netinfo.interfaces.<ifname>.protocols.<ipv4|ipv6>.addresses.

Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-27 11:56:20 +02:00
Luca Guerra
ff32882a7f chore(build): update libs to 0.18.1
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-26 08:18:14 +02:00
Luca Guerra
f1b208f8fb fix(engine): sync outputs before printing stats at shutdown
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-24 10:15:05 +02:00
Leonardo Di Giovanna
ff65dc75ae cleanup(falco_metrics): remove unused falco_utils import
Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-24 10:15:05 +02:00
Leonardo Di Giovanna
a1ff7c7384 fix(falco_metrics): remove ifinfo_json stat/metric
Using JSON as value prevents any meaningful aggregation for the stats.
Splitting these information into multiple labels can drastically
increase the number of dimensions, as the number of interfaces and
addresses can be high in some environment. Moreover, these information
are not currently refreshed, even if they can frequently change. Given
these reasons, remove ifinfo_json from stats and metrics.

Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-24 10:15:05 +02:00
Leonardo Di Giovanna
fb47e816ae fix(falco_metrics)!: use full name for configs and rules files
Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-24 10:15:05 +02:00
Leonardo Di Giovanna
39dfd6765a fix(falco_metrics)!: split tags label into multiple tag_ labels
Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-24 10:15:05 +02:00
Luca Guerra
f4477f1ac2 update(tests): add test for plugin init_config map
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-24 10:15:05 +02:00
Luca Guerra
92fa3b5347 fix(falco): allow plugin init_config map in json schema
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-24 10:15:05 +02:00
Federico Di Pierro
fad91ea080 fix(userspace/falco): properly account for plugin with CAP_PARSING when computing interesting sc set.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-24 10:15:05 +02:00
Leonardo Di Giovanna
5e9a8fd665 update(systemd): add falco.service alias to all systemd units
Signed-off-by: Leonardo Di Giovanna <leonardodigiovanna1@gmail.com>
2024-09-24 10:15:05 +02:00
Federico Di Pierro
241f620956 update(cmake): bump libs to 0.18.0 and driver to 7.3.0+driver.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-18 11:11:52 +02:00
Federico Di Pierro
80816e67d6 chore(userspace/falco): deprecate cri related CLI options.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-18 11:11:52 +02:00
Federico Di Pierro
5874dc1f95 fix(userspace/engine): improve rule json schema to account for source and required_plugin_versions.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-18 11:11:52 +02:00
Federico Di Pierro
6b634df56e update(cmake): bump libs and driver to 0.18.0-rc2.
Moreover, bumped falcoctl to v0.10.0 and rules to 3.2.0.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-16 16:04:48 +02:00
Luca Guerra
037d7f9b36 cleanup(falco): use a header file for rule json schema
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-16 09:59:46 +02:00
Luca Guerra
ed4fb33981 cleanup(falco): use header file for json schema
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-16 09:59:46 +02:00
Luca Guerra
cd0d607f14 update(falco): add warning if the append condition does not appear to make sense
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-13 15:58:36 +02:00
Luca Guerra
5c959d0b1b update(falco): use std::include for readability
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-13 15:58:36 +02:00
Luca Guerra
a2336f186e update(falco): update json schema
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-13 15:58:36 +02:00
Luca Guerra
7005983409 update(engine): modify append_output format
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-13 15:58:36 +02:00
Melissa Kilby
d3c6a7478e update(falco_metrics): change prometheus rules metric naming
Co-authored-by: Leonardo Grasso <me@leonardograsso.com>
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-13 11:25:36 +02:00
Federico Di Pierro
d1644079e9 chore(userspace/falco): updated configuration schema.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-12 15:26:33 +02:00
Melissa Kilby
9089262569 update(falco_metrics): add kernel_event_counters_per_cpu_enabled config
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-12 15:26:33 +02:00
Melissa Kilby
2ceb6ecf0f update(Falco_metrics): fix prom subsystem for some scap vs falco metrics
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-12 15:26:33 +02:00
Melissa Kilby
2badce1714 update(falco_metrics): adjust sha256 prometheus name, remove double falco_
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-12 15:26:33 +02:00
Melissa Kilby
4f35b3e4e2 update(falco_metrics): apply reviewers suggestions
Co-authored-by: Federico Di Pierro <nierro92@gmail.com>
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-12 15:26:33 +02:00
Melissa Kilby
9669a4a0bb update(falco_metrics): rearrange evts and drops prometheus metrics
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-09-12 15:26:33 +02:00
Andrea Terzolo
55069c8a0a chore: scaffolding for enabling code formatting
Signed-off-by: Andrea Terzolo <andreaterzolo3@gmail.com>
2024-09-11 19:03:31 +02:00
Luca Guerra
bc7394b8c3 new(falco): add json_include_message_property option
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-11 17:52:32 +02:00
Federico Di Pierro
0f26e3c9ed chore(userspace): adjusted rule_loader::result::as_verbose_string following errors and warnings output layout.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
468037151a chore(userspace,unit_tests): properly report all schema validation warnings from yaml_helper::validate_node().
`-V` option will print all warnings, while normal run will only print foremost warning.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
2f89a2c140 chore(userspace): added schema validation info to rule_loader::result as_json and as_string outputs.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
1f9bea5a0b update(userspace/engine): fixed priorities in rules schema.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>

Co-authored-by: Leonardo Grasso <me@leonardograsso.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
c8361efea7 chore(userspace/falco): reverted file to master version.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
118e82ae01 cleanup(userspace): drop unused includes from yaml_helper.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
a392e1ed2d chore(userspace): minified rule schema json.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
5bd2d5a63e cleanup(userspace,unit_tests): moved rule schema under engine.
Also, moved yaml_helper under engine/ folder.
Ported rule json schema validation in the engine.

Also, updated rule_loader tests to check for validation.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
895e50d3a0 new(userspace): added json schema validation for rules.
Also, a new `--rule-schema` cli option was added to print the schema and leave.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:20:31 +02:00
Federico Di Pierro
d14825faf0 update(userspace/engine): bump engine version and checksum.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:15:31 +02:00
Federico Di Pierro
7f9211d817 update(cmake): bump libs and driver to 0.18.0-rc1.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-11 13:15:31 +02:00
Federico Di Pierro
a6f31058c1 fix(ci): restore master and release CI workflow permissions.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-10 12:23:28 +02:00
Aldo Lacuku
0034c3f082 update(cmake): bump falcoctl to v0.10.0-rc1
Signed-off-by: Aldo Lacuku <aldo@lacuku.eu>
2024-09-09 15:52:23 +02:00
Luca Guerra
df072dace7 update(libsinsp/tests): add CLI options test for append output
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Luca Guerra
ddc736057f cleanup(falco): apply review suggestion about extra_output_field_t
Signed-off-by: Luca Guerra <luca@guerra.sh>
Co-authored-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-09 15:31:24 +02:00
Luca Guerra
aeb4126ce2 fix(falco): update json schema
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Luca Guerra
8a19f1b135 update(tests): add message for failing configuration schema test
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Luca Guerra
3c95c0512d new(falco): add append_output explanation to falco.yaml
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Luca Guerra
63784e06ef new(falco): add json schema for append_output
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Luca Guerra
d210ed2e4f new(app): add append_output configuration option with fields and format
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-09 15:31:24 +02:00
Francesco Furlan
00ff9d82ea ci(insecure-api): update semgrep docker image
Signed-off-by: Francesco Furlan <francesco.furlan@sysdig.com>
2024-09-09 15:03:24 +02:00
Federico Di Pierro
f3eecb6b21 new(userspace/falco): added --config-schema action to print config schema.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-06 09:51:10 +02:00
Federico Di Pierro
dabfe0e154 cleanup(userspace/falco): drop deprecated -t,-T,-D options.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-09-06 09:26:10 +02:00
Luca Guerra
36d6951e77 new(falco): add test for object cli configuration, minor test fix
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-06 09:25:11 +02:00
Luca Guerra
5b6810a51e new(falco): enable -o key={object} configuration
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-09-06 09:25:11 +02:00
harshitasao
24a70da976 made required changes
Signed-off-by: harshitasao <harshitasao@gmail.com>
2024-09-04 22:00:06 +02:00
harshitasao
9f180b989a fixed the token-permission and pinned-dependencies issue
Signed-off-by: harshitasao <harshitasao@gmail.com>
2024-09-04 22:00:06 +02:00
Bill Vandenberk
4053c6e1cc Apply suggestions from code review
Formatting and case, adds links

Co-authored-by: Federico Di Pierro <nierro92@gmail.com>
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Bill Vandenberk
8030c03334 fix spelling
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Bill Vandenberk
32550dad26 add newline to end of config file
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Bill Vandenberk
c587d8efc7 add missing changes
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Bill Vandenberk
123d5ba244 add config file, update readme, config mount, remove command override
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Bill Vandenberk
48442be91e adds docker-compose config
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-30 10:22:41 +02:00
Melissa Kilby
8a3cb7608a chore: updat config schema w/ container_engines
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 12:13:26 +02:00
Melissa Kilby
898e060544 chore: update desc in falco.yaml
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 12:13:26 +02:00
Melissa Kilby
08d5ac92ad update(engine): move some contaienr engines debug message to init inspector
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 12:13:26 +02:00
Melissa Kilby
e8afcc55cc update(engine): address reviewers comments wrt container_engines config
Co-authored-by: Federico Di Pierro <nierro92@gmail.com>
Co-authored-by: Leonardo Grasso <me@leonardograsso.com>
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 12:13:26 +02:00
Melissa Kilby
f6ffa75d74 new(config): add container_engines config to falco.yaml
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 12:13:26 +02:00
Melissa Kilby
f8398213ba update(metrics): always refresh ifinfo
Because libs constantly refreshes them, it's fine to re-create the JSON
each time

Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 10:18:26 +02:00
Melissa Kilby
1caece2cf9 update(metrics): use new libs addr_to_string methods for host_ifinfo_json
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 10:18:26 +02:00
Melissa Kilby
23b412ea3c new(metrics): add host_ifinfo metric
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-27 10:18:26 +02:00
Fede Barcelona
7a684fdf13 feat(cmake): add conditional builds for falcoctl and rules
There are systems, like Nix derivations where the build process
does not have network access in order to enforce reproducibility.
This patch allows people building Falco to optionally skip the build
of falcoctl with `-DADD_FALCOCTL_DEPENDENCY=OFF` and point to their own
self-backed, or pre-fetched rules files with
`-DFALCOSECURITY_RULES_FALCO_PATH=<some-path>` and
`-DFALCOSECURITY_RULES_LOCAL_PATH=<some-path>`.

For context, I needed to apply these patches while building the
project with Nix in https://github.com/tembleking/falco-nix but I think
that would be benefitial for the community to have also these options
open, and that would also make Falco feasible to be added to the
nixpkgs repository at https://github.com/nixos/nixpkgs

Signed-off-by: Fede Barcelona <fede_rico_94@hotmail.com>
2024-08-27 10:15:26 +02:00
dependabot[bot]
8920701385 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `baecf18` to `b6ad373`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](baecf181ea...b6ad373719)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-08-26 18:27:25 +02:00
Federico Di Pierro
db52442b3f fix(userspace/falco): fixed windows build by enforcing NOMINMAX compile definition.
Also, minified config schema, since the big schema string leads to an MSVC compiler error.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
3fff994b19 chore(userspace/falco): include numeric header for std::accumulate.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
05bbe74d69 fix(unit_tests): skip Configuration.schema_validate_config test if Falco config is not present.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
d1c715e7a8 chore(unit_tests,userspace): use nlhomann json instead of jsoncpp.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
be927edfe8 new(userspace/falco,unit_tests): added new tests around schema validation feature.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
94dc7da986 cleanup(unit_tests,userspace/falco): moved all config validation logic to be more testable.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
6dfdfdd649 chore(unit_tests): moved config_files and env vars config tests to their own source file.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
c807727475 chore(userspace/falco): use minProperties where needed.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
5c551df116 new(userspace/falco): validate loaded configuration files against config schema.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 18:06:25 +02:00
Federico Di Pierro
4e45152521 fix(cmake,userspace/falco): bumped libs to latest master.
Also, fixes some newly introduced API breaks.

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-08-26 15:51:25 +02:00
Luca Guerra
1886aca8b5 update(falco): update metrics interface
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-08-26 15:51:25 +02:00
Luca Guerra
d93c51c929 update(build): update libs to latest master
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-08-26 15:51:25 +02:00
Luca Guerra
784d2d27cb update(cmake): bump libs and drivers to fix compilation issue
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-08-26 15:51:25 +02:00
Jason Dellaluce
6783cc7055 fix(unit_tests): adapt tests to new engine warning formats
Signed-off-by: Jason Dellaluce <jasondellaluce@gmail.com>
2024-08-26 15:51:25 +02:00
Jason Dellaluce
4ae942f1c6 update(cmake): bump libs and driver to latest master
Signed-off-by: Jason Dellaluce <jasondellaluce@gmail.com>
2024-08-26 15:51:25 +02:00
dependabot[bot]
d3191bdf15 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `342b20d` to `baecf18`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](342b20dc7d...baecf181ea)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-08-20 10:46:43 +02:00
Luca Guerra
6824bdb660 update(docs): update changelog for 0.38.2
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-08-19 16:34:41 +02:00
Bill Vandenberk
1755527ad7 Add Tulip Retail to adopters list
Signed-off-by: Bill Vandenberk <bill@vandenberk.me>
2024-08-08 15:00:54 +02:00
Melissa Kilby
33a0d9c6ab fix(metrics/prometheus): adopt best prometheus practices for rules counters and sha256 file metrics
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-08-05 11:39:40 +02:00
dependabot[bot]
7a9048125f chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `068f0f2` to `342b20d`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](068f0f2dc9...342b20dc7d)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-08-02 19:55:30 +02:00
dependabot[bot]
d12b0ce290 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `28b98b6` to `068f0f2`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](28b98b6f5f...068f0f2dc9)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-23 14:03:45 +02:00
Samuel Gaist
0e0428c5f7 vote: request to join maintainers
Signed-off-by: Samuel Gaist <samuel.gaist@idiap.ch>
2024-07-08 16:45:35 +02:00
Federico Di Pierro
1f2943da1e chore(ci): add ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION:true env to enforce the usage of node16.
Centos:7 does not support node20 (glibc required mismatch).

Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-07-08 07:03:33 +02:00
Federico Di Pierro
a9f3d98a00 chore(ci): use correct vault repo path for arm64.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-07-08 07:03:33 +02:00
Federico Di Pierro
aa42e380e0 fix(ci): use vault.centos.org for centos:7 CI build.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-07-08 07:03:33 +02:00
dependabot[bot]
5283dca335 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `c0a9bf1` to `28b98b6`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](c0a9bf17d5...28b98b6f5f)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-07-03 11:27:18 +02:00
harshitasao
c25ded8f39 made some required changes
Signed-off-by: harshitasao <harshitasao@gmail.com>
2024-07-02 11:16:12 +02:00
harshitasao
a9ef7f9f97 added the openssf scorecard badge
Signed-off-by: harshitasao <harshitasao@gmail.com>
2024-07-02 11:16:12 +02:00
dependabot[bot]
62a448f805 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `ea57e78` to `c0a9bf1`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](ea57e78ea1...c0a9bf17d5)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-27 14:45:50 +02:00
Federico Di Pierro
4a4ed1e118 update(userspace/engine): bump engine version and checksum.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-26 10:32:44 +02:00
Federico Di Pierro
c602be596b update(docs): update CHANGELOG for 0.38.1
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-26 10:32:44 +02:00
Federico Di Pierro
24eec1e92a update(cmake,userspace): bump libs and driver to latest master.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-26 10:32:44 +02:00
Mark Stemm
a3bf8b472b If rule compilation fails, return immediately
There's no need to populate rulesets with the output if compilation
failed.

Signed-off-by: Mark Stemm <mark.stemm@gmail.com>
2024-06-25 18:27:39 +02:00
Mark Stemm
adeca79d1c Modify evttype_index_ruleset to derive from indexable_ruleset
Modify evttype_index_ruleset to derive from indexable_ruleset instead
of having its own implementation of segregating filters by ruleset
id/event type.

An evttype_index_wrapper contains a falco rule and filter, and
implements the methods required by the template. run_wrappers()
evaluate the filter as before, without the segregation by ruleset
id/event type.

Signed-off-by: Mark Stemm <mark.stemm@gmail.com>
2024-06-20 11:23:12 +02:00
Mark Stemm
bbcfa61d82 Add an indexable ruleset that can split filters by ruleset/evttype
Now that custom rules loading implementations (and related, custom
rulesets) can be swapped into falco in a customizable way, there is
some functionality in evttype_index_ruleset that could be used by
other rulesets, specifically the part that segregates filters by
ruleset and enables/disables filters based on name substring + tags.

To allow for this, create a new template indexable_ruleset<class
filter_wrapper> which derives from filter_ruleset and segregates the
filter_wrappers by ruleset. It also optionally segregates
filter_wrappers by event type.

The filter_wrapper class is an object that can return a name, tags,
and sc/event codes.

The main interfaces for classes that derive from indexable_ruleset are:

- add_wrapper(), which provides a filter_wrapper to the
  indexable_ruleset. This is generally called from
  add()/add_compile_output(), which must be implemented by the derived class.
- run_wrappers(), which must be implemented by the derived class and
  is called for event processing.

Most of the methods required by filter_ruleset are implemented by
indexable_ruleset and do not need to be implemented by the derived
class.

Signed-off-by: Mark Stemm <mark.stemm@gmail.com>
2024-06-20 11:23:12 +02:00
Gianmatteo Palmieri
3e91a27538 new(metrics): enable plugins metrics
Signed-off-by: Gianmatteo Palmieri <mail@gian.im>
Co-authored-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-06-13 16:32:48 +02:00
Federico Di Pierro
0e754aec14 chore(userspace): bump engine version and checksum.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-13 13:40:48 +02:00
Federico Di Pierro
0e4c580c1e update(cmake): bump libs to master.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-13 13:40:48 +02:00
Luca Guerra
b8e5e2e8dd update(engine): allow using -p to pass a format to plugin events
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-06-11 09:19:39 +02:00
dependabot[bot]
1c31390c56 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `df963b6` to `ea57e78`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](df963b6bcd...ea57e78ea1)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-11 09:18:40 +02:00
Luca Guerra
8a59cee355 cleanup(falco): clarify that --print variants only affect syscalls
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-06-06 09:46:22 +02:00
Gianmatteo Palmieri
1c66b640f2 Revert "fix(engine): apply output substitutions for all sources"
This reverts commit 4ef7c9553a.

Signed-off-by: Gianmatteo Palmieri <mail@gian.im>
2024-06-05 12:43:19 +02:00
Federico Di Pierro
35395728cc chore(ci): enable dummy tests on the testing framework.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-04 10:15:13 +02:00
Melissa Kilby
5777a44ca1 fix(metrics): fix sha256 metric names for prometheus
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-06-04 09:52:13 +02:00
Melissa Kilby
97207d309a fix(metrics): allow each metric output channel to be selected independently
Signed-off-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-06-04 09:52:13 +02:00
dependabot[bot]
f43347da45 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `679a50a` to `df963b6`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](679a50aa5c...df963b6bcd)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-06-03 17:01:10 +02:00
Federico Di Pierro
6687d50fc2 chore(userspace/falco): more extra safety checks on stats collector too.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>

Co-authored-by: Melissa Kilby <melissa.kilby.oss@gmail.com>
2024-06-03 15:56:14 +02:00
Federico Di Pierro
ae71cec507 fix(userspace/falco): fixed falco_metrics::to_text implementation when running with plugins.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-06-03 15:56:14 +02:00
Federico Di Pierro
ba85afa2ab update(cmake): bump libs and driver to master.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-05-31 11:26:59 +02:00
dependabot[bot]
048b9e3dd0 chore(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `9e56293` to `679a50a`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](9e56293b55...679a50aa5c)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-30 16:36:56 +02:00
Luca Guerra
1ddfde61f5 update(docs): update CHANGELOG for 0.38.0
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-05-30 16:35:56 +02:00
Federico Di Pierro
edd93054fd chore(proposals): fix typo.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-05-28 11:05:46 +02:00
Federico Di Pierro
b5316c98bc update(cmake): bump falcoctl to v0.8.0.
Signed-off-by: Federico Di Pierro <nierro92@gmail.com>
2024-05-28 11:05:46 +02:00
Luca Guerra
6c66294e72 chore(build): bump rules to 3.1.0
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-05-27 16:29:43 +02:00
dependabot[bot]
9fd26eaa2e ---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-23 09:51:23 +02:00
Jason Dellaluce
cd1c5f911c refactor(userspace): move falco logger under falco engine
Signed-off-by: Jason Dellaluce <jasondellaluce@gmail.com>
2024-05-23 09:29:23 +02:00
Luca Guerra
40765ca77b chore(gha): update cosign
Signed-off-by: Luca Guerra <luca@guerra.sh>
2024-05-21 11:41:13 +02:00
dependabot[bot]
1e942129b2 build(deps): Bump submodules/falcosecurity-rules
Bumps [submodules/falcosecurity-rules](https://github.com/falcosecurity/rules) from `29c41c4` to `59bf03b`.
- [Release notes](https://github.com/falcosecurity/rules/releases)
- [Commits](29c41c4eed...59bf03bf74)

---
updated-dependencies:
- dependency-name: submodules/falcosecurity-rules
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-21 11:37:13 +02:00
210 changed files with 13002 additions and 10319 deletions

View File

@@ -1,16 +1,36 @@
---
Language: Cpp
BasedOnStyle: LLVM
AccessModifierOffset: -8
BreakBeforeBraces: Allman
BasedOnStyle: Google
AccessModifierOffset: -4
BreakBeforeBraces: Attach
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
BinPackArguments: false
BinPackParameters: false
ColumnLimit: 100
DerivePointerBinding: false
IndentCaseLabels: false
IndentWidth: 4
SpaceAfterTemplateKeyword: false
TabWidth: 4
UseTab: ForIndentation
BreakConstructorInitializers: AfterColon
ColumnLimit: 0
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
DerivePointerAlignment: true
IndentWidth: 8
SortIncludes: false
SpaceAfterTemplateKeyword: false
SortIncludes: Never
SpaceBeforeCtorInitializerColon: false
SpaceBeforeParens: Never
UseTab: Always
InsertNewlineAtEOF: true
---
Language: Proto
DisableFormat: true
---
Language: JavaScript
DisableFormat: true
---
Language: Java
DisableFormat: true

3
.clang-format-ignore Normal file
View File

@@ -0,0 +1,3 @@
# These files contain some JSON schema definitions that are not C++ code
userspace/falco/config_json_schema.h
userspace/engine/rule_json_schema.h

View File

@@ -1,119 +0,0 @@
# --------------------------
# General Formatting Options
# --------------------------
# How wide to allow formatted cmake files
line_width = 120
# How many spaces to tab for indent
tab_size = 2
# If arg lists are longer than this, break them always
max_subargs_per_line = 3
# If true, separate flow control names from their parentheses with a space
separate_ctrl_name_with_space = False
# If true, separate function names from parentheses with a space
separate_fn_name_with_space = False
# If a statement is wrapped to more than one line, than dangle the closing
# parenthesis on it's own line
dangle_parens = False
# If the statement spelling length (including space and parenthesis is larger
# than the tab width by more than this among, then force reject un-nested
# layouts.
max_prefix_chars = 2
# If a candidate layout is wrapped horizontally but it exceeds this many lines,
# then reject the layout.
max_lines_hwrap = 2
# What style line endings to use in the output.
line_ending = 'unix'
# Format command names consistently as 'lower' or 'upper' case
command_case = 'canonical'
# Format keywords consistently as 'lower' or 'upper' case
keyword_case = 'unchanged'
# Specify structure for custom cmake functions
additional_commands = {
"pkg_find": {
"kwargs": {
"PKG": "*"
}
}
}
# A list of command names which should always be wrapped
always_wrap = []
# Specify the order of wrapping algorithms during successive reflow attempts
algorithm_order = [0, 1, 2, 3, 4]
# If true, the argument lists which are known to be sortable will be sorted
# lexicographically
enable_sort = True
# If true, the parsers may infer whether or not an argument list is sortable
# (without annotation).
autosort = False
# If a comment line starts with at least this many consecutive hash characters,
# then don't lstrip() them off. This allows for lazy hash rulers where the first
# hash char is not separated by space
hashruler_min_length = 10
# A dictionary containing any per-command configuration overrides. Currently
# only `command_case` is supported.
per_command = {}
# --------------------------
# Comment Formatting Options
# --------------------------
# What character to use for bulleted lists
bullet_char = '*'
# What character to use as punctuation after numerals in an enumerated list
enum_char = '.'
# enable comment markup parsing and reflow
enable_markup = True
# If comment markup is enabled, don't reflow the first comment block in each
# listfile. Use this to preserve formatting of your copyright/license
# statements.
first_comment_is_literal = False
# If comment markup is enabled, don't reflow any comment block which matches
# this (regex) pattern. Default is `None` (disabled).
literal_comment_pattern = None
# Regular expression to match preformat fences in comments
# default=r'^\s*([`~]{3}[`~]*)(.*)$'
fence_pattern = '^\\s*([`~]{3}[`~]*)(.*)$'
# Regular expression to match rulers in comments
# default=r'^\s*[^\w\s]{3}.*[^\w\s]{3}$'
ruler_pattern = '^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$'
# If true, then insert a space between the first hash char and remaining hash
# chars in a hash ruler, and normalize it's length to fill the column
canonicalize_hashrulers = True
# ---------------------------------
# Miscellaneous Options
# ---------------------------------
# If true, emit the unicode byte-order mark (BOM) at the start of the file
emit_byteorder_mark = False
# Specify the encoding of the input file. Defaults to utf-8.
input_encoding = 'utf-8'
# Specify the encoding of the output file. Defaults to utf-8. Note that cmake
# only claims to support utf-8 so be careful when using anything else
output_encoding = 'utf-8'

254
.cmake-format.json Normal file
View File

@@ -0,0 +1,254 @@
{
"_help_format": "Options affecting formatting.",
"format": {
"_help_disable": [
"Disable formatting entirely, making cmake-format a no-op"
],
"disable": false,
"_help_line_width": [
"How wide to allow formatted cmake files"
],
"line_width": 100,
"_help_tab_size": [
"How many spaces to tab for indent"
],
"tab_size": 4,
"_help_use_tabchars": [
"If true, lines are indented using tab characters (utf-8",
"0x09) instead of <tab_size> space characters (utf-8 0x20).",
"In cases where the layout would require a fractional tab",
"character, the behavior of the fractional indentation is",
"governed by <fractional_tab_policy>"
],
"use_tabchars": true,
"_help_fractional_tab_policy": [
"If <use_tabchars> is True, then the value of this variable",
"indicates how fractional indentions are handled during",
"whitespace replacement. If set to 'use-space', fractional",
"indentation is left as spaces (utf-8 0x20). If set to",
"`round-up` fractional indentation is replaced with a single",
"tab character (utf-8 0x09) effectively shifting the column",
"to the next tabstop"
],
"fractional_tab_policy": "use-space",
"_help_max_subgroups_hwrap": [
"If an argument group contains more than this many sub-groups",
"(parg or kwarg groups) then force it to a vertical layout."
],
"max_subgroups_hwrap": 2,
"_help_max_pargs_hwrap": [
"If a positional argument group contains more than this many",
"arguments, then force it to a vertical layout."
],
"max_pargs_hwrap": 6,
"_help_max_rows_cmdline": [
"If a cmdline positional group consumes more than this many",
"lines without nesting, then invalidate the layout (and nest)"
],
"max_rows_cmdline": 2,
"_help_separate_ctrl_name_with_space": [
"If true, separate flow control names from their parentheses",
"with a space"
],
"separate_ctrl_name_with_space": false,
"_help_separate_fn_name_with_space": [
"If true, separate function names from parentheses with a",
"space"
],
"separate_fn_name_with_space": false,
"_help_dangle_parens": [
"If a statement is wrapped to more than one line, than dangle",
"the closing parenthesis on its own line."
],
"dangle_parens": true,
"_help_dangle_align": [
"If the trailing parenthesis must be 'dangled' on its on",
"line, then align it to this reference: `prefix`: the start",
"of the statement, `prefix-indent`: the start of the",
"statement, plus one indentation level, `child`: align to",
"the column of the arguments"
],
"dangle_align": "prefix",
"_help_min_prefix_chars": [
"If the statement spelling length (including space and",
"parenthesis) is smaller than this amount, then force reject",
"nested layouts."
],
"min_prefix_chars": 4,
"_help_max_prefix_chars": [
"If the statement spelling length (including space and",
"parenthesis) is larger than the tab width by more than this",
"amount, then force reject un-nested layouts."
],
"max_prefix_chars": 10,
"_help_max_lines_hwrap": [
"If a candidate layout is wrapped horizontally but it exceeds",
"this many lines, then reject the layout."
],
"max_lines_hwrap": 2,
"_help_line_ending": [
"What style line endings to use in the output."
],
"line_ending": "unix",
"_help_command_case": [
"Format command names consistently as 'lower' or 'upper' case"
],
"command_case": "canonical",
"_help_keyword_case": [
"Format keywords consistently as 'lower' or 'upper' case"
],
"keyword_case": "unchanged",
"_help_always_wrap": [
"A list of command names which should always be wrapped"
],
"always_wrap": [],
"_help_enable_sort": [
"If true, the argument lists which are known to be sortable",
"will be sorted lexicographicall"
],
"enable_sort": true,
"_help_autosort": [
"If true, the parsers may infer whether or not an argument",
"list is sortable (without annotation)."
],
"autosort": false,
"_help_require_valid_layout": [
"By default, if cmake-format cannot successfully fit",
"everything into the desired linewidth it will apply the",
"last, most agresive attempt that it made. If this flag is",
"True, however, cmake-format will print error, exit with non-",
"zero status code, and write-out nothing"
],
"require_valid_layout": false,
"_help_layout_passes": [
"A dictionary mapping layout nodes to a list of wrap",
"decisions. See the documentation for more information."
],
"layout_passes": {}
},
"_help_markup": "Options affecting comment reflow and formatting.",
"markup": {
"_help_bullet_char": [
"What character to use for bulleted lists"
],
"bullet_char": "*",
"_help_enum_char": [
"What character to use as punctuation after numerals in an",
"enumerated list"
],
"enum_char": ".",
"_help_first_comment_is_literal": [
"If comment markup is enabled, don't reflow the first comment",
"block in each listfile. Use this to preserve formatting of",
"your copyright/license statements."
],
"first_comment_is_literal": false,
"_help_literal_comment_pattern": [
"If comment markup is enabled, don't reflow any comment block",
"which matches this (regex) pattern. Default is `None`",
"(disabled)."
],
"literal_comment_pattern": null,
"_help_fence_pattern": [
"Regular expression to match preformat fences in comments",
"default= ``r'^\\s*([`~]{3}[`~]*)(.*)$'``"
],
"fence_pattern": "^\\s*([`~]{3}[`~]*)(.*)$",
"_help_ruler_pattern": [
"Regular expression to match rulers in comments default=",
"``r'^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$'``"
],
"ruler_pattern": "^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$",
"_help_explicit_trailing_pattern": [
"If a comment line matches starts with this pattern then it",
"is explicitly a trailing comment for the preceding",
"argument. Default is '#<'"
],
"explicit_trailing_pattern": "#<",
"_help_hashruler_min_length": [
"If a comment line starts with at least this many consecutive",
"hash characters, then don't lstrip() them off. This allows",
"for lazy hash rulers where the first hash char is not",
"separated by space"
],
"hashruler_min_length": 10,
"_help_canonicalize_hashrulers": [
"If true, then insert a space between the first hash char and",
"remaining hash chars in a hash ruler, and normalize its",
"length to fill the column"
],
"canonicalize_hashrulers": true,
"_help_enable_markup": [
"enable comment markup parsing and reflow"
],
"enable_markup": true
},
"_help_lint": "Options affecting the linter",
"lint": {
"_help_disabled_codes": [
"a list of lint codes to disable"
],
"disabled_codes": [],
"_help_function_pattern": [
"regular expression pattern describing valid function names"
],
"function_pattern": "[0-9a-z_]+",
"_help_macro_pattern": [
"regular expression pattern describing valid macro names"
],
"macro_pattern": "[0-9A-Z_]+",
"_help_global_var_pattern": [
"regular expression pattern describing valid names for",
"variables with global (cache) scope"
],
"global_var_pattern": "[A-Z][0-9A-Z_]+",
"_help_internal_var_pattern": [
"regular expression pattern describing valid names for",
"variables with global scope (but internal semantic)"
],
"internal_var_pattern": "_[A-Z][0-9A-Z_]+",
"_help_local_var_pattern": [
"regular expression pattern describing valid names for",
"variables with local scope"
],
"local_var_pattern": "[a-z][a-z0-9_]+",
"_help_private_var_pattern": [
"regular expression pattern describing valid names for",
"privatedirectory variables"
],
"private_var_pattern": "_[0-9a-z_]+",
"_help_public_var_pattern": [
"regular expression pattern describing valid names for public",
"directory variables"
],
"public_var_pattern": "[A-Z][0-9A-Z_]+",
"_help_argument_var_pattern": [
"regular expression pattern describing valid names for",
"function/macro arguments and loop variables."
],
"argument_var_pattern": "[a-z][a-z0-9_]+",
"_help_keyword_pattern": [
"regular expression pattern describing valid names for",
"keywords used in functions or macros"
],
"keyword_pattern": "[A-Z][0-9A-Z_]+",
"_help_max_conditionals_custom_parser": [
"In the heuristic for C0201, how many conditionals to match",
"within a loop in before considering the loop a parser."
],
"max_conditionals_custom_parser": 2,
"_help_min_statement_spacing": [
"Require at least this many newlines between statements"
],
"min_statement_spacing": 1,
"_help_max_statement_spacing": [
"Require no more than this many newlines between statements"
],
"max_statement_spacing": 2,
"max_returns": 6,
"max_branches": 12,
"max_arguments": 5,
"max_localvars": 15,
"max_statements": 50
}
}

2
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,2 @@
# This commit formatted the Falco code for the first time.
50b98b30e588eadce641136da85bc94a60eb6a3d

View File

@@ -12,6 +12,9 @@ concurrency:
group: ${{ github.head_ref || github.run_id }}
cancel-in-progress: true
permissions:
contents: read
jobs:
fetch-version:
uses: ./.github/workflows/reusable_fetch_version.yaml

View File

@@ -18,6 +18,9 @@ on:
# The branches below must be a subset of the branches above
branches: [ "master" ]
permissions:
contents: read
jobs:
analyze:
name: Analyze

View File

@@ -1,6 +1,10 @@
name: Codespell
on:
pull_request:
permissions:
contents: read
jobs:
codespell:
runs-on: ubuntu-latest

View File

@@ -9,6 +9,9 @@ on:
- 'userspace/engine/*.cpp'
- 'userspace/engine/*.h'
permissions:
contents: read
jobs:
paths-filter:
runs-on: ubuntu-latest

38
.github/workflows/format.yaml vendored Normal file
View File

@@ -0,0 +1,38 @@
name: Format code
on:
pull_request:
push:
branches:
- master
- "release/**"
jobs:
format:
name: format code 🐲
runs-on: ubuntu-22.04
steps:
- name: Checkout repository 🎉
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0
with:
fetch-depth: 0
- name: Install deps ⛓️
run: |
sudo apt update -y
sudo apt install -y --no-install-recommends ca-certificates pip git
pip install pre-commit
- name: Run pre-commit ©️
run: |
pre-commit run --all-files
- name: Generate the git-diff 🚒
if: failure()
run: git diff > format_diff.patch
- name: Upload the git diff artifact 📦
if: failure()
uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3
with:
name: format_diff.patch
path: ./format_diff.patch

View File

@@ -6,12 +6,15 @@ on:
- 'release/**'
- 'maintainers/**'
permissions:
contents: read
jobs:
insecure-api:
name: check-insecure-api
runs-on: ubuntu-latest
container:
image: returntocorp/semgrep:1.41.0@sha256:85956fbe795a0e8a3825d5252f175887c0e0c6ce7a766a07062c0fb68415cd67
image: semgrep/semgrep:1.85.0@sha256:b4c2272e0a2e59ca551ff96d3bbae657bd2b7356e339af557b27a96d9e751544
steps:
- name: Checkout Falco ⤵️
uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v4.1.0

View File

@@ -6,7 +6,7 @@ on:
# Checks if any concurrent jobs is running for master CI and eventually cancel it
concurrency:
group: ci-master
cancel-in-progress: true
cancel-in-progress: true
jobs:
fetch-version:

View File

@@ -7,7 +7,7 @@ on:
concurrency:
group: ci-release
cancel-in-progress: true
jobs:
release-settings:
runs-on: ubuntu-latest
@@ -16,7 +16,7 @@ jobs:
bucket_suffix: ${{ steps.get_settings.outputs.bucket_suffix }}
steps:
- name: Get latest release
uses: rez0n/actions-github-release@v2.0
uses: rez0n/actions-github-release@27a57820ee808f8fd940c8a9d1f7188f854aa2b5 # v2.0
id: latest_release
env:
token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -33,6 +33,9 @@ on:
default: ''
type: string
permissions:
contents: read
jobs:
build-and-test:
# See https://github.com/actions/runner/issues/409#issuecomment-1158849936

View File

@@ -24,6 +24,10 @@ on:
# then we upload all the tarballs to be later downloaded by reusable_publish_docker workflow.
# In this way, we don't need to publish any arch specific image,
# and this "build" workflow is actually only building images.
permissions:
contents: read
jobs:
build-docker:
# See https://github.com/actions/runner/issues/409#issuecomment-1158849936

View File

@@ -21,6 +21,9 @@ on:
type: boolean
default: false
permissions:
contents: read
jobs:
build-modern-bpf-skeleton:
# See https://github.com/actions/runner/issues/409#issuecomment-1158849936
@@ -49,15 +52,37 @@ jobs:
retention-days: 1
build-packages:
env:
ACTIONS_ALLOW_USE_UNSECURE_NODE_VERSION: true
# See https://github.com/actions/runner/issues/409#issuecomment-1158849936
runs-on: ${{ (inputs.arch == 'aarch64' && 'actuated-arm64-8cpu-16gb') || 'ubuntu-latest' }}
needs: [build-modern-bpf-skeleton]
container: centos:7
steps:
# Always install deps before invoking checkout action, to properly perform a full clone.
- name: Install build dependencies
- name: Fix mirrors to use vault.centos.org
run: |
sed -i s/mirror.centos.org/vault.centos.org/g /etc/yum.repos.d/*.repo
sed -i s/^#.*baseurl=http/baseurl=https/g /etc/yum.repos.d/*.repo
sed -i s/^mirrorlist=http/#mirrorlist=https/g /etc/yum.repos.d/*.repo
- name: Install scl repos
run: |
yum -y install centos-release-scl
- name: Fix new mirrors to use vault.centos.org
run: |
sed -i s/mirror.centos.org/vault.centos.org/g /etc/yum.repos.d/*.repo
sed -i s/^#.*baseurl=http/baseurl=https/g /etc/yum.repos.d/*.repo
sed -i s/^mirrorlist=http/#mirrorlist=https/g /etc/yum.repos.d/*.repo
- name: Fix arm64 scl repos to use correct mirror
if: inputs.arch == 'aarch64'
run: |
sed -i 's/vault.centos.org\/centos/vault.centos.org\/altarch/g' /etc/yum.repos.d/CentOS-SCLo-scl*.repo
- name: Install build deps
run: |
yum -y install devtoolset-9-gcc devtoolset-9-gcc-c++
source /opt/rh/devtoolset-9/enable
yum install -y wget git make m4 rpm-build elfutils-libelf-devel perl-IPC-Cmd devtoolset-9-libasan-devel devtoolset-9-libubsan-devel

View File

@@ -6,6 +6,9 @@ on:
description: "Falco version"
value: ${{ jobs.fetch-version.outputs.version }}
permissions:
contents: read
jobs:
# We need to use an ubuntu-latest to fetch Falco version because
# Falco version is computed by some cmake scripts that do git sorceries

View File

@@ -152,9 +152,7 @@ jobs:
- name: Setup Cosign
if: inputs.sign
uses: sigstore/cosign-installer@11086d25041f77fe8fe7b9ea4e48e3b9192b8f19 # v3.1.2
with:
cosign-release: v2.0.2
uses: sigstore/cosign-installer@59acb6260d9c0ba8f4a2f9d9b48431a222b68e20 # v3.5.0
- name: Sign images with cosign
if: inputs.sign

View File

@@ -21,6 +21,9 @@ on:
default: false
type: boolean
permissions:
contents: read
jobs:
test-packages:
# See https://github.com/actions/runner/issues/409#issuecomment-1158849936
@@ -54,11 +57,12 @@ jobs:
- name: Run tests
env:
LSAN_OPTIONS: "intercept_tls_get_addr=0"
uses: falcosecurity/testing@main
uses: falcosecurity/testing@main
with:
test-falco: 'true'
test-falcoctl: 'true'
test-k8saudit: 'true'
test-dummy: 'true'
static: ${{ inputs.static && 'true' || 'false' }}
test-drivers: ${{ inputs.arch == 'x86_64' && 'true' || 'false' }}
show-all: 'true'

View File

@@ -1,6 +1,9 @@
name: StaticAnalysis
on:
pull_request:
permissions:
contents: read
jobs:
staticanalysis:
runs-on: ubuntu-22.04

23
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,23 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
fail_fast: false
minimum_pre_commit_version: '0'
repos:
- repo: https://github.com/cheshirekow/cmake-format-precommit
rev: v0.6.13
hooks:
- id: cmake-format
stages: [commit]
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v18.1.8
hooks:
- id: clang-format
types_or: [c++, c]
stages: [commit]
- repo: local
hooks:
- id: dco-hook-local
name: DCO hook local
entry: ./tools/local_hooks/dco-pre-commit-msg.sh
language: script
stages: [prepare-commit-msg]

View File

@@ -74,6 +74,8 @@ This is a list of production adopters of Falco (in alphabetical order):
* [Thought Machine](https://www.thoughtmachine.net) Thought Machine builds Vault Core and Vault Payments: cloud-native core and payments technology enabling banks and fintechs to remain competitive and flourish into the future. Vault Core and Vault Payments are the foundation layer of a bank's technology stack. They can run any bank, any product, and any payment set. Thought Machine uses Falco to perform cloud agnostic real time detections of suspicious container behaviour.
* [Tulip Retail](https://tulip.com) Tulip Retail uses Falco to monitor container activity in our environments. It's numerous integration points, easy deployment and easily customizable rules were the main reasons we chose Falco.
* [Vinted](https://vinted.com/) Vinted uses Falco to continuously monitor container activities, identifying security threats, and ensuring compliance. The container-native approach, rule-based real-time threat detection, community support, extensibility, and compliance capabilities are the main factors why we chose it to enhance Vinted Kubernetes security. Falco Sidekick is used to send critical and warning severity alerts to our incident management solution (RTIR).
* [Xenit AB](https://xenit.se/contact/) Xenit is a growth company with services within cloud and digital transformation. We provide an open-source Kubernetes framework that we leverage to help our customers get their applications to production as quickly and as securely as possible. We use Falco's detection capabilities to identify anomalous behaviour within our clusters in both Azure and AWS.

View File

@@ -1,5 +1,290 @@
# Change Log
## v0.39.1
Released on 2024-10-09
### Bug Fixes
* fix(engine): allow null init_config for plugin info [[#3372](https://github.com/falcosecurity/falco/pull/3372)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(engine): fix parsing issues in -o key={object} when the object definition contains a comma [[#3363](https://github.com/falcosecurity/falco/pull/3363)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(userspace/falco): fix event set selection for plugin with parsing capability [[#3368](https://github.com/falcosecurity/falco/pull/3368)] - [@FedeDP](https://github.com/FedeDP)
### Statistics
| MERGED PRS | NUMBER |
|-----------------|--------|
| Not user-facing | 0 |
| Release note | 3 |
| Total | 3 |
## v0.39.0
Released on 2024-10-01
### Breaking Changes :warning:
* fix(falco_metrics)!: split tags label into multiple `tag_`-prefixed labels [[#3337](https://github.com/falcosecurity/falco/pull/3337)] - [@ekoops](https://github.com/ekoops)
* fix(falco_metrics)!: use full name for configs and rules files [[#3337](https://github.com/falcosecurity/falco/pull/3337)] - [@ekoops](https://github.com/ekoops)
* update(falco_metrics)!: rearrange `n_evts_cpu` and `n_drops_cpu` Prometheus metrics to follow best practices [[#3319](https://github.com/falcosecurity/falco/pull/3319)] - [@incertum](https://github.com/incertum)
* cleanup(userspace/falco)!: drop deprecated -t,-T,-D options. [[#3311](https://github.com/falcosecurity/falco/pull/3311)] - [@FedeDP](https://github.com/FedeDP)
### Major Changes
* feat(stats): add host_netinfo networking information stats family [[#3344](https://github.com/falcosecurity/falco/pull/3344)] - [@ekoops](https://github.com/ekoops)
* new(falco): add json_include_message_property to have a message field without date and priority [[#3314](https://github.com/falcosecurity/falco/pull/3314)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(userspace/falco,userspace/engine): rule json schema validation [[#3313](https://github.com/falcosecurity/falco/pull/3313)] - [@FedeDP](https://github.com/FedeDP)
* new(falco): introduce append_output configuration [[#3308](https://github.com/falcosecurity/falco/pull/3308)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(userspace/falco): added --config-schema action to print config schema [[#3312](https://github.com/falcosecurity/falco/pull/3312)] - [@FedeDP](https://github.com/FedeDP)
* new(falco): enable CLI options with -o key={object} [[#3310](https://github.com/falcosecurity/falco/pull/3310)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(config): add `container_engines` config to falco.yaml [[#3266](https://github.com/falcosecurity/falco/pull/3266)] - [@incertum](https://github.com/incertum)
* new(metrics): add host_ifinfo metric [[#3253](https://github.com/falcosecurity/falco/pull/3253)] - [@incertum](https://github.com/incertum)
* new(userspace,unit_tests): validate configs against schema [[#3302](https://github.com/falcosecurity/falco/pull/3302)] - [@FedeDP](https://github.com/FedeDP)
### Minor Changes
* update(falco): upgrade libs to 0.18.1 [[#3349](https://github.com/falcosecurity/falco/pull/3349)] - [@LucaGuerra](https://github.com/LucaGuerra)
* update(systemd): users can refer to systemd falco services with a consistent unique alias falco.service [[#3332](https://github.com/falcosecurity/falco/pull/3332)] - [@ekoops](https://github.com/ekoops)
* update(cmake): bump libs to 0.18.0 and driver to 7.3.0+driver. [[#3330](https://github.com/falcosecurity/falco/pull/3330)] - [@FedeDP](https://github.com/FedeDP)
* chore(userspace/falco): deprecate `cri` related CLI options. [[#3329](https://github.com/falcosecurity/falco/pull/3329)] - [@FedeDP](https://github.com/FedeDP)
* update(cmake): bumped falcoctl to v0.10.0 and rules to 3.2.0 [[#3327](https://github.com/falcosecurity/falco/pull/3327)] - [@FedeDP](https://github.com/FedeDP)
* update(falco_metrics): change prometheus rules metric naming [[#3324](https://github.com/falcosecurity/falco/pull/3324)] - [@incertum](https://github.com/incertum)
### Bug Fixes
* fix(falco): allow disable_cri_async from both CLI and config [[#3353](https://github.com/falcosecurity/falco/pull/3353)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(engine): sync outputs before printing stats at shutdown [[#3338](https://github.com/falcosecurity/falco/pull/3338)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(falco): allow plugin init_config map in json schema [[#3335](https://github.com/falcosecurity/falco/pull/3335)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(userspace/falco): properly account for plugin with CAP_PARSING when computing interesting sc set [[#3334](https://github.com/falcosecurity/falco/pull/3334)] - [@FedeDP](https://github.com/FedeDP)
### Non user-facing changes
* feat(cmake): add conditional builds for falcoctl and rules paths [[#3305](https://github.com/falcosecurity/falco/pull/3305)] - [@tembleking](https://github.com/tembleking)
* cleanup(falco): ignore lint commit [[#3354](https://github.com/falcosecurity/falco/pull/3354)] - [@LucaGuerra](https://github.com/LucaGuerra)
* chore(falco): apply code formatting [[#3350](https://github.com/falcosecurity/falco/pull/3350)] - [@poiana](https://github.com/poiana)
* chore: ignore_some_files for clang format [[#3351](https://github.com/falcosecurity/falco/pull/3351)] - [@Andreagit97](https://github.com/Andreagit97)
* sync: release 0.39.x [[#3340](https://github.com/falcosecurity/falco/pull/3340)] - [@FedeDP](https://github.com/FedeDP)
* fix(userspace/engine): improve rule json schema to account for `source` and `required_plugin_versions` [[#3328](https://github.com/falcosecurity/falco/pull/3328)] - [@FedeDP](https://github.com/FedeDP)
* cleanup(falco): use header file for json schema [[#3325](https://github.com/falcosecurity/falco/pull/3325)] - [@LucaGuerra](https://github.com/LucaGuerra)
* update(engine): modify append_output format [[#3322](https://github.com/falcosecurity/falco/pull/3322)] - [@LucaGuerra](https://github.com/LucaGuerra)
* chore: scaffolding for enabling code formatting [[#3321](https://github.com/falcosecurity/falco/pull/3321)] - [@Andreagit97](https://github.com/Andreagit97)
* update(cmake): bump libs and driver to 0.18.0-rc1. [[#3320](https://github.com/falcosecurity/falco/pull/3320)] - [@FedeDP](https://github.com/FedeDP)
* fix(ci): restore master and release CI workflow permissions. [[#3317](https://github.com/falcosecurity/falco/pull/3317)] - [@FedeDP](https://github.com/FedeDP)
* fixed the token-permission and pinned-dependencies issue [[#3299](https://github.com/falcosecurity/falco/pull/3299)] - [@harshitasao](https://github.com/harshitasao)
* update(cmake): bump falcoctl to v0.10.0-rc1 [[#3316](https://github.com/falcosecurity/falco/pull/3316)] - [@alacuku](https://github.com/alacuku)
* ci(insecure-api): update semgrep docker image [[#3315](https://github.com/falcosecurity/falco/pull/3315)] - [@francesco-furlan](https://github.com/francesco-furlan)
* Add demo environment instructions and docker-config files [[#3295](https://github.com/falcosecurity/falco/pull/3295)] - [@bbl232](https://github.com/bbl232)
* chore(deps): Bump submodules/falcosecurity-rules from `baecf18` to `b6ad373` [[#3301](https://github.com/falcosecurity/falco/pull/3301)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bump libs and driver to latest master [[#3283](https://github.com/falcosecurity/falco/pull/3283)] - [@jasondellaluce](https://github.com/jasondellaluce)
* chore(deps): Bump submodules/falcosecurity-rules from `342b20d` to `baecf18` [[#3298](https://github.com/falcosecurity/falco/pull/3298)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore(deps): Bump submodules/falcosecurity-rules from `068f0f2` to `342b20d` [[#3288](https://github.com/falcosecurity/falco/pull/3288)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* vote: add sgaist to OWNERS [[#3264](https://github.com/falcosecurity/falco/pull/3264)] - [@sgaist](https://github.com/sgaist)
* Add Tulip Retail to adopters list [[#3291](https://github.com/falcosecurity/falco/pull/3291)] - [@bbl232](https://github.com/bbl232)
* chore(deps): Bump submodules/falcosecurity-rules from `28b98b6` to `068f0f2` [[#3282](https://github.com/falcosecurity/falco/pull/3282)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore(deps): Bump submodules/falcosecurity-rules from `c0a9bf1` to `28b98b6` [[#3267](https://github.com/falcosecurity/falco/pull/3267)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* Added the OpenSSF Scorecard Badge [[#3250](https://github.com/falcosecurity/falco/pull/3250)] - [@harshitasao](https://github.com/harshitasao)
* chore(deps): Bump submodules/falcosecurity-rules from `ea57e78` to `c0a9bf1` [[#3247](https://github.com/falcosecurity/falco/pull/3247)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake,userspace): bump libs and driver to latest master. [[#3263](https://github.com/falcosecurity/falco/pull/3263)] - [@FedeDP](https://github.com/FedeDP)
* If rule compilation fails, return immediately [[#3260](https://github.com/falcosecurity/falco/pull/3260)] - [@mstemm](https://github.com/mstemm)
* new(userspace/engine): generalize indexable ruleset [[#3251](https://github.com/falcosecurity/falco/pull/3251)] - [@mstemm](https://github.com/mstemm)
* update(cmake): bump libs to master. [[#3249](https://github.com/falcosecurity/falco/pull/3249)] - [@FedeDP](https://github.com/FedeDP)
* chore(deps): Bump submodules/falcosecurity-rules from `df963b6` to `ea57e78` [[#3240](https://github.com/falcosecurity/falco/pull/3240)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore(ci): enable dummy tests on the testing framework. [[#3233](https://github.com/falcosecurity/falco/pull/3233)] - [@FedeDP](https://github.com/FedeDP)
* chore(deps): Bump submodules/falcosecurity-rules from `679a50a` to `df963b6` [[#3231](https://github.com/falcosecurity/falco/pull/3231)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bump libs and driver to master. [[#3225](https://github.com/falcosecurity/falco/pull/3225)] - [@FedeDP](https://github.com/FedeDP)
* chore(deps): Bump submodules/falcosecurity-rules from `9e56293` to `679a50a` [[#3222](https://github.com/falcosecurity/falco/pull/3222)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(docs): update CHANGELOG for 0.38.0 (master branch) [[#3224](https://github.com/falcosecurity/falco/pull/3224)] - [@LucaGuerra](https://github.com/LucaGuerra)
### Statistics
| MERGED PRS | NUMBER |
|-----------------|--------|
| Not user-facing | 35 |
| Release note | 22 |
| Total | 57 |
## v0.38.2
Released on 2024-08-19
### Bug Fixes
* fix(engine): fix metrics names to better adhere to best practices [[#3272](https://github.com/falcosecurity/falco/pull/3272)] - [@incertum](https://github.com/incertum)
* fix(ci): use vault.centos.org for centos:7 CI build. [[#3274](https://github.com/falcosecurity/falco/pull/3274)] - [@FedeDP](https://github.com/FedeDP)
## v0.38.1
Released on 2024-06-19
### Major Changes
* new(metrics): enable plugins metrics [[#3228](https://github.com/falcosecurity/falco/pull/3228)] - [@mrgian](https://github.com/mrgian)
### Minor Changes
* cleanup(falco): clarify that --print variants only affect syscalls [[#3238](https://github.com/falcosecurity/falco/pull/3238)] - [@LucaGuerra](https://github.com/LucaGuerra)
* update(engine): enable -p option for all sources, -pk, -pc etc only for syscall sources [[#3239](https://github.com/falcosecurity/falco/pull/3239)] - [@LucaGuerra](https://github.com/LucaGuerra)
### Bug Fixes
* fix(engine): enable output substitution only for syscall rules, prevent engine from exiting with validation errors when a plugin is loaded and -pc/pk is specified [[#3236](https://github.com/falcosecurity/falco/pull/3236)] - [@mrgian](https://github.com/mrgian)
* fix(metrics): allow each metric output channel to be selected independently [[#3232](https://github.com/falcosecurity/falco/pull/3232)] - [@incertum](https://github.com/incertum)
* fix(userspace/falco): fixed `falco_metrics::to_text` implementation when running with plugins [[#3230](https://github.com/falcosecurity/falco/pull/3230)] - [@FedeDP](https://github.com/FedeDP)
### Statistics
| MERGED PRS | NUMBER |
|-----------------|--------|
| Not user-facing | 0 |
| Release note | 6 |
| Total | 6 |
## v0.38.0
Released on 2024-05-30
### Breaking Changes :warning:
* new(scripts,docker)!: enable automatic driver selection logic in packages and docker images. Modern eBPF is now also the default driver and the highest priority one in the new driver selection logic. [[#3154](https://github.com/falcosecurity/falco/pull/3154)] - [@FedeDP](https://github.com/FedeDP)
* cleanup(falco.yaml)!: remove some deprecated configs [[#3087](https://github.com/falcosecurity/falco/pull/3087)] - [@Andreagit97](https://github.com/Andreagit97)
* cleanup(docker)!: remove unused builder dockerfile [[#3088](https://github.com/falcosecurity/falco/pull/3088)] - [@Andreagit97](https://github.com/Andreagit97)
More details: https://falco.org/blog/falco-0-38-0/#breaking-changes-and-deprecations
### Major Changes
* new(webserver): a metrics endpoint has been added providing prometheus metrics. It can be optionally enabled using the new `metrics.prometheus_enabled` configuration option. It will only be activated if the `metrics.enabled` is true as well. [[#3140](https://github.com/falcosecurity/falco/pull/3140)] - [@sgaist](https://github.com/sgaist)
* new(metrics): add `rules_counters_enabled` option [[#3192](https://github.com/falcosecurity/falco/pull/3192)] - [@incertum](https://github.com/incertum)
* new(build): provide signatures for .tar.gz packages [[#3201](https://github.com/falcosecurity/falco/pull/3201)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(engine): add print_enabled_rules_falco_logger when log_level debug [[#3189](https://github.com/falcosecurity/falco/pull/3189)] - [@incertum](https://github.com/incertum)
* new(falco): allow selecting which rules to load from the configuration file or command line [[#3178](https://github.com/falcosecurity/falco/pull/3178)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(metrics): add file sha256sum metrics for loaded config and rules files [[#3187](https://github.com/falcosecurity/falco/pull/3187)] - [@incertum](https://github.com/incertum)
* new(engine): throw an error when an invalid macro/list name is used [[#3116](https://github.com/falcosecurity/falco/pull/3116)] - [@mrgian](https://github.com/mrgian)
* new(engine): raise warning instead of error on invalid macro/list name [[#3167](https://github.com/falcosecurity/falco/pull/3167)] - [@mrgian](https://github.com/mrgian)
* new(userspace): support split config files [[#3024](https://github.com/falcosecurity/falco/pull/3024)] - [@FedeDP](https://github.com/FedeDP)
* new(engine): enforce unique exceptions names [[#3134](https://github.com/falcosecurity/falco/pull/3134)] - [@mrgian](https://github.com/mrgian)
* new(engine): add warning when appending an exception with no values [[#3133](https://github.com/falcosecurity/falco/pull/3133)] - [@mrgian](https://github.com/mrgian)
* feat(metrics): coherent metrics stats model including few metrics naming changes [[#3129](https://github.com/falcosecurity/falco/pull/3129)] - [@incertum](https://github.com/incertum)
* new(config): add `falco_libs.thread_table_size` [[#3071](https://github.com/falcosecurity/falco/pull/3071)] - [@incertum](https://github.com/incertum)
* new(proposals): introduce on host anomaly detection framework [[#2655](https://github.com/falcosecurity/falco/pull/2655)] - [@incertum](https://github.com/incertum)
### Minor Changes
* update(cmake): bump falcoctl to v0.8.0. [[#3219](https://github.com/falcosecurity/falco/pull/3219)] - [@FedeDP](https://github.com/FedeDP)
* update(rules): update falco-rules to 3.1.0 [[#3217](https://github.com/falcosecurity/falco/pull/3217)] - [@LucaGuerra](https://github.com/LucaGuerra)
* refactor(userspace): move falco logger under falco engine [[#3208](https://github.com/falcosecurity/falco/pull/3208)] - [@jasondellaluce](https://github.com/jasondellaluce)
* chore(docs): apply features adoption and deprecation proposal to config file keys [[#3206](https://github.com/falcosecurity/falco/pull/3206)] - [@FedeDP](https://github.com/FedeDP)
* cleanup(metrics): add original rule name as label [[#3205](https://github.com/falcosecurity/falco/pull/3205)] - [@incertum](https://github.com/incertum)
* update(falco): deprecate options -T, -t and -D [[#3193](https://github.com/falcosecurity/falco/pull/3193)] - [@LucaGuerra](https://github.com/LucaGuerra)
* refactor: bump libs and driver, support field modifiers [[#3186](https://github.com/falcosecurity/falco/pull/3186)] - [@jasondellaluce](https://github.com/jasondellaluce)
* chore(userspace/falco): deprecated old 'rules_file' config key [[#3162](https://github.com/falcosecurity/falco/pull/3162)] - [@FedeDP](https://github.com/FedeDP)
* chore(falco): update falco libs and driver to master (Apr 8th 2024) [[#3158](https://github.com/falcosecurity/falco/pull/3158)] - [@LucaGuerra](https://github.com/LucaGuerra)
* update(build): update libs to 026ffe1d8f1b25c6ccdc09afa2c02afdd3e3f672 [[#3151](https://github.com/falcosecurity/falco/pull/3151)] - [@LucaGuerra](https://github.com/LucaGuerra)
* cleanup: minor adjustments to readme, add new testing section [[#3072](https://github.com/falcosecurity/falco/pull/3072)] - [@incertum](https://github.com/incertum)
* refactor(userspace/engine): reduce allocations during rules loading [[#3065](https://github.com/falcosecurity/falco/pull/3065)] - [@jasondellaluce](https://github.com/jasondellaluce)
* update(CI): publish wasm package as dev-wasm [[#3017](https://github.com/falcosecurity/falco/pull/3017)] - [@Rohith-Raju](https://github.com/Rohith-Raju)
### Bug Fixes
* fix(userspace/falco): fix state initialization avoid a crash during hot reload [[#3190](https://github.com/falcosecurity/falco/pull/3190)] - [@FedeDP](https://github.com/FedeDP)
* fix(userspace/engine): make sure exception fields are not optional in replace mode [[#3108](https://github.com/falcosecurity/falco/pull/3108)] - [@jasondellaluce](https://github.com/jasondellaluce)
* fix(docker): added zstd to driver loader images [[#3203](https://github.com/falcosecurity/falco/pull/3203)] - [@FedeDP](https://github.com/FedeDP)
* fix(engine): raise warning instead of error on not-unique exceptions names [[#3159](https://github.com/falcosecurity/falco/pull/3159)] - [@mrgian](https://github.com/mrgian)
* fix(engine): apply output substitutions for all sources [[#3135](https://github.com/falcosecurity/falco/pull/3135)] - [@mrgian](https://github.com/mrgian)
* fix(userspace/configuration): make sure that folders that would trigger permission denied are not traversed [[#3127](https://github.com/falcosecurity/falco/pull/3127)] - [@sgaist](https://github.com/sgaist)
* fix(engine): logical issue in exceptions condition [[#3115](https://github.com/falcosecurity/falco/pull/3115)] - [@mrgian](https://github.com/mrgian)
* fix(cmake): properly let falcoctl cmake module create /usr/share/falco/plugins/ folder. [[#3105](https://github.com/falcosecurity/falco/pull/3105)] - [@FedeDP](https://github.com/FedeDP)
### Non user-facing changes
* update(scripts/falcoctl): bump falco-rules version to 3 [[#3128](https://github.com/falcosecurity/falco/pull/3128)] - [@alacuku](https://github.com/alacuku)
* build(deps): Bump submodules/falcosecurity-rules from `59bf03b` to `9e56293` [[#3212](https://github.com/falcosecurity/falco/pull/3212)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore(gha): update cosign to v3.5.0 [[#3209](https://github.com/falcosecurity/falco/pull/3209)] - [@LucaGuerra](https://github.com/LucaGuerra)
* build(deps): Bump submodules/falcosecurity-rules from `29c41c4` to `59bf03b` [[#3207](https://github.com/falcosecurity/falco/pull/3207)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bumped libs to 0.17.0-rc1 and falcoctl to v0.8.0-rc6. [[#3204](https://github.com/falcosecurity/falco/pull/3204)] - [@FedeDP](https://github.com/FedeDP)
* build(deps): Bump submodules/falcosecurity-rules from `3f668d0` to `3cac61c` [[#3044](https://github.com/falcosecurity/falco/pull/3044)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* build(deps): Bump submodules/falcosecurity-testing from `ae3950a` to `7abf76f` [[#3094](https://github.com/falcosecurity/falco/pull/3094)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* fix(ci): enforce bundled deps OFF in build-dev CI [[#3118](https://github.com/falcosecurity/falco/pull/3118)] - [@FedeDP](https://github.com/FedeDP)
* build(deps): Bump submodules/falcosecurity-rules from `88a40c8` to `869c9a7` [[#3156](https://github.com/falcosecurity/falco/pull/3156)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bumped falcoctl to v0.8.0-rc5. [[#3199](https://github.com/falcosecurity/falco/pull/3199)] - [@FedeDP](https://github.com/FedeDP)
* build(deps): Bump submodules/falcosecurity-rules from `4f153f5` to `29c41c4` [[#3198](https://github.com/falcosecurity/falco/pull/3198)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bump falcoctl to v0.8.0-rc4 [[#3191](https://github.com/falcosecurity/falco/pull/3191)] - [@FedeDP](https://github.com/FedeDP)
* refactor: smart pointer usage [[#3184](https://github.com/falcosecurity/falco/pull/3184)] - [@federico-sysdig](https://github.com/federico-sysdig)
* build(deps): Bump submodules/falcosecurity-rules from `ec255e6` to `4f153f5` [[#3182](https://github.com/falcosecurity/falco/pull/3182)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(cmake): bumped libs and driver to latest master. [[#3177](https://github.com/falcosecurity/falco/pull/3177)] - [@FedeDP](https://github.com/FedeDP)
* chore(cmake): enable modern bpf build by default. [[#3180](https://github.com/falcosecurity/falco/pull/3180)] - [@FedeDP](https://github.com/FedeDP)
* cleanup(docs): fix typo in license blocks [[#3175](https://github.com/falcosecurity/falco/pull/3175)] - [@LucaGuerra](https://github.com/LucaGuerra)
* chore(docker,scripts): set old eBPF probe as lowest priority driver. [[#3173](https://github.com/falcosecurity/falco/pull/3173)] - [@FedeDP](https://github.com/FedeDP)
* build(deps): Bump submodules/falcosecurity-rules from `869c9a7` to `ec255e6` [[#3170](https://github.com/falcosecurity/falco/pull/3170)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* update(app): close inspectors at teardown time [[#3169](https://github.com/falcosecurity/falco/pull/3169)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(docker): fixed docker entrypoints for driver loading. [[#3168](https://github.com/falcosecurity/falco/pull/3168)] - [@FedeDP](https://github.com/FedeDP)
* fix(docker,scripts): do not load falcoctl driver loader when installing Falco deb package in docker images [[#3166](https://github.com/falcosecurity/falco/pull/3166)] - [@FedeDP](https://github.com/FedeDP)
* update(ci): build both release and debug versions [[#3161](https://github.com/falcosecurity/falco/pull/3161)] - [@LucaGuerra](https://github.com/LucaGuerra)
* chore(userspace/falco): watch all configs files. [[#3160](https://github.com/falcosecurity/falco/pull/3160)] - [@FedeDP](https://github.com/FedeDP)
* fix(ci): update scorecard-action to v2.3.1 [[#3153](https://github.com/falcosecurity/falco/pull/3153)] - [@LucaGuerra](https://github.com/LucaGuerra)
* cleanup(falco): consolidate falco::grpc::server in one class [[#3150](https://github.com/falcosecurity/falco/pull/3150)] - [@LucaGuerra](https://github.com/LucaGuerra)
* new(build): enable ASan and UBSan builds with options and in CI [[#3147](https://github.com/falcosecurity/falco/pull/3147)] - [@LucaGuerra](https://github.com/LucaGuerra)
* fix(userspace): variable / function shadowing [[#3123](https://github.com/falcosecurity/falco/pull/3123)] - [@sgaist](https://github.com/sgaist)
* build(deps): Bump submodules/falcosecurity-rules from `fbf0a4e` to `88a40c8` [[#3145](https://github.com/falcosecurity/falco/pull/3145)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* fix(cmake): fix USE_BUNDLED_DEPS=ON and BUILD_FALCO_UNIT_TESTS=ON [[#3146](https://github.com/falcosecurity/falco/pull/3146)] - [@LucaGuerra](https://github.com/LucaGuerra)
* Add --kernelversion and --kernelrelease options to falco driver loader entrypoint [[#3143](https://github.com/falcosecurity/falco/pull/3143)] - [@Sryther](https://github.com/Sryther)
* build(deps): Bump submodules/falcosecurity-rules from `44addef` to `fbf0a4e` [[#3139](https://github.com/falcosecurity/falco/pull/3139)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore: bump to latest libs commit [[#3137](https://github.com/falcosecurity/falco/pull/3137)] - [@Andreagit97](https://github.com/Andreagit97)
* refactor: Use FetchContent for integrating three bundled libs [[#3107](https://github.com/falcosecurity/falco/pull/3107)] - [@federico-sysdig](https://github.com/federico-sysdig)
* build(deps): Bump submodules/falcosecurity-rules from `dc7970d` to `44addef` [[#3136](https://github.com/falcosecurity/falco/pull/3136)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* build(deps): Bump submodules/falcosecurity-rules from `f88b991` to `dc7970d` [[#3126](https://github.com/falcosecurity/falco/pull/3126)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* refactor(ci): Avoid using command make directly [[#3101](https://github.com/falcosecurity/falco/pull/3101)] - [@federico-sysdig](https://github.com/federico-sysdig)
* docs(proposal): 20231220-features-adoption-and-deprecation.md [[#2986](https://github.com/falcosecurity/falco/pull/2986)] - [@leogr](https://github.com/leogr)
* build(deps): Bump submodules/falcosecurity-rules from `b499a1d` to `f88b991` [[#3125](https://github.com/falcosecurity/falco/pull/3125)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* docs(README.md): Falco Graduates within the CNCF [[#3124](https://github.com/falcosecurity/falco/pull/3124)] - [@leogr](https://github.com/leogr)
* build(deps): Bump submodules/falcosecurity-rules from `497e011` to `b499a1d` [[#3111](https://github.com/falcosecurity/falco/pull/3111)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* chore(ci): bumped codeql actions. [[#3114](https://github.com/falcosecurity/falco/pull/3114)] - [@FedeDP](https://github.com/FedeDP)
* Cleanup warnings and smart ptrs [[#3112](https://github.com/falcosecurity/falco/pull/3112)] - [@federico-sysdig](https://github.com/federico-sysdig)
* new(build): add options to use bundled dependencies [[#3092](https://github.com/falcosecurity/falco/pull/3092)] - [@mrgian](https://github.com/mrgian)
* fix(ci): test-dev-packages-arm64 needs build-dev-packages-arm64. [[#3110](https://github.com/falcosecurity/falco/pull/3110)] - [@FedeDP](https://github.com/FedeDP)
* refactor: bump libs and driver, and adopt unique pointers wherever possible [[#3109](https://github.com/falcosecurity/falco/pull/3109)] - [@jasondellaluce](https://github.com/jasondellaluce)
* cleanup: falco_engine test fixture [[#3099](https://github.com/falcosecurity/falco/pull/3099)] - [@federico-sysdig](https://github.com/federico-sysdig)
* refactor: test AtomicSignalHandler.handle_once_wait_consistency [[#3100](https://github.com/falcosecurity/falco/pull/3100)] - [@federico-sysdig](https://github.com/federico-sysdig)
* Cleanup variable use [[#3097](https://github.com/falcosecurity/falco/pull/3097)] - [@sgaist](https://github.com/sgaist)
* cleanup(submodules): dropped testing submodule. [[#3098](https://github.com/falcosecurity/falco/pull/3098)] - [@FedeDP](https://github.com/FedeDP)
* cleanup(ci): make use of falcosecurity/testing provided composite action [[#3093](https://github.com/falcosecurity/falco/pull/3093)] - [@FedeDP](https://github.com/FedeDP)
* Improve const correctness [[#3083](https://github.com/falcosecurity/falco/pull/3083)] - [@sgaist](https://github.com/sgaist)
* Improve exception throwing [[#3085](https://github.com/falcosecurity/falco/pull/3085)] - [@sgaist](https://github.com/sgaist)
* fix(ci): update sync in deb and rpm scripts with acl [[#3062](https://github.com/falcosecurity/falco/pull/3062)] - [@LucaGuerra](https://github.com/LucaGuerra)
* cleanup(tests): consolidate Falco engine and rule loader tests [[#3066](https://github.com/falcosecurity/falco/pull/3066)] - [@LucaGuerra](https://github.com/LucaGuerra)
* cleanup: falco_engine deps and include paths [[#3090](https://github.com/falcosecurity/falco/pull/3090)] - [@federico-sysdig](https://github.com/federico-sysdig)
* fix: Some compiler warnings [[#3089](https://github.com/falcosecurity/falco/pull/3089)] - [@federico-sysdig](https://github.com/federico-sysdig)
* build(deps): Bump submodules/falcosecurity-rules from `0f60976` to `497e011` [[#3081](https://github.com/falcosecurity/falco/pull/3081)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* fix(c++): add missing explicit to single argument constructors [[#3069](https://github.com/falcosecurity/falco/pull/3069)] - [@sgaist](https://github.com/sgaist)
* Improve class initialization [[#3074](https://github.com/falcosecurity/falco/pull/3074)] - [@sgaist](https://github.com/sgaist)
* build(deps): Bump submodules/falcosecurity-rules from `6ed2036` to `0f60976` [[#3078](https://github.com/falcosecurity/falco/pull/3078)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* build(deps): Bump submodules/falcosecurity-rules from `1053b2d` to `6ed2036` [[#3067](https://github.com/falcosecurity/falco/pull/3067)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* fix(c++): add missing overrides [[#3064](https://github.com/falcosecurity/falco/pull/3064)] - [@sgaist](https://github.com/sgaist)
* new(build): prune deb-dev and rpm-dev directories [[#3056](https://github.com/falcosecurity/falco/pull/3056)] - [@LucaGuerra](https://github.com/LucaGuerra)
* refactor(userspace): align falco to gen-event class family deprecation [[#3051](https://github.com/falcosecurity/falco/pull/3051)] - [@jasondellaluce](https://github.com/jasondellaluce)
* build(deps): Bump submodules/falcosecurity-rules from `3cac61c` to `1053b2d` [[#3047](https://github.com/falcosecurity/falco/pull/3047)] - [@dependabot[bot]](https://github.com/apps/dependabot)
* fix: adopt new libsinsp logger [[#3026](https://github.com/falcosecurity/falco/pull/3026)] - [@therealbobo](https://github.com/therealbobo)
* refactor: cleanup libs relative include paths [[#2936](https://github.com/falcosecurity/falco/pull/2936)] - [@therealbobo](https://github.com/therealbobo)
* chore(ci): bumped rn2md to latest master. [[#3046](https://github.com/falcosecurity/falco/pull/3046)] - [@FedeDP](https://github.com/FedeDP)
* Support alternate rules loader [[#3008](https://github.com/falcosecurity/falco/pull/3008)] - [@mstemm](https://github.com/mstemm)
* fix(ci): fixed release body driver version. [[#3042](https://github.com/falcosecurity/falco/pull/3042)] - [@FedeDP](https://github.com/FedeDP)
* build(deps): Bump submodules/falcosecurity-rules from `c39d31a` to `3f668d0` [[#3039](https://github.com/falcosecurity/falco/pull/3039)] - [@dependabot[bot]](https://github.com/apps/dependabot)
## v0.37.1
Released on 2024-02-13

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
cmake_minimum_required(VERSION 3.5.1)
@@ -18,7 +19,11 @@ project(falco)
option(USE_BUNDLED_DEPS "Bundle hard to find dependencies into the Falco binary" ON)
option(USE_DYNAMIC_LIBELF "Dynamically link libelf" ON)
option(BUILD_WARNINGS_AS_ERRORS "Enable building with -Wextra -Werror flags" OFF)
option(MINIMAL_BUILD "Build a minimal version of Falco, containing only the engine and basic input/output (EXPERIMENTAL)" OFF)
option(
MINIMAL_BUILD
"Build a minimal version of Falco, containing only the engine and basic input/output (EXPERIMENTAL)"
OFF
)
option(MUSL_OPTIMIZED_BUILD "Enable if you want a musl optimized build" OFF)
option(BUILD_FALCO_UNIT_TESTS "Build falco unit tests" OFF)
option(USE_ASAN "Build with AddressSanitizer" OFF)
@@ -26,54 +31,70 @@ option(USE_UBSAN "Build with UndefinedBehaviorSanitizer" OFF)
option(UBSAN_HALT_ON_ERROR "Halt on error when building with UBSan" ON)
if(WIN32)
if(POLICY CMP0091)
# Needed for CMAKE_MSVC_RUNTIME_LIBRARY
# https://cmake.org/cmake/help/latest/policy/CMP0091.html
cmake_policy(SET CMP0091 NEW)
endif()
if(POLICY CMP0091)
# Needed for CMAKE_MSVC_RUNTIME_LIBRARY
# https://cmake.org/cmake/help/latest/policy/CMP0091.html
cmake_policy(SET CMP0091 NEW)
endif()
set(CPACK_GENERATOR "NSIS") # this needs NSIS installed, and available
elseif (APPLE)
elseif(APPLE)
set(CPACK_GENERATOR "DragNDrop")
elseif(EMSCRIPTEN)
set(USE_BUNDLED_DEPS ON CACHE BOOL "" FORCE)
set(BUILD_DRIVER OFF CACHE BOOL "" FORCE)
set(ENABLE_DKMS OFF CACHE BOOL "" FORCE)
set(BUILD_BPF OFF CACHE BOOL "" FORCE)
set(CPACK_GENERATOR TGZ CACHE BOOL "" FORCE)
set(USE_BUNDLED_DEPS
ON
CACHE BOOL "" FORCE
)
set(BUILD_DRIVER
OFF
CACHE BOOL "" FORCE
)
set(ENABLE_DKMS
OFF
CACHE BOOL "" FORCE
)
set(BUILD_BPF
OFF
CACHE BOOL "" FORCE
)
set(CPACK_GENERATOR
TGZ
CACHE BOOL "" FORCE
)
endif()
# gVisor is currently only supported on Linux x86_64
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" AND CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT MINIMAL_BUILD)
option(BUILD_FALCO_GVISOR "Build gVisor support for Falco" ON)
if (BUILD_FALCO_GVISOR)
add_definitions(-DHAS_GVISOR)
endif()
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64"
AND CMAKE_SYSTEM_NAME MATCHES "Linux"
AND NOT MINIMAL_BUILD
)
option(BUILD_FALCO_GVISOR "Build gVisor support for Falco" ON)
if(BUILD_FALCO_GVISOR)
add_definitions(-DHAS_GVISOR)
endif()
endif()
# Modern BPF is not supported on not Linux systems and in MINIMAL_BUILD
if(CMAKE_SYSTEM_NAME MATCHES "Linux" AND NOT MINIMAL_BUILD)
option(BUILD_FALCO_MODERN_BPF "Build modern BPF support for Falco" ON)
if(BUILD_FALCO_MODERN_BPF)
add_definitions(-DHAS_MODERN_BPF)
endif()
option(BUILD_FALCO_MODERN_BPF "Build modern BPF support for Falco" ON)
if(BUILD_FALCO_MODERN_BPF)
add_definitions(-DHAS_MODERN_BPF)
endif()
endif()
# We shouldn't need to set this, see https://gitlab.kitware.com/cmake/cmake/-/issues/16419
option(EP_UPDATE_DISCONNECTED "ExternalProject update disconnected" OFF)
if (${EP_UPDATE_DISCONNECTED})
set_property(
DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
PROPERTY EP_UPDATE_DISCONNECTED TRUE)
if(${EP_UPDATE_DISCONNECTED})
set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY EP_UPDATE_DISCONNECTED TRUE)
endif()
# Elapsed time
# set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CMAKE_COMMAND} -E time") # TODO(fntlnz, leodido): add a flag to enable this
# Elapsed time set_property(GLOBAL PROPERTY RULE_LAUNCH_COMPILE "${CMAKE_COMMAND} -E time") #
# TODO(fntlnz, leodido): add a flag to enable this
# Make flag for parallel processing
include(ProcessorCount)
processorcount(PROCESSOR_COUNT)
ProcessorCount(PROCESSOR_COUNT)
if(NOT PROCESSOR_COUNT EQUAL 0)
set(PROCESSOUR_COUNT_MAKE_FLAG -j${PROCESSOR_COUNT})
set(PROCESSOUR_COUNT_MAKE_FLAG -j${PROCESSOR_COUNT})
endif()
# Custom CMake modules
@@ -83,14 +104,14 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules")
include(GNUInstallDirs)
if(NOT DEFINED FALCO_ETC_DIR)
set(FALCO_ETC_DIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/falco")
set(FALCO_ETC_DIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/falco")
endif()
# This will be used to print the architecture for which Falco is compiled.
if (EMSCRIPTEN)
set(FALCO_TARGET_ARCH "wasm")
if(EMSCRIPTEN)
set(FALCO_TARGET_ARCH "wasm")
else()
set(FALCO_TARGET_ARCH ${CMAKE_SYSTEM_PROCESSOR})
set(FALCO_TARGET_ARCH ${CMAKE_SYSTEM_PROCESSOR})
endif()
include(CompilerFlags)
@@ -100,19 +121,20 @@ set(DRIVER_NAME "falco")
set(DRIVER_DEVICE_NAME "falco")
set(DRIVERS_REPO "https://download.falco.org/driver")
# If no path is provided, try to search the BPF probe in: `home/.falco/falco-bpf.o`
# This is the same fallback that we had in the libraries: `SCAP_PROBE_BPF_FILEPATH`.
# If no path is provided, try to search the BPF probe in: `home/.falco/falco-bpf.o` This is the same
# fallback that we had in the libraries: `SCAP_PROBE_BPF_FILEPATH`.
set(FALCO_PROBE_BPF_FILEPATH ".${DRIVER_NAME}/${DRIVER_NAME}-bpf.o")
add_definitions(-DFALCO_PROBE_BPF_FILEPATH="${FALCO_PROBE_BPF_FILEPATH}")
if(NOT DEFINED FALCO_COMPONENT_NAME)
set(FALCO_COMPONENT_NAME "${CMAKE_PROJECT_NAME}")
set(FALCO_COMPONENT_NAME "${CMAKE_PROJECT_NAME}")
endif()
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX
/usr
CACHE PATH "Default install path" FORCE)
set(CMAKE_INSTALL_PREFIX
/usr
CACHE PATH "Default install path" FORCE
)
endif()
set(CMD_MAKE make)
@@ -131,60 +153,93 @@ include(njson)
# yaml-cpp
include(yaml-cpp)
if(NOT WIN32 AND NOT APPLE AND NOT MINIMAL_BUILD AND NOT EMSCRIPTEN)
# OpenSSL
include(openssl)
if(NOT WIN32
AND NOT APPLE
AND NOT MINIMAL_BUILD
AND NOT EMSCRIPTEN
)
# OpenSSL
include(openssl)
# libcurl
include(curl)
# libcurl
include(curl)
# todo(jasondellaluce,rohith-raju): support webserver for non-linux builds too
# cpp-httlib
include(cpp-httplib)
# todo(jasondellaluce,rohith-raju): support webserver for non-linux builds too cpp-httlib
include(cpp-httplib)
endif()
include(cxxopts)
# One TBB
if (NOT EMSCRIPTEN)
include(tbb)
if(NOT EMSCRIPTEN)
include(tbb)
endif()
include(zlib)
if (NOT MINIMAL_BUILD)
if (NOT WIN32 AND NOT APPLE AND NOT EMSCRIPTEN)
include(cares)
include(protobuf)
# gRPC
include(grpc)
endif()
include(valijson)
if(NOT MINIMAL_BUILD)
if(NOT WIN32
AND NOT APPLE
AND NOT EMSCRIPTEN
)
include(cares)
include(protobuf)
# gRPC
include(grpc)
endif()
endif()
# Installation
if(WIN32)
set(FALCO_INSTALL_CONF_FILE "%PROGRAMFILES%/${PACKAGE_NAME}-${FALCO_VERSION}/etc/falco/falco.yaml")
install(FILES falco.yaml DESTINATION etc/falco/ COMPONENT "${FALCO_COMPONENT_NAME}")
install(DIRECTORY DESTINATION etc/falco/config.d COMPONENT "${FALCO_COMPONENT_NAME}")
set(FALCO_INSTALL_CONF_FILE
"%PROGRAMFILES%/${PACKAGE_NAME}-${FALCO_VERSION}/etc/falco/falco.yaml"
)
install(
FILES falco.yaml
DESTINATION etc/falco/
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(
DIRECTORY
DESTINATION etc/falco/config.d
COMPONENT "${FALCO_COMPONENT_NAME}"
)
elseif(APPLE)
set(FALCO_INSTALL_CONF_FILE "/etc/falco/falco.yaml")
install(FILES falco.yaml DESTINATION etc/falco/ COMPONENT "${FALCO_COMPONENT_NAME}")
install(DIRECTORY DESTINATION etc/falco/config.d COMPONENT "${FALCO_COMPONENT_NAME}")
install(
FILES falco.yaml
DESTINATION etc/falco/
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(
DIRECTORY
DESTINATION etc/falco/config.d
COMPONENT "${FALCO_COMPONENT_NAME}"
)
else()
set(FALCO_INSTALL_CONF_FILE "/etc/falco/falco.yaml")
install(FILES falco.yaml DESTINATION "${FALCO_ETC_DIR}" COMPONENT "${FALCO_COMPONENT_NAME}")
install(DIRECTORY DESTINATION "${FALCO_ETC_DIR}/config.d" COMPONENT "${FALCO_COMPONENT_NAME}")
install(
FILES falco.yaml
DESTINATION "${FALCO_ETC_DIR}"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(
DIRECTORY
DESTINATION "${FALCO_ETC_DIR}/config.d"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
endif()
if(NOT MINIMAL_BUILD)
# Coverage
include(Coverage)
# Coverage
include(Coverage)
endif()
# Rules
include(rules)
# Clang format
# add_custom_target(format COMMAND clang-format --style=file -i $<TARGET_PROPERTY:falco,SOURCES> COMMENT "Formatting ..." VERBATIM)
# Clang format add_custom_target(format COMMAND clang-format --style=file -i
# $<TARGET_PROPERTY:falco,SOURCES> COMMENT "Formatting ..." VERBATIM)
# Static analysis
include(static-analysis)
@@ -198,13 +253,17 @@ add_subdirectory(scripts)
add_subdirectory(userspace/engine)
add_subdirectory(userspace/falco)
if(NOT WIN32 AND NOT APPLE AND NOT EMSCRIPTEN AND NOT MUSL_OPTIMIZED_BUILD)
include(falcoctl)
if(NOT WIN32
AND NOT APPLE
AND NOT EMSCRIPTEN
AND NOT MUSL_OPTIMIZED_BUILD
)
include(falcoctl)
endif()
# Packages configuration
include(CPackConfig)
if(BUILD_FALCO_UNIT_TESTS)
add_subdirectory(unit_tests)
add_subdirectory(unit_tests)
endif()

207
Contributing.md Normal file
View File

@@ -0,0 +1,207 @@
# How to contribute
## Enforce coding style 💻
### Introduction
This document introduces the coding style that will be applied in this repository.
This coding style involves all the following files: `.c`, `.h`, `.cpp`, `.cmake`, `CMakeLists.txt`. To enforce it we rely on two main tools:
1. `clang-format` version `18.1.8`.
2. `cmake-format` version `0.6.13`.
> __Please note__: tools versions are important! Different versions will enforce slightly different changes on the code. For example `clang-format-18` will produce a slightly different output respect to `clang-format-17` always respecting the imposed style.
The coding style is expressed through the 2 configuration file that you find in this repo: `.clang-format`, `.cmake-format.json`.
### Enforce the style locally
There are many ways to enforce the style locally, here we will describe two of them:
1. Use `pre-commit` framework.
2. Use the repo `Makefile`.
#### 1.Pre-commit framework (suggested if you don't have the 2 tools already installed on your machine)
The `pre-commit` framework allows you to automatically install different `git-hooks` that will run at every new commit. More precisely, if you use the `.pre-commit-config.yaml` in this repo you will install 3 different hooks:
1. The `clang-format` hook: this is a `pre-commit` git hook that runs `clang-format` on your staged changes.
2. The `cmake-format` hook: this is a `pre-commit` git hook that runs `cmake-format` on your staged changes.
3. The `DCO signed-off` hook: this is a `pre-commit-msg` git hook that adds the `DCO` on your commit if not present. This hook is not strictly related to the coding style so we will talk about it in a separate section: [Add DCO signed-off to your commits](#add-dco-signed-off-to-your-commits).
Now let's see what we need to use `pre-commit` framework.
##### Step 1
Install `pre-commit` framework following the [official documentation](https://pre-commit.com/#installation).
> __Please note__: you have to follow only the "Installation" section.
##### Step 2
Once you have installed `pre-commit`, you don't need to install anything else! This is the good point of using a framework like `pre-commit`, all the tools necessary to format your code will be directly managed by the framework. But in order to be ready, you need to install the git hooks in your local repo.
This simple command allows you to install the two `pre-commit` git hooks, `clang-format` and `cmake-format`.
```bash
pre-commit install --install-hooks --hook-type pre-commit --overwrite
```
If you want to install also the `pre-commit-msg` git hook for the DCO you have to type the following command, but be sure to have configured all you need as said in the [dedicated section]((#add-dco-signed-off-to-your-commits))
```bash
pre-commit install --install-hooks --hook-type prepare-commit-msg --overwrite
```
You have done, at every new commit, this hook will check that your patch respects the coding style of this repo!
If you want to detach the git hooks, you can simply type:
```bash
pre-commit uninstall --hook-type prepare-commit-msg
pre-commit uninstall --hook-type pre-commit
```
#### 2.Makefile
##### Step 1
In order to use the repo `Makefile`, you need to install on your local machine the two aforementioned tools:
__clang-format v18.1.8__
One of the easiest ways to install `clang-format` could be directly downloading its static binary from [here](https://github.com/muttleyxd/clang-tools-static-binaries).
There are other ways for example you can download the package for your distro or you can also build it from sources.
__cmake-format v0.6.13__
To install `cmake-format` you can follow the official documentation [here](https://cmake-format.readthedocs.io/en/latest/installation.html).
> __NOTE__: Please check the versions of the two tool with `clang-format --version` and `cmake-format --version`.
##### Step 2
Once you have installed the __right__ versions of the 2 tools, you can simply type `make format-all` from the root directory of the project (`/libs`) to format all your code according to the coding style.
Remember to do that before submitting a new patch upstream! 😁
#### Other solutions
Obviously, you can also install the 2 tools locally and enable some extension of your favorite IDE (like `VScode`) to format your code every time you save your files!
## Add DCO signed-off to your commits 🔏
### Introduction
Another requirement for contributing to the `libs` repository, is applying the [DCO](https://cert-manager.io/docs/contributing/sign-off/) to every commit you want to push upstream.
Before doing this you have to configure your git user `name` and `email` if you haven't already done it. To check your actual `name` and `email` type:
```bash
git config --get user.name
git config --get user.email
```
If they are correct you have done, otherwise, you have to set them:
```bash
git config user.name <full-name>
git config user.email <mail-used_with-GitHub-profile>
```
>__Please note__: If you have problems in doing this you can read the full documentation [here](https://docs.github.com/en/get-started/getting-started-with-git/setting-your-username-in-git).
### Enforce the DCO locally
Now you are ready to sign your commits! You have two main ways to do this:
1. Manually with `git` tool.
2. Use the `pre-commit-msg` hook quoted before.
### Manually
To do this you just need to remember the `-s` while performing your commits:
```bash
git commit -s
```
or with the inline message:
```bash
git commit -s -m "my first commit"
```
### Use `pre-commit` hook
Here if you have already added the hook in the [previous section](#step-2), you have to do nothing otherwise you have to simply install the DCO hook with:
```bash
pre-commit install --install-hooks --hook-type prepare-commit-msg --overwrite
```
And you have done! Now you don't have to remember the `-s` option every time you commit something, the DCO hook will automatically add the DCO if you forget it! 😄
## Some best practices 📏
### Class variables
To know whether a variable belongs to a `class` or a `function`, we start member variables with `m_`.
Example:
```c
public int32_t m_counter;
```
### Global variables
To know whether the variable is global or not, we start globals with `g_`.
Example:
```c
int g_nplugins;
```
### Capitalization
The naming convention is camel-cased "Unix" style, i.e. always lower case. Words are separated by underscores.
Example:
```c
int32_t g_global_bean_counter;
int32_t count_beans();
```
and not,
```c
int32_t GlobalBeanCounter;
int32_t CountBeans();
```
### Packed Structures
Packed structures should use the GCC and MSVC-style supported `pragma`:
Example:
```c
#pragma pack(push,1)
struct frame_control
{
struct fields....
};
#pragma pack(pop)
```
### 64-bit constants
Put an `LL` at the end of your `64-bit` constants. Without the `LL`, some platform compilers try to interpret the constant on the right-hand side as a `long integer` instead of a `long long` and this could lead to an error at building time.
Example:
```c
x=0X00FF00000000000LL
```

81
Makefile Normal file
View File

@@ -0,0 +1,81 @@
#
# Copyright (C) 2024 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# mofidy the following variables to match your paths
CLANG_FORMAT_EXE ?= clang-format
CLANG_FORMAT_VERSION = "$(shell ${CLANG_FORMAT_EXE} --version | grep -o '[0-9]*\.[0-9]*\.[0-9]*')"
CLANG_FORMAT_DESIRED_VERSION ="18.1.8"
CMAKE_FORMAT_EXE ?= cmake-format
CMAKE_FORMAT_VERSION = "$(shell ${CMAKE_FORMAT_EXE} --version | grep -o '[0-9]*\.[0-9]*\.[0-9]*')"
CMAKE_FORMAT_DESIRED_VERSION = "0.6.13"
PROJECT_ROOT_DIR = $(shell git rev-parse --show-toplevel)
######################
# Clang-format #
######################
.PHONY: clang-format-install
clang-format-install:
ifeq (, $(shell ${CLANG_FORMAT_EXE} --version))
@echo "${CLANG_FORMAT_EXE} is not installed. Please read the 'coding style' doc to get more info."
@exit 1
endif
ifneq ($(CLANG_FORMAT_VERSION), $(CLANG_FORMAT_DESIRED_VERSION))
@echo "${CLANG_FORMAT_EXE} version is not '${CLANG_FORMAT_DESIRED_VERSION}'. Actual version is '${CLANG_FORMAT_VERSION}'"
@exit 1
endif
.PHONY: format-clang
format-clang: clang-format-install
git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cpp|h|c)$$' | xargs ${CLANG_FORMAT_EXE} -Werror --style=file:${PROJECT_ROOT_DIR}/.clang-format -i
.PHONY: check-clang
check-clang: clang-format-install
git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cpp|h|c)$$' | xargs ${CLANG_FORMAT_EXE} -Werror --style=file:${PROJECT_ROOT_DIR}/.clang-format -n
######################
# Cmake-format #
######################
.PHONY: cmake-format-install
cmake-format-install:
ifeq (, $(shell ${CMAKE_FORMAT_EXE} --version))
@echo "${CMAKE_FORMAT_EXE} is not installed. Please read the 'coding style' doc to get more info."
@exit 1
endif
ifneq ($(CMAKE_FORMAT_VERSION), $(CMAKE_FORMAT_DESIRED_VERSION))
@echo "${CMAKE_FORMAT_EXE} version is not '${CMAKE_FORMAT_DESIRED_VERSION}'. Actual version is '${CMAKE_FORMAT_VERSION}'"
@exit 1
endif
.PHONY: format-cmake
format-cmake: cmake-format-install
git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cmake)$$|CMakeLists.txt$$' | xargs ${CMAKE_FORMAT_EXE} --config-files ${PROJECT_ROOT_DIR}/.cmake-format.json -i
.PHONY: check-cmake
check-cmake: cmake-format-install
git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cmake)$$|CMakeLists.txt$$' | xargs ${CMAKE_FORMAT_EXE} --config-files ${PROJECT_ROOT_DIR}/.cmake-format.json --check
# Add new formatters here...
.PHONY: format-all
format-all: format-clang format-cmake
.PHONY: check-all
check-all: check-clang check-cmake

1
OWNERS
View File

@@ -6,6 +6,7 @@ approvers:
- andreagit97
- incertum
- LucaGuerra
- sgaist
reviewers:
- kaizhe
emeritus_approvers:

View File

@@ -2,7 +2,7 @@
[![Latest release](https://img.shields.io/github/v/release/falcosecurity/falco?style=for-the-badge)](https://github.com/falcosecurity/falco/releases/latest) [![Supported Architectures](https://img.shields.io/badge/ARCHS-x86__64%7Caarch64-blueviolet?style=for-the-badge)](https://github.com/falcosecurity/falco/releases/latest) [![License](https://img.shields.io/github/license/falcosecurity/falco?style=for-the-badge)](COPYING) [![Docs](https://img.shields.io/badge/docs-latest-green.svg?style=for-the-badge)](https://falco.org/docs)
[![Falco Core Repository](https://github.com/falcosecurity/evolution/blob/main/repos/badges/falco-core-blue.svg)](https://github.com/falcosecurity/evolution/blob/main/REPOSITORIES.md#core-scope) [![Stable](https://img.shields.io/badge/status-stable-brightgreen?style=for-the-badge)](https://github.com/falcosecurity/evolution/blob/main/REPOSITORIES.md#stable) [![OpenSSF Best Practices](https://img.shields.io/cii/summary/2317?label=OpenSSF%20Best%20Practices&style=for-the-badge)](https://bestpractices.coreinfrastructure.org/projects/2317) <a href="https://actuated.dev/"><img alt="Arm CI sponsored by Actuated" src="https://docs.actuated.dev/images/actuated-badge.png" width="120px"></img></a>
[![Falco Core Repository](https://github.com/falcosecurity/evolution/blob/main/repos/badges/falco-core-blue.svg)](https://github.com/falcosecurity/evolution/blob/main/REPOSITORIES.md#core-scope) [![Stable](https://img.shields.io/badge/status-stable-brightgreen?style=for-the-badge)](https://github.com/falcosecurity/evolution/blob/main/REPOSITORIES.md#stable) [![OpenSSF Scorecard](https://img.shields.io/ossf-scorecard/github.com/falcosecurity/falco?label=openssf%20scorecard&style=for-the-badge)](https://scorecard.dev/viewer/?uri=github.com/falcosecurity/falco) [![OpenSSF Best Practices](https://img.shields.io/cii/summary/2317?label=OpenSSF%20Best%20Practices&style=for-the-badge)](https://bestpractices.coreinfrastructure.org/projects/2317) <a href="https://actuated.dev/"><img alt="Arm CI sponsored by Actuated" src="https://docs.actuated.dev/images/actuated-badge.png" width="120px"></img></a>
[![Falco](https://falco.org/img/brand/falco-horizontal-color.svg)](https://falco.org)
@@ -43,6 +43,9 @@ Considerations and guidance for Falco adopters:
5. Integrate with output destinations: Integrate Falco with SIEM, data lake systems, or other preferred output destinations to establish a robust foundation for comprehensive data analysis and enable effective incident response workflows.
### Demo Environment
A demo environment is provided via a docker-compose file that can be started on a docker host which includes falco, falcosidekick, falcosidekick-ui and its required redis database. For more information see the [docker-compose section](docker/docker-compose/)
## How to Contribute

View File

@@ -2,24 +2,53 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
if(CPACK_GENERATOR MATCHES "DEB" OR CPACK_GENERATOR MATCHES "RPM")
list(APPEND CPACK_INSTALL_COMMANDS "mkdir -p _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falco-kmod-inject.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falco-kmod.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falco-bpf.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falco-modern-bpf.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falco-custom.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(APPEND CPACK_INSTALL_COMMANDS "cp scripts/systemd/falcoctl-artifact-follow.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system")
list(
APPEND
CPACK_INSTALL_COMMANDS
"mkdir -p _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falco-kmod-inject.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falco-kmod.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falco-bpf.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falco-modern-bpf.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falco-custom.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
list(
APPEND
CPACK_INSTALL_COMMANDS
"cp scripts/systemd/falcoctl-artifact-follow.service _CPack_Packages/${CPACK_TOPLEVEL_TAG}/${CPACK_GENERATOR}/${CPACK_PACKAGE_FILE_NAME}/usr/lib/systemd/system"
)
endif()
if(CPACK_GENERATOR MATCHES "TGZ")

View File

@@ -2,19 +2,21 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
set(CPACK_PACKAGE_NAME "${PACKAGE_NAME}")
set(CPACK_PACKAGE_VENDOR "Cloud Native Computing Foundation (CNCF) cncf.io.")
set(CPACK_PACKAGE_CONTACT "cncf-falco-dev@lists.cncf.io") # todo: change this once we've got @falco.org addresses
set(CPACK_PACKAGE_CONTACT "cncf-falco-dev@lists.cncf.io") # todo: change this once we've got
# @falco.org addresses
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "Falco - Container Native Runtime Security")
set(CPACK_PACKAGE_DESCRIPTION_FILE "${PROJECT_SOURCE_DIR}/scripts/description.txt")
set(CPACK_PACKAGE_VERSION "${FALCO_VERSION}")
@@ -24,32 +26,35 @@ set(CPACK_PACKAGE_VERSION_PATCH "${FALCO_VERSION_PATCH}")
set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_SOURCE_DIR}/cmake/cpack/CMakeCPackOptions.cmake")
set(CPACK_STRIP_FILES "ON")
set(CPACK_PACKAGE_RELOCATABLE "OFF")
if (EMSCRIPTEN)
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-wasm")
if(EMSCRIPTEN)
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-wasm")
else()
set(CPACK_PACKAGE_FILE_NAME "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CMAKE_SYSTEM_PROCESSOR}")
set(CPACK_PACKAGE_FILE_NAME
"${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}-${CMAKE_SYSTEM_PROCESSOR}"
)
endif()
if(WIN32)
SET(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME}-${CPACK_PACKAGE_VERSION}")
endif()
# Built packages will include only the following components
set(CPACK_INSTALL_CMAKE_PROJECTS
"${CMAKE_CURRENT_BINARY_DIR};${FALCO_COMPONENT_NAME};${FALCO_COMPONENT_NAME};/"
"${CMAKE_CURRENT_BINARY_DIR};${FALCO_COMPONENT_NAME};${FALCO_COMPONENT_NAME};/"
)
if(CMAKE_SYSTEM_NAME MATCHES "Linux") # only Linux has drivers
list(APPEND CPACK_INSTALL_CMAKE_PROJECTS
"${CMAKE_CURRENT_BINARY_DIR};${DRIVER_COMPONENT_NAME};${DRIVER_COMPONENT_NAME};/")
list(APPEND CPACK_INSTALL_CMAKE_PROJECTS
"${CMAKE_CURRENT_BINARY_DIR};${DRIVER_COMPONENT_NAME};${DRIVER_COMPONENT_NAME};/"
)
endif()
if(NOT CPACK_GENERATOR)
if (CMAKE_SYSTEM_NAME MATCHES "Linux")
set(CPACK_GENERATOR DEB RPM TGZ)
else()
set(CPACK_GENERATOR TGZ)
endif()
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
set(CPACK_GENERATOR DEB RPM TGZ)
else()
set(CPACK_GENERATOR TGZ)
endif()
endif()
message(STATUS "Using package generators: ${CPACK_GENERATOR}")
@@ -57,15 +62,15 @@ message(STATUS "Package architecture: ${CMAKE_SYSTEM_PROCESSOR}")
set(CPACK_DEBIAN_PACKAGE_SECTION "utils")
if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64")
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64")
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64")
endif()
if(${CMAKE_SYSTEM_PROCESSOR} STREQUAL "aarch64")
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "arm64")
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "arm64")
endif()
set(CPACK_DEBIAN_PACKAGE_HOMEPAGE "https://www.falco.org")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "dkms (>= 2.1.0.0)")
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA
"${CMAKE_BINARY_DIR}/scripts/debian/postinst;${CMAKE_BINARY_DIR}/scripts/debian/prerm;${CMAKE_BINARY_DIR}/scripts/debian/postrm;${PROJECT_SOURCE_DIR}/cmake/cpack/debian/conffiles"
"${CMAKE_BINARY_DIR}/scripts/debian/postinst;${CMAKE_BINARY_DIR}/scripts/debian/prerm;${CMAKE_BINARY_DIR}/scripts/debian/postrm;${PROJECT_SOURCE_DIR}/cmake/cpack/debian/conffiles"
)
set(CPACK_RPM_PACKAGE_LICENSE "Apache v2.0")
@@ -77,13 +82,14 @@ set(CPACK_RPM_PRE_UNINSTALL_SCRIPT_FILE "${CMAKE_BINARY_DIR}/scripts/rpm/preunin
set(CPACK_RPM_POST_UNINSTALL_SCRIPT_FILE "${CMAKE_BINARY_DIR}/scripts/rpm/postuninstall")
set(CPACK_RPM_PACKAGE_VERSION "${FALCO_VERSION}")
set(CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION
/usr/src
/usr/share/man
/usr/share/man/man8
/etc
/usr
/usr/bin
/usr/share)
/usr/src
/usr/share/man
/usr/share/man/man8
/etc
/usr
/usr/bin
/usr/share
)
set(CPACK_RPM_PACKAGE_RELOCATABLE "OFF")
include(CPack)

View File

@@ -2,51 +2,51 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_EXTENSIONS OFF)
if(NOT FALCO_EXTRA_DEBUG_FLAGS)
set(FALCO_EXTRA_DEBUG_FLAGS "-D_DEBUG")
set(FALCO_EXTRA_DEBUG_FLAGS "-D_DEBUG")
endif()
string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE)
if(CMAKE_BUILD_TYPE STREQUAL "debug")
set(KBUILD_FLAGS "${FALCO_EXTRA_DEBUG_FLAGS} ${FALCO_EXTRA_FEATURE_FLAGS}")
set(KBUILD_FLAGS "${FALCO_EXTRA_DEBUG_FLAGS} ${FALCO_EXTRA_FEATURE_FLAGS}")
else()
set(CMAKE_BUILD_TYPE "release")
set(KBUILD_FLAGS "${FALCO_EXTRA_FEATURE_FLAGS}")
add_definitions(-DBUILD_TYPE_RELEASE)
set(CMAKE_BUILD_TYPE "release")
set(KBUILD_FLAGS "${FALCO_EXTRA_FEATURE_FLAGS}")
add_definitions(-DBUILD_TYPE_RELEASE)
endif()
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
if(MINIMAL_BUILD)
set(MINIMAL_BUILD_FLAGS "-DMINIMAL_BUILD")
set(MINIMAL_BUILD_FLAGS "-DMINIMAL_BUILD")
endif()
if(MUSL_OPTIMIZED_BUILD)
set(MUSL_FLAGS "-static -Os -fPIE -pie")
add_definitions(-DMUSL_OPTIMIZED)
set(MUSL_FLAGS "-static -Os -fPIE -pie")
add_definitions(-DMUSL_OPTIMIZED)
endif()
# explicitly set hardening flags
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(FALCO_SECURITY_FLAGS "")
if(LINUX)
set(FALCO_SECURITY_FLAGS "${FALCO_SECURITY_FLAGS} -fstack-protector-strong")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,relro,-z,now")
set(FALCO_SECURITY_FLAGS "${FALCO_SECURITY_FLAGS} -fstack-protector-strong")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-z,relro,-z,now")
endif()
if(NOT MSVC)
if(CMAKE_BUILD_TYPE STREQUAL "release")
@@ -64,7 +64,9 @@ if(NOT MSVC)
endif()
endif()
set(CMAKE_COMMON_FLAGS "${FALCO_SECURITY_FLAGS} -Wall -ggdb ${FALCO_EXTRA_FEATURE_FLAGS} ${MINIMAL_BUILD_FLAGS} ${MUSL_FLAGS}")
set(CMAKE_COMMON_FLAGS
"${FALCO_SECURITY_FLAGS} -Wall -ggdb ${FALCO_EXTRA_FEATURE_FLAGS} ${MINIMAL_BUILD_FLAGS} ${MUSL_FLAGS}"
)
if(BUILD_WARNINGS_AS_ERRORS)
set(CMAKE_SUPPRESSED_WARNINGS
@@ -87,16 +89,11 @@ else() # MSVC
set(MINIMAL_BUILD ON)
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
# The WIN32_LEAN_AND_MEAN define avoids possible macro pollution
# when a libsinsp consumer includes the windows.h header.
# See: https://stackoverflow.com/a/28380820
# The WIN32_LEAN_AND_MEAN define avoids possible macro pollution when a libsinsp consumer
# includes the windows.h header: https://stackoverflow.com/a/28380820 Same goes for NOMINMAX:
# https://stackoverflow.com/questions/5004858/why-is-stdmin-failing-when-windows-h-is-included
add_compile_definitions(
_HAS_STD_BYTE=0
_CRT_SECURE_NO_WARNINGS
WIN32
MINIMAL_BUILD
WIN32_LEAN_AND_MEAN
_HAS_STD_BYTE=0 _CRT_SECURE_NO_WARNINGS WIN32 MINIMAL_BUILD WIN32_LEAN_AND_MEAN NOMINMAX
)
set(FALCOSECURITY_LIBS_COMMON_FLAGS "/EHsc /W3 /Zi /std:c++17")

View File

@@ -2,25 +2,28 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
# Tests coverage
option(FALCO_COVERAGE "Build test suite with coverage information" OFF)
if(FALCO_COVERAGE)
if(NOT (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")))
message(FATAL_ERROR "FALCO_COVERAGE requires GCC or Clang.")
endif()
if(NOT (("${CMAKE_CXX_COMPILER_ID}" MATCHES "GNU") OR ("${CMAKE_CXX_COMPILER_ID}" MATCHES
"Clang"))
)
message(FATAL_ERROR "FALCO_COVERAGE requires GCC or Clang.")
endif()
message(STATUS "Building with coverage information")
add_compile_options(-g --coverage)
set(CMAKE_SHARED_LINKER_FLAGS "--coverage ${CMAKE_SHARED_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "--coverage ${CMAKE_EXE_LINKER_FLAGS}")
message(STATUS "Building with coverage information")
add_compile_options(-g --coverage)
set(CMAKE_SHARED_LINKER_FLAGS "--coverage ${CMAKE_SHARED_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "--coverage ${CMAKE_EXE_LINKER_FLAGS}")
endif()

View File

@@ -2,30 +2,32 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
function(copy_files_to_build_dir source_files targetsuffix)
set(build_files)
set(build_files)
foreach(file_path ${source_files})
get_filename_component(trace_file ${file_path} NAME)
list(APPEND build_files ${CMAKE_CURRENT_BINARY_DIR}/${trace_file})
endforeach()
foreach(file_path ${source_files})
get_filename_component(trace_file ${file_path} NAME)
list(APPEND build_files ${CMAKE_CURRENT_BINARY_DIR}/${trace_file})
endforeach()
add_custom_target(copy-files-${targetsuffix} ALL
DEPENDS ${build_files})
add_custom_target(copy-files-${targetsuffix} ALL DEPENDS ${build_files})
add_custom_command(OUTPUT ${build_files}
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${source_files} ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${source_files})
add_custom_command(
OUTPUT ${build_files}
COMMAND ${CMAKE_COMMAND} -E copy_if_different ${source_files} ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${source_files}
)
endfunction()

View File

@@ -2,25 +2,27 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
option(USE_BUNDLED_CPPHTTPLIB "Enable building of the bundled cpp-httplib" ${USE_BUNDLED_DEPS})
if(USE_BUNDLED_CPPHTTPLIB)
include(FetchContent)
FetchContent_Declare(cpp-httplib
URL https://github.com/yhirose/cpp-httplib/archive/refs/tags/v0.15.3.tar.gz
URL_HASH SHA256=2121bbf38871bb2aafb5f7f2b9b94705366170909f434428352187cb0216124e
)
FetchContent_MakeAvailable(cpp-httplib)
include(FetchContent)
FetchContent_Declare(
cpp-httplib
URL https://github.com/yhirose/cpp-httplib/archive/refs/tags/v0.15.3.tar.gz
URL_HASH SHA256=2121bbf38871bb2aafb5f7f2b9b94705366170909f434428352187cb0216124e
)
FetchContent_MakeAvailable(cpp-httplib)
else()
find_package(httplib CONFIG REQUIRED)
find_package(httplib CONFIG REQUIRED)
endif()

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
#
@@ -19,25 +20,26 @@
option(USE_BUNDLED_CXXOPTS "Enable building of the bundled cxxopts" ${USE_BUNDLED_DEPS})
if(CXXOPTS_INCLUDE_DIR)
# we already have cxxopts
# we already have cxxopts
elseif(NOT USE_BUNDLED_CXXOPTS)
find_package(cxxopts CONFIG REQUIRED)
get_target_property(CXXOPTS_INCLUDE_DIR cxxopts::cxxopts INTERFACE_INCLUDE_DIRECTORIES)
find_package(cxxopts CONFIG REQUIRED)
get_target_property(CXXOPTS_INCLUDE_DIR cxxopts::cxxopts INTERFACE_INCLUDE_DIRECTORIES)
else()
set(CXXOPTS_SRC "${PROJECT_BINARY_DIR}/cxxopts-prefix/src/cxxopts/")
set(CXXOPTS_INCLUDE_DIR "${CXXOPTS_SRC}/include")
set(CXXOPTS_SRC "${PROJECT_BINARY_DIR}/cxxopts-prefix/src/cxxopts/")
set(CXXOPTS_INCLUDE_DIR "${CXXOPTS_SRC}/include")
message(STATUS "Using bundled cxxopts in ${CXXOPTS_SRC}")
message(STATUS "Using bundled cxxopts in ${CXXOPTS_SRC}")
ExternalProject_Add(
cxxopts
URL "https://github.com/jarro2783/cxxopts/archive/refs/tags/v3.0.0.tar.gz"
URL_HASH "SHA256=36f41fa2a46b3c1466613b63f3fa73dc24d912bc90d667147f1e43215a8c6d00"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND "")
ExternalProject_Add(
cxxopts
URL "https://github.com/jarro2783/cxxopts/archive/refs/tags/v3.0.0.tar.gz"
URL_HASH "SHA256=36f41fa2a46b3c1466613b63f3fa73dc24d912bc90d667147f1e43215a8c6d00"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
)
endif()
if(NOT TARGET cxxopts)
add_custom_target(cxxopts)
add_custom_target(cxxopts)
endif()

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
cmake_minimum_required(VERSION 3.5.1)
@@ -20,12 +21,12 @@ message(STATUS "Driver repository: ${DRIVER_REPO}")
message(STATUS "Driver version: ${DRIVER_VERSION}")
ExternalProject_Add(
driver
URL "https://github.com/${DRIVER_REPO}/archive/${DRIVER_VERSION}.tar.gz"
URL_HASH "${DRIVER_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
PATCH_COMMAND sh -c "mv ./driver ../driver.tmp && rm -rf ./* && mv ../driver.tmp/* ."
driver
URL "https://github.com/${DRIVER_REPO}/archive/${DRIVER_VERSION}.tar.gz"
URL_HASH "${DRIVER_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
PATCH_COMMAND sh -c "mv ./driver ../driver.tmp && rm -rf ./* && mv ../driver.tmp/* ."
)

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
set(DRIVER_CMAKE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/driver-repo")
@@ -18,37 +19,42 @@ set(DRIVER_CMAKE_WORKING_DIR "${CMAKE_BINARY_DIR}/driver-repo")
file(MAKE_DIRECTORY ${DRIVER_CMAKE_WORKING_DIR})
if(DRIVER_SOURCE_DIR)
set(DRIVER_VERSION "0.0.0-local")
message(STATUS "Using local version for driver: '${DRIVER_SOURCE_DIR}'")
set(DRIVER_VERSION "0.0.0-local")
message(STATUS "Using local version for driver: '${DRIVER_SOURCE_DIR}'")
else()
# DRIVER_REPO accepts a repository name (<org name>/<repo name>) alternative to the falcosecurity/libs repository.
# In case you want to test against a fork of falcosecurity/libs just pass the variable -
# ie., `cmake -DDRIVER_REPO=<your-gh-handle>/libs ..`
if (NOT DRIVER_REPO)
set(DRIVER_REPO "falcosecurity/libs")
endif()
# DRIVER_REPO accepts a repository name (<org name>/<repo name>) alternative to the
# falcosecurity/libs repository. In case you want to test against a fork of falcosecurity/libs
# just pass the variable - ie., `cmake -DDRIVER_REPO=<your-gh-handle>/libs ..`
if(NOT DRIVER_REPO)
set(DRIVER_REPO "falcosecurity/libs")
endif()
# DRIVER_VERSION accepts a git reference (branch name, commit hash, or tag) to the falcosecurity/libs repository
# which contains the driver source code under the `/driver` directory.
# The chosen driver version must be compatible with the given FALCOSECURITY_LIBS_VERSION.
# In case you want to test against another driver version (or branch, or commit) just pass the variable -
# ie., `cmake -DDRIVER_VERSION=dev ..`
if(NOT DRIVER_VERSION)
set(DRIVER_VERSION "0.17.0-rc1")
set(DRIVER_CHECKSUM "SHA256=63809beb5e448911f153b8c25f814075238a55f301923aeb3d2374be6309460b")
endif()
# DRIVER_VERSION accepts a git reference (branch name, commit hash, or tag) to the
# falcosecurity/libs repository which contains the driver source code under the `/driver`
# directory. The chosen driver version must be compatible with the given
# FALCOSECURITY_LIBS_VERSION. In case you want to test against another driver version (or
# branch, or commit) just pass the variable - ie., `cmake -DDRIVER_VERSION=dev ..`
if(NOT DRIVER_VERSION)
set(DRIVER_VERSION "7.3.0+driver")
set(DRIVER_CHECKSUM
"SHA256=8f572d9a83feda635a3fa53b859d61e37af127c241e35068aadee3bc50d212c0"
)
endif()
# cd /path/to/build && cmake /path/to/source
execute_process(COMMAND "${CMAKE_COMMAND}"
-DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
-DDRIVER_REPO=${DRIVER_REPO}
-DDRIVER_VERSION=${DRIVER_VERSION}
-DDRIVER_CHECKSUM=${DRIVER_CHECKSUM}
${DRIVER_CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${DRIVER_CMAKE_WORKING_DIR})
# cd /path/to/build && cmake /path/to/source
execute_process(
COMMAND
"${CMAKE_COMMAND}" -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}" -DDRIVER_REPO=${DRIVER_REPO}
-DDRIVER_VERSION=${DRIVER_VERSION} -DDRIVER_CHECKSUM=${DRIVER_CHECKSUM}
${DRIVER_CMAKE_SOURCE_DIR}
WORKING_DIRECTORY ${DRIVER_CMAKE_WORKING_DIR}
)
# cmake --build .
execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${DRIVER_CMAKE_WORKING_DIR}")
set(DRIVER_SOURCE_DIR "${DRIVER_CMAKE_WORKING_DIR}/driver-prefix/src/driver")
# cmake --build .
execute_process(
COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${DRIVER_CMAKE_WORKING_DIR}"
)
set(DRIVER_SOURCE_DIR "${DRIVER_CMAKE_WORKING_DIR}/driver-prefix/src/driver")
endif()
add_definitions(-D_GNU_SOURCE)

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
# Retrieve git ref and commit hash
@@ -17,33 +18,39 @@ include(GetVersionFromGit)
# Get Falco version variable according to git index
if(NOT FALCO_VERSION)
set(FALCO_VERSION "0.0.0")
get_version_from_git(FALCO_VERSION "" "")
set(FALCO_VERSION "0.0.0")
get_version_from_git(FALCO_VERSION "" "")
endif()
# Remove the starting "v" in case there is one
string(REGEX REPLACE "^v(.*)" "\\1" FALCO_VERSION "${FALCO_VERSION}")
string(REGEX MATCH "^(0|[1-9][0-9]*)" FALCO_VERSION_MAJOR "${FALCO_VERSION}")
string(REGEX REPLACE "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\..*" "\\2" FALCO_VERSION_MINOR "${FALCO_VERSION}")
string(REGEX REPLACE "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*).*" "\\3" FALCO_VERSION_PATCH
"${FALCO_VERSION}")
string(REGEX REPLACE "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\..*" "\\2" FALCO_VERSION_MINOR
"${FALCO_VERSION}"
)
string(REGEX REPLACE "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*).*" "\\3"
FALCO_VERSION_PATCH "${FALCO_VERSION}"
)
string(
REGEX
REPLACE
"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*).*"
"\\5"
FALCO_VERSION_PRERELEASE
"${FALCO_VERSION}")
REGEX
REPLACE
"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*).*"
"\\5"
FALCO_VERSION_PRERELEASE
"${FALCO_VERSION}"
)
if(FALCO_VERSION_PRERELEASE STREQUAL "${FALCO_VERSION}")
set(FALCO_VERSION_PRERELEASE "")
set(FALCO_VERSION_PRERELEASE "")
endif()
if(NOT FALCO_VERSION_BUILD)
string(REGEX REPLACE ".*\\+([0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)" "\\1" FALCO_VERSION_BUILD "${FALCO_VERSION}")
string(REGEX REPLACE ".*\\+([0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)" "\\1" FALCO_VERSION_BUILD
"${FALCO_VERSION}"
)
endif()
if(FALCO_VERSION_BUILD STREQUAL "${FALCO_VERSION}")
set(FALCO_VERSION_BUILD "")
set(FALCO_VERSION_BUILD "")
endif()
message(STATUS "Falco version: ${FALCO_VERSION}")

View File

@@ -2,37 +2,55 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
include(ExternalProject)
string(TOLOWER ${CMAKE_HOST_SYSTEM_NAME} FALCOCTL_SYSTEM_NAME)
option(ADD_FALCOCTL_DEPENDENCY "Add falcoctl dependency while building falco" ON)
set(FALCOCTL_VERSION "0.8.0-rc6")
if(ADD_FALCOCTL_DEPENDENCY)
string(TOLOWER ${CMAKE_HOST_SYSTEM_NAME} FALCOCTL_SYSTEM_NAME)
if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64")
set(FALCOCTL_SYSTEM_PROC_GO "amd64")
set(FALCOCTL_HASH "af49a15f28281aff37aa57808211cdd0772966a694da3b5a256d0e58e27bd16b")
else() # aarch64
set(FALCOCTL_SYSTEM_PROC_GO "arm64")
set(FALCOCTL_HASH "262189f954be20372ff79c5e984b64e530cdfeecc6df74be3b8846fb52ee2bdf")
set(FALCOCTL_VERSION "0.10.0")
message(STATUS "Building with falcoctl: ${FALCOCTL_VERSION}")
if(${CMAKE_HOST_SYSTEM_PROCESSOR} STREQUAL "x86_64")
set(FALCOCTL_SYSTEM_PROC_GO "amd64")
set(FALCOCTL_HASH "32d1be4ab2335d9c3fc8ae8900341bcc26d3166094fc553ddb7bb783aa6c7b68")
else() # aarch64
set(FALCOCTL_SYSTEM_PROC_GO "arm64")
set(FALCOCTL_HASH "9186fd948c1230c338a7fa36d6569ce85d3c4aa8153b30e8d86d2e887eb76756")
endif()
ExternalProject_Add(
falcoctl
URL "https://github.com/falcosecurity/falcoctl/releases/download/v${FALCOCTL_VERSION}/falcoctl_${FALCOCTL_VERSION}_${FALCOCTL_SYSTEM_NAME}_${FALCOCTL_SYSTEM_PROC_GO}.tar.gz"
URL_HASH "SHA256=${FALCOCTL_HASH}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
)
install(
PROGRAMS "${PROJECT_BINARY_DIR}/falcoctl-prefix/src/falcoctl/falcoctl"
DESTINATION "${FALCO_BIN_DIR}"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(
DIRECTORY
DESTINATION "${FALCO_ABSOLUTE_SHARE_DIR}/plugins"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
else()
message(STATUS "Won't build with falcoctl")
endif()
ExternalProject_Add(
falcoctl
URL "https://github.com/falcosecurity/falcoctl/releases/download/v${FALCOCTL_VERSION}/falcoctl_${FALCOCTL_VERSION}_${FALCOCTL_SYSTEM_NAME}_${FALCOCTL_SYSTEM_PROC_GO}.tar.gz"
URL_HASH "SHA256=${FALCOCTL_HASH}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND "")
install(PROGRAMS "${PROJECT_BINARY_DIR}/falcoctl-prefix/src/falcoctl/falcoctl" DESTINATION "${FALCO_BIN_DIR}" COMPONENT "${FALCO_COMPONENT_NAME}")
install(DIRECTORY DESTINATION "${FALCO_ABSOLUTE_SHARE_DIR}/plugins" COMPONENT "${FALCO_COMPONENT_NAME}")

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
cmake_minimum_required(VERSION 3.5.1)
@@ -20,11 +21,11 @@ message(STATUS "Libs repository: ${FALCOSECURITY_LIBS_REPO}")
message(STATUS "Libs version: ${FALCOSECURITY_LIBS_VERSION}")
ExternalProject_Add(
falcosecurity-libs
URL "https://github.com/${FALCOSECURITY_LIBS_REPO}/archive/${FALCOSECURITY_LIBS_VERSION}.tar.gz"
URL_HASH "${FALCOSECURITY_LIBS_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
falcosecurity-libs
URL "https://github.com/${FALCOSECURITY_LIBS_REPO}/archive/${FALCOSECURITY_LIBS_VERSION}.tar.gz"
URL_HASH "${FALCOSECURITY_LIBS_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)

View File

@@ -2,65 +2,82 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
set(FALCOSECURITY_LIBS_CMAKE_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/falcosecurity-libs-repo")
set(FALCOSECURITY_LIBS_CMAKE_SOURCE_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/falcosecurity-libs-repo"
)
set(FALCOSECURITY_LIBS_CMAKE_WORKING_DIR "${CMAKE_BINARY_DIR}/falcosecurity-libs-repo")
file(MAKE_DIRECTORY ${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR})
# explicitly disable the bundled driver, since we pull it separately
set(USE_BUNDLED_DRIVER OFF CACHE BOOL "")
set(USE_BUNDLED_DRIVER
OFF
CACHE BOOL ""
)
if(FALCOSECURITY_LIBS_SOURCE_DIR)
set(FALCOSECURITY_LIBS_VERSION "0.0.0-local")
message(STATUS "Using local version of falcosecurity/libs: '${FALCOSECURITY_LIBS_SOURCE_DIR}'")
set(FALCOSECURITY_LIBS_VERSION "0.0.0-local")
message(STATUS "Using local version of falcosecurity/libs: '${FALCOSECURITY_LIBS_SOURCE_DIR}'")
else()
# FALCOSECURITY_LIBS_REPO accepts a repository name (<org name>/<repo name>) alternative to the falcosecurity/libs repository.
# In case you want to test against a fork of falcosecurity/libs just pass the variable -
# ie., `cmake -DFALCOSECURITY_LIBS_REPO=<your-gh-handle>/libs ..`
if (NOT FALCOSECURITY_LIBS_REPO)
set(FALCOSECURITY_LIBS_REPO "falcosecurity/libs")
endif()
# FALCOSECURITY_LIBS_REPO accepts a repository name (<org name>/<repo name>) alternative to the
# falcosecurity/libs repository. In case you want to test against a fork of falcosecurity/libs
# just pass the variable - ie., `cmake -DFALCOSECURITY_LIBS_REPO=<your-gh-handle>/libs ..`
if(NOT FALCOSECURITY_LIBS_REPO)
set(FALCOSECURITY_LIBS_REPO "falcosecurity/libs")
endif()
# FALCOSECURITY_LIBS_VERSION accepts a git reference (branch name, commit hash, or tag) to the falcosecurity/libs repository.
# In case you want to test against another falcosecurity/libs version (or branch, or commit) just pass the variable -
# ie., `cmake -DFALCOSECURITY_LIBS_VERSION=dev ..`
if(NOT FALCOSECURITY_LIBS_VERSION)
set(FALCOSECURITY_LIBS_VERSION "0.17.0-rc1")
set(FALCOSECURITY_LIBS_CHECKSUM "SHA256=63809beb5e448911f153b8c25f814075238a55f301923aeb3d2374be6309460b")
endif()
# FALCOSECURITY_LIBS_VERSION accepts a git reference (branch name, commit hash, or tag) to the
# falcosecurity/libs repository. In case you want to test against another falcosecurity/libs
# version (or branch, or commit) just pass the variable - ie., `cmake
# -DFALCOSECURITY_LIBS_VERSION=dev ..`
if(NOT FALCOSECURITY_LIBS_VERSION)
set(FALCOSECURITY_LIBS_VERSION "0.18.1")
set(FALCOSECURITY_LIBS_CHECKSUM
"SHA256=1812e8236c4cb51d3fe5dd066d71be99f25da7ed22d8feeeebeed09bdc26325f"
)
endif()
# cd /path/to/build && cmake /path/to/source
execute_process(COMMAND "${CMAKE_COMMAND}"
-DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
-DFALCOSECURITY_LIBS_REPO=${FALCOSECURITY_LIBS_REPO}
-DFALCOSECURITY_LIBS_VERSION=${FALCOSECURITY_LIBS_VERSION}
-DFALCOSECURITY_LIBS_CHECKSUM=${FALCOSECURITY_LIBS_CHECKSUM}
${FALCOSECURITY_LIBS_CMAKE_SOURCE_DIR} WORKING_DIRECTORY ${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR})
# cd /path/to/build && cmake /path/to/source
execute_process(
COMMAND
"${CMAKE_COMMAND}" -DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}"
-DFALCOSECURITY_LIBS_REPO=${FALCOSECURITY_LIBS_REPO}
-DFALCOSECURITY_LIBS_VERSION=${FALCOSECURITY_LIBS_VERSION}
-DFALCOSECURITY_LIBS_CHECKSUM=${FALCOSECURITY_LIBS_CHECKSUM}
${FALCOSECURITY_LIBS_CMAKE_SOURCE_DIR}
WORKING_DIRECTORY ${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR}
)
# cmake --build .
execute_process(COMMAND "${CMAKE_COMMAND}" --build . WORKING_DIRECTORY "${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR}")
set(FALCOSECURITY_LIBS_SOURCE_DIR "${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR}/falcosecurity-libs-prefix/src/falcosecurity-libs")
# cmake --build .
execute_process(
COMMAND "${CMAKE_COMMAND}" --build .
WORKING_DIRECTORY "${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR}"
)
set(FALCOSECURITY_LIBS_SOURCE_DIR
"${FALCOSECURITY_LIBS_CMAKE_WORKING_DIR}/falcosecurity-libs-prefix/src/falcosecurity-libs"
)
endif()
set(LIBS_PACKAGE_NAME "falcosecurity")
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
add_definitions(-D_GNU_SOURCE)
add_definitions(-DHAS_CAPTURE)
add_definitions(-D_GNU_SOURCE)
add_definitions(-DHAS_CAPTURE)
endif()
if(MUSL_OPTIMIZED_BUILD)
add_definitions(-DMUSL_OPTIMIZED)
add_definitions(-DMUSL_OPTIMIZED)
endif()
set(SCAP_HOST_ROOT_ENV_VAR_NAME "HOST_ROOT")
@@ -68,27 +85,60 @@ set(SCAP_HOSTNAME_ENV_VAR "FALCO_HOSTNAME")
set(SINSP_AGENT_CGROUP_MEM_PATH_ENV_VAR "FALCO_CGROUP_MEM_PATH")
if(NOT LIBS_DIR)
set(LIBS_DIR "${FALCOSECURITY_LIBS_SOURCE_DIR}")
set(LIBS_DIR "${FALCOSECURITY_LIBS_SOURCE_DIR}")
endif()
# configure gVisor support
set(BUILD_LIBSCAP_GVISOR ${BUILD_FALCO_GVISOR} CACHE BOOL "")
set(BUILD_LIBSCAP_GVISOR
${BUILD_FALCO_GVISOR}
CACHE BOOL ""
)
# configure modern BPF support
set(BUILD_LIBSCAP_MODERN_BPF ${BUILD_FALCO_MODERN_BPF} CACHE BOOL "")
set(BUILD_LIBSCAP_MODERN_BPF
${BUILD_FALCO_MODERN_BPF}
CACHE BOOL ""
)
# explicitly disable the tests/examples of this dependency
set(CREATE_TEST_TARGETS OFF CACHE BOOL "")
set(BUILD_LIBSCAP_EXAMPLES OFF CACHE BOOL "")
set(CREATE_TEST_TARGETS
OFF
CACHE BOOL ""
)
set(BUILD_LIBSCAP_EXAMPLES
OFF
CACHE BOOL ""
)
set(USE_BUNDLED_TBB ON CACHE BOOL "")
set(USE_BUNDLED_JSONCPP ON CACHE BOOL "")
set(USE_BUNDLED_VALIJSON ON CACHE BOOL "")
set(USE_BUNDLED_RE2 ON CACHE BOOL "")
set(USE_BUNDLED_UTHASH ON CACHE BOOL "")
set(USE_BUNDLED_TBB
ON
CACHE BOOL ""
)
set(USE_BUNDLED_JSONCPP
ON
CACHE BOOL ""
)
set(USE_BUNDLED_VALIJSON
ON
CACHE BOOL ""
)
set(USE_BUNDLED_RE2
ON
CACHE BOOL ""
)
set(USE_BUNDLED_UTHASH
ON
CACHE BOOL ""
)
if(USE_DYNAMIC_LIBELF)
set(USE_BUNDLED_LIBELF OFF CACHE BOOL "")
set(USE_SHARED_LIBELF ON CACHE BOOL "")
set(USE_BUNDLED_LIBELF
OFF
CACHE BOOL ""
)
set(USE_SHARED_LIBELF
ON
CACHE BOOL ""
)
endif()
list(APPEND CMAKE_MODULE_PATH "${FALCOSECURITY_LIBS_SOURCE_DIR}/cmake/modules")
@@ -97,15 +147,18 @@ include(CheckSymbolExists)
check_symbol_exists(strlcpy "string.h" HAVE_STRLCPY)
if(HAVE_STRLCPY)
message(STATUS "Existing strlcpy and strlcat found, will *not* use local definition by setting -DHAVE_STRLCPY and -DHAVE_STRLCAT.")
add_definitions(-DHAVE_STRLCPY)
add_definitions(-DHAVE_STRLCAT)
message(
STATUS
"Existing strlcpy and strlcat found, will *not* use local definition by setting -DHAVE_STRLCPY and -DHAVE_STRLCAT."
)
add_definitions(-DHAVE_STRLCPY)
add_definitions(-DHAVE_STRLCAT)
else()
message(STATUS "No strlcpy and strlcat found, will use local definition")
message(STATUS "No strlcpy and strlcat found, will use local definition")
endif()
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
include(driver)
include(driver)
endif()
include(libscap)
include(libsinsp)

View File

@@ -2,25 +2,27 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
option(USE_BUNDLED_NLOHMANN_JSON "Enable building of the bundled nlohmann-json" ${USE_BUNDLED_DEPS})
if(USE_BUNDLED_NLOHMANN_JSON)
include(FetchContent)
FetchContent_Declare(nlohmann_json
URL https://github.com/nlohmann/json/archive/v3.11.3.tar.gz
URL_HASH SHA256=0d8ef5af7f9794e3263480193c491549b2ba6cc74bb018906202ada498a79406
)
FetchContent_MakeAvailable(nlohmann_json)
include(FetchContent)
FetchContent_Declare(
nlohmann_json
URL https://github.com/nlohmann/json/archive/v3.11.3.tar.gz
URL_HASH SHA256=0d8ef5af7f9794e3263480193c491549b2ba6cc74bb018906202ada498a79406
)
FetchContent_MakeAvailable(nlohmann_json)
else()
find_package(nlohmann_json CONFIG REQUIRED)
find_package(nlohmann_json CONFIG REQUIRED)
endif()

View File

@@ -2,36 +2,47 @@
#
# Copyright (C) 2024 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
include(GNUInstallDirs)
include(ExternalProject)
# falco_rules.yaml
set(FALCOSECURITY_RULES_FALCO_VERSION "falco-rules-3.0.0")
set(FALCOSECURITY_RULES_FALCO_CHECKSUM "SHA256=2e91799fee49c2daf58fb482e47410a21433eb116e02cde18206f7af87449ddb")
set(FALCOSECURITY_RULES_FALCO_PATH "${PROJECT_BINARY_DIR}/falcosecurity-rules-falco-prefix/src/falcosecurity-rules-falco/falco_rules.yaml")
ExternalProject_Add(
falcosecurity-rules-falco
URL "https://download.falco.org/rules/${FALCOSECURITY_RULES_FALCO_VERSION}.tar.gz"
URL_HASH "${FALCOSECURITY_RULES_FALCO_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
if(NOT DEFINED FALCOSECURITY_RULES_FALCO_PATH)
# falco_rules.yaml
set(FALCOSECURITY_RULES_FALCO_VERSION "falco-rules-3.2.0")
set(FALCOSECURITY_RULES_FALCO_CHECKSUM
"SHA256=b3990bf0209cfbf6a903b361e458a1f5851a9a5aeee808ad26a5ddbe1377157d"
)
set(FALCOSECURITY_RULES_FALCO_PATH
"${PROJECT_BINARY_DIR}/falcosecurity-rules-falco-prefix/src/falcosecurity-rules-falco/falco_rules.yaml"
)
ExternalProject_Add(
falcosecurity-rules-falco
URL "https://download.falco.org/rules/${FALCOSECURITY_RULES_FALCO_VERSION}.tar.gz"
URL_HASH "${FALCOSECURITY_RULES_FALCO_CHECKSUM}"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
endif()
# falco_rules.local.yaml
set(FALCOSECURITY_RULES_LOCAL_PATH "${PROJECT_BINARY_DIR}/falcosecurity-rules-local-prefix/falco_rules.local.yaml")
file(WRITE "${FALCOSECURITY_RULES_LOCAL_PATH}" "# Your custom rules!\n")
if(NOT DEFINED FALCOSECURITY_RULES_LOCAL_PATH)
# falco_rules.local.yaml
set(FALCOSECURITY_RULES_LOCAL_PATH
"${PROJECT_BINARY_DIR}/falcosecurity-rules-local-prefix/falco_rules.local.yaml"
)
file(WRITE "${FALCOSECURITY_RULES_LOCAL_PATH}" "# Your custom rules!\n")
endif()
if(NOT DEFINED FALCO_ETC_DIR)
set(FALCO_ETC_DIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/falco")
@@ -42,34 +53,43 @@ if(WIN32 OR APPLE)
endif()
if(NOT DEFINED FALCO_RULES_DEST_FILENAME)
set(FALCO_RULES_DEST_FILENAME "falco_rules.yaml")
set(FALCO_LOCAL_RULES_DEST_FILENAME "falco_rules.local.yaml")
set(FALCO_RULES_DEST_FILENAME "falco_rules.yaml")
set(FALCO_LOCAL_RULES_DEST_FILENAME "falco_rules.local.yaml")
endif()
if(DEFINED FALCO_COMPONENT) # Allow a slim version of Falco to be embedded in other projects, intentionally *not* installing all rulesets.
install(
FILES "${FALCOSECURITY_RULES_FALCO_PATH}"
COMPONENT "${FALCO_COMPONENT}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_RULES_DEST_FILENAME}")
if(DEFINED FALCO_COMPONENT) # Allow a slim version of Falco to be embedded in other projects,
# intentionally *not* installing all rulesets.
install(
FILES "${FALCOSECURITY_RULES_FALCO_PATH}"
COMPONENT "${FALCO_COMPONENT}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_RULES_DEST_FILENAME}"
)
install(
FILES "${FALCOSECURITY_RULES_LOCAL_PATH}"
COMPONENT "${FALCO_COMPONENT}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_LOCAL_RULES_DEST_FILENAME}")
install(
FILES "${FALCOSECURITY_RULES_LOCAL_PATH}"
COMPONENT "${FALCO_COMPONENT}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_LOCAL_RULES_DEST_FILENAME}"
)
else() # Default Falco installation
install(
FILES "${FALCOSECURITY_RULES_FALCO_PATH}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_RULES_DEST_FILENAME}"
COMPONENT "${FALCO_COMPONENT_NAME}")
install(
FILES "${FALCOSECURITY_RULES_FALCO_PATH}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_RULES_DEST_FILENAME}"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(
FILES "${FALCOSECURITY_RULES_LOCAL_PATH}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_LOCAL_RULES_DEST_FILENAME}"
COMPONENT "${FALCO_COMPONENT_NAME}")
install(
FILES "${FALCOSECURITY_RULES_LOCAL_PATH}"
DESTINATION "${FALCO_ETC_DIR}"
RENAME "${FALCO_LOCAL_RULES_DEST_FILENAME}"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
install(DIRECTORY DESTINATION "${FALCO_ETC_DIR}/rules.d" COMPONENT "${FALCO_COMPONENT_NAME}")
install(
DIRECTORY
DESTINATION "${FALCO_ETC_DIR}/rules.d"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
endif()

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
# create the reports folder
@@ -22,35 +23,42 @@ find_program(CPPCHECK cppcheck)
find_program(CPPCHECK_HTMLREPORT cppcheck-htmlreport)
if(NOT CPPCHECK)
message(STATUS "cppcheck command not found, static code analysis using cppcheck will not be available.")
message(
STATUS
"cppcheck command not found, static code analysis using cppcheck will not be available."
)
else()
message(STATUS "cppcheck found at: ${CPPCHECK}")
# we are aware that cppcheck can be run
# along with the software compilation in a single step
# using the CMAKE_CXX_CPPCHECK variables.
# However, for practical needs we want to keep the
# two things separated and have a specific target for it.
# Our cppcheck target reads the compilation database produced by CMake
set(CMAKE_EXPORT_COMPILE_COMMANDS On)
add_custom_target(
cppcheck
COMMAND ${CPPCHECK}
"--enable=all"
"--force"
"--inconclusive"
"--inline-suppr" # allows to specify suppressions directly in source code
"--xml" # we want to generate a report
"--output-file=${CMAKE_CURRENT_BINARY_DIR}/static-analysis-reports/cppcheck/cppcheck.xml" # generate the report under the reports folder in the build folder
"-i${CMAKE_CURRENT_BINARY_DIR}"# exclude the build folder
"${CMAKE_SOURCE_DIR}"
)
message(STATUS "cppcheck found at: ${CPPCHECK}")
# we are aware that cppcheck can be run along with the software compilation in a single step
# using the CMAKE_CXX_CPPCHECK variables. However, for practical needs we want to keep the two
# things separated and have a specific target for it. Our cppcheck target reads the compilation
# database produced by CMake
set(CMAKE_EXPORT_COMPILE_COMMANDS On)
add_custom_target(
cppcheck
COMMAND
${CPPCHECK} "--enable=all" "--force" "--inconclusive" "--inline-suppr" # allows to
# specify suppressions directly in source code
"--xml" # we want to generate a report
"--output-file=${CMAKE_CURRENT_BINARY_DIR}/static-analysis-reports/cppcheck/cppcheck.xml" # generate
# the report under the reports folder in the build folder
"-i${CMAKE_CURRENT_BINARY_DIR}" # exclude the build folder
"${CMAKE_SOURCE_DIR}"
)
endif() # CPPCHECK
if(NOT CPPCHECK_HTMLREPORT)
message(STATUS "cppcheck-htmlreport command not found, will not be able to produce html reports for cppcheck results")
message(
STATUS
"cppcheck-htmlreport command not found, will not be able to produce html reports for cppcheck results"
)
else()
message(STATUS "cppcheck-htmlreport found at: ${CPPCHECK_HTMLREPORT}")
add_custom_target(
cppcheck_htmlreport
COMMAND ${CPPCHECK_HTMLREPORT} --title=${CMAKE_PROJECT_NAME} --report-dir=${CMAKE_CURRENT_BINARY_DIR}/static-analysis-reports/cppcheck --file=static-analysis-reports/cppcheck/cppcheck.xml)
message(STATUS "cppcheck-htmlreport found at: ${CPPCHECK_HTMLREPORT}")
add_custom_target(
cppcheck_htmlreport
COMMAND
${CPPCHECK_HTMLREPORT} --title=${CMAKE_PROJECT_NAME}
--report-dir=${CMAKE_CURRENT_BINARY_DIR}/static-analysis-reports/cppcheck
--file=static-analysis-reports/cppcheck/cppcheck.xml
)
endif() # CPPCHECK_HTMLREPORT

View File

@@ -2,25 +2,27 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
option(USE_BUNDLED_YAMLCPP "Enable building of the bundled yamlcpp" ${USE_BUNDLED_DEPS})
if(USE_BUNDLED_YAMLCPP)
include(FetchContent)
FetchContent_Declare(yamlcpp
URL https://github.com/jbeder/yaml-cpp/archive/refs/tags/0.8.0.tar.gz
URL_HASH SHA256=fbe74bbdcee21d656715688706da3c8becfd946d92cd44705cc6098bb23b3a16
)
FetchContent_MakeAvailable(yamlcpp)
include(FetchContent)
FetchContent_Declare(
yamlcpp
URL https://github.com/jbeder/yaml-cpp/archive/refs/tags/0.8.0.tar.gz
URL_HASH SHA256=fbe74bbdcee21d656715688706da3c8becfd946d92cd44705cc6098bb23b3a16
)
FetchContent_MakeAvailable(yamlcpp)
else()
find_package(yaml-cpp CONFIG REQUIRED)
find_package(yaml-cpp CONFIG REQUIRED)
endif()

View File

@@ -0,0 +1,17 @@
# Warning
This environment is provided for demonstration purposes only and does not represent a production ready deployment of Falco.
# Components
The components that this docker-compose file spins up are [Falco](https://falco.org/), [falcosidekick](https://github.com/falcosecurity/falcosidekick), [falcosidekick-ui](https://github.com/falcosecurity/falcosidekick-ui) and a [redis](https://redis.io/) database.
# Running
To start this environment run `docker-compose up`.
Note: You may need to use sudo for Falco to start correctly.
# Cleaning up
To clean up run `docker-compose rm`.
# Generating events
If you'd like to generate events that will trigger rules and show up in the UI you can run `docker run -it --rm falcosecurity/event-generator run syscall --loop`

View File

@@ -0,0 +1,11 @@
# [Stable] `http_output`
#
# Send logs to an HTTP endpoint or webhook.
#
# When using falcosidekick, it is necessary to set `json_output` to true.
json_output: true
json_include_output_property: true
http_output:
enabled: true
url: "http://falco-sidekick:2801/"

View File

@@ -0,0 +1,34 @@
version: "3"
services:
falco:
container_name: falco
cap_drop:
- all
cap_add:
- sys_admin
- sys_resource
- sys_ptrace
volumes:
- /var/run/docker.sock:/host/var/run/docker.sock
- /proc:/host/proc:ro
- /etc:/host/etc:ro
- ./config/http_output.yml:/etc/falco/config.d/http_output.yml
image: falcosecurity/falco-no-driver:latest
sidekick:
container_name: falco-sidekick
image: falcosecurity/falcosidekick
environment:
WEBUI_URL: http://falco-webui:2802
webui:
container_name: falco-webui
image: falcosecurity/falcosidekick-ui:2.2.0
ports:
- 2802:2802
depends_on:
- redis
command: ['-r', 'redis:6379', '-d']
redis:
image: redis/redis-stack:7.2.0-v11

View File

@@ -468,7 +468,7 @@ load_plugins: []
plugins:
- name: k8saudit
library_path: libk8saudit.so
init_config:
init_config: ""
# maxEventSize: 262144
# webhookMaxBatchSize: 12582912
# sslCertificate: /etc/falco/falco.pem
@@ -518,6 +518,15 @@ json_output: false
# case.
json_include_output_property: true
# [Incubating] `json_include_message_property`
#
# When using JSON output in Falco, you have the option to include the formatted
# rule output without timestamp or priority. For instance, if a rule specifies
# an "output" property like "Opened process %proc.name" the "message" field will
# only contain "Opened process bash" whereas the "output" field will contain more
# information.
json_include_message_property: false
# [Stable] `json_include_tags_property`
#
# When using JSON output in Falco, you have the option to include the "tags"
@@ -576,6 +585,48 @@ rule_matching: first
outputs_queue:
capacity: 0
# [Sandbox] `append_output`
#
# Add information to the Falco output.
# With this setting you can add more information to the Falco output message, customizable by
# rule, tag or source.
# You can also add additional data that will appear in the output_fields property
# of JSON formatted messages or gRPC output but will not be part of the regular output message.
# This allows you to add custom fields that can help you filter your Falco events without
# polluting the message text.
#
# Each append_output entry has an optional `match` map which specifies which rules will be
# affected.
# `match`:
# `rule`: append output only to a specific rule
# `source`: append output only to a specific source
# `tags`: append output only to rules that have all of the specified tags
# If none of the above are specified (or `match` is omitted)
# output is appended to all events.
# If more than one match condition is specified output will be appended to events
# that match all conditions.
# And several options to add output:
# `extra_output`: add output to the Falco message
# `extra_fields`: add new fields to the JSON output and structured output, which will not
# affect the regular Falco message in any way. These can be specified as a
# custom name with a custom format or as any supported field
# (see: https://falco.org/docs/reference/rules/supported-fields/)
#
# Example:
#
# append_output:
# - match:
# source: syscall
# extra_output: "on CPU %evt.cpu"
# extra_fields:
# - home_directory: "${HOME}"
# - evt.hostname
#
# In the example above every event coming from the syscall source will get an extra message
# at the end telling the CPU number. In addition, if `json_output` is true, in the "output_fields"
# property you will find three new ones: "evt.cpu", "home_directory" which will contain the value of the
# environment variable $HOME, and "evt.hostname" which will contain the hostname.
##########################
# Falco outputs channels #
@@ -1021,6 +1072,9 @@ syscall_event_drops:
# counters reflect monotonic values since Falco's start and are exported at a
# constant stats interval.
#
# `kernel_event_counters_per_cpu_enabled`: Detailed kernel event and drop counters
# per CPU. Typically used when debugging and not in production.
#
# `libbpf_stats_enabled`: Exposes statistics similar to `bpftool prog show`,
# providing information such as the number of invocations of each BPF program
# attached by Falco and the time spent in each program measured in nanoseconds.
@@ -1037,6 +1091,11 @@ syscall_event_drops:
# beneficial for exploring the data schema and ensuring that fields with empty
# values are included in the output.
#
# `plugins_metrics_enabled`: Falco can now expose your custom plugins'
# metrics. Please note that if the respective plugin has no metrics implemented,
# there will be no metrics available. In other words, there are no default or
# generic plugin metrics at this time. This may be subject to change.
#
# If metrics are enabled, the web server can be configured to activate the
# corresponding Prometheus endpoint using `webserver.prometheus_metrics_enabled`.
# Prometheus output can be used in combination with the other output options.
@@ -1054,7 +1113,10 @@ metrics:
resource_utilization_enabled: true
state_counters_enabled: true
kernel_event_counters_enabled: true
# Enabling `kernel_event_counters_per_cpu_enabled` automatically enables `kernel_event_counters_enabled`
kernel_event_counters_per_cpu_enabled: false
libbpf_stats_enabled: true
plugins_metrics_enabled: true
convert_memory_to_mb: true
include_empty_values: false
@@ -1200,33 +1262,43 @@ base_syscalls:
falco_libs:
thread_table_size: 262144
# [Stable] Guidance for Kubernetes container engine command-line args settings
# [Incubating] `container_engines`
#
# Modern cloud environments, particularly Kubernetes, heavily rely on
# containerized workload deployments. When capturing events with Falco, it
# becomes essential to identify the owner of the workload for which events are
# being captured, such as syscall events. Falco integrates with the container
# runtime to enrich its events with container information, including fields like
# `container.image.repository`, `container.image.tag`, ... , `k8s.ns.name`,
# `k8s.pod.name`, `k8s.pod.*` in the Falco output (Falco retrieves Kubernetes
# namespace and pod name directly from the container runtime, see
# https://falco.org/docs/reference/rules/supported-fields/#field-class-container).
# This option allows you to explicitly enable or disable API lookups against container
# runtime sockets for each supported container runtime.
# Access to these sockets enables Falco to retrieve container and Kubernetes fields,
# helping identify workload owners in modern containerized environments.
# Refer to the fields docs:
#
# - [Kubernetes fields](https://falco.org/docs/reference/rules/supported-fields/#field-class-k8s)
# - [Container fields](https://falco.org/docs/reference/rules/supported-fields/#container)
#
# Additionally, Falco can use container events as a data source for alerting (evt.type = container).
#
# For most container engines, you can solely enable or disable them, and Falco will search the
# default (hard-coded) container runtime socket paths, such as `/var/run/docker.sock` for Docker.
#
# Furthermore, Falco exposes container events themselves as a data source for
# alerting. To achieve this integration with the container runtime, Falco
# requires access to the runtime socket. By default, for Kubernetes, Falco
# attempts to connect to the following sockets:
# "/run/containerd/containerd.sock", "/run/crio/crio.sock",
# "/run/k3s/containerd/containerd.sock". If you have a custom path, you can use
# the `--cri` option to specify the correct location.
#
# In some cases, you may encounter empty fields for container metadata. To
# address this, you can explore the `--disable-cri-async` option, which disables
# asynchronous fetching if the fetch operation is not completing quickly enough.
#
# To get more information on these command-line arguments, you can run `falco
# --help` in your terminal to view their current descriptions.
#
# !!! The options mentioned here are not available in the falco.yaml
# configuration file. Instead, they can can be used as a command-line argument
# when running the Falco command.
# However, for Kubernetes settings, you can customize the CRI socket paths:
#
# - `container_engines.cri.sockets`: Pass a list of container runtime sockets.
# - `container_engines.cri.disable_async`: Since API lookups may not always be quick or
# perfect, resulting in empty fields for container metadata, you can use this option option
# to disable asynchronous fetching. Note that missing fields may still occasionally occur.
#
# The equivalent (stable) CLI args are `--cri` or `--disable-cri-async`.
container_engines:
docker:
enabled: true
cri:
enabled: true
sockets: ["/run/containerd/containerd.sock", "/run/crio/crio.sock", "/run/k3s/containerd/containerd.sock"]
disable_async: false
podman:
enabled: true
lxc:
enabled: true
libvirt_lxc:
enabled: true
bpm:
enabled: true

View File

@@ -335,7 +335,7 @@ typedef struct
// the type of the value they return (string, integer...).
// Required: no
// Arguments:
// - evtnum: the number of the event that is bein processed
// - evtnum: the number of the event that is being processed
// - id: the numeric identifier of the field to extract. It corresponds to the
// position of the field in the array returned by get_fields().
// - arg: the field argument, if an argument has been specified for the field,

View File

@@ -2,35 +2,44 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
# Systemd
file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/scripts/systemd)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falco-kmod-inject.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falco-kmod.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falco-bpf.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falco-modern-bpf.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falco-custom.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file("${PROJECT_SOURCE_DIR}/scripts/systemd/falcoctl-artifact-follow.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falco-kmod-inject.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falco-kmod.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falco-bpf.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falco-modern-bpf.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falco-custom.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
configure_file(
"${PROJECT_SOURCE_DIR}/scripts/systemd/falcoctl-artifact-follow.service"
"${PROJECT_BINARY_DIR}/scripts/systemd" COPYONLY
)
# Debian
configure_file(debian/postinst.in debian/postinst COPYONLY)
@@ -44,21 +53,32 @@ if(CMAKE_SYSTEM_NAME MATCHES "Linux")
endif()
# Install Falcoctl config file
if (NOT WIN32 AND NOT APPLE AND NOT EMSCRIPTEN AND NOT MUSL_OPTIMIZED_BUILD)
if(NOT WIN32
AND NOT APPLE
AND NOT EMSCRIPTEN
AND NOT MUSL_OPTIMIZED_BUILD
)
if(NOT DEFINED FALCOCTL_ETC_DIR)
set(FALCOCTL_ETC_DIR "${CMAKE_INSTALL_FULL_SYSCONFDIR}/falcoctl")
endif()
set(FALCOCTL_DRIVER_TYPES_LIST "")
if (BUILD_FALCO_MODERN_BPF)
endif()
set(FALCOCTL_DRIVER_TYPES_LIST "")
if(BUILD_FALCO_MODERN_BPF)
list(APPEND FALCOCTL_DRIVER_TYPES_LIST "modern_ebpf")
endif()
if (BUILD_DRIVER)
if(BUILD_DRIVER)
list(APPEND FALCOCTL_DRIVER_TYPES_LIST "kmod")
endif()
if (BUILD_BPF)
if(BUILD_BPF)
list(APPEND FALCOCTL_DRIVER_TYPES_LIST "ebpf")
endif()
string(REPLACE ";" ", " FALCOCTL_DRIVER_TYPES "${FALCOCTL_DRIVER_TYPES_LIST}")
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/falcoctl/falcoctl.yaml.in ${PROJECT_BINARY_DIR}/scripts/falcoctl/falcoctl.yaml)
install(FILES ${PROJECT_BINARY_DIR}/scripts/falcoctl/falcoctl.yaml DESTINATION "${FALCOCTL_ETC_DIR}" COMPONENT "${FALCO_COMPONENT_NAME}")
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/falcoctl/falcoctl.yaml.in
${PROJECT_BINARY_DIR}/scripts/falcoctl/falcoctl.yaml
)
install(
FILES ${PROJECT_BINARY_DIR}/scripts/falcoctl/falcoctl.yaml
DESTINATION "${FALCOCTL_ETC_DIR}"
COMPONENT "${FALCO_COMPONENT_NAME}"
)
endif()

View File

@@ -24,3 +24,4 @@ StandardOutput=null
[Install]
WantedBy=multi-user.target
Alias=falco.service

View File

@@ -24,3 +24,4 @@ StandardOutput=null
[Install]
WantedBy=multi-user.target
Alias=falco.service

View File

@@ -24,3 +24,4 @@ StandardOutput=null
[Install]
WantedBy=multi-user.target
Alias=falco.service

View File

@@ -0,0 +1,16 @@
#!/bin/bash
#
# This is a git pre-commit-msg hook which automatically add a
# DCO signed-off message if one is missing.
#
MESSAGE_FILE="$1"
GIT_AUTHOR=$(git var GIT_AUTHOR_IDENT)
SIGNOFF_BY=$(echo $GIT_AUTHOR | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p')
# Verify if a DCO signoff message exists.
# Append a DCO signoff message if one doesn't exist.
if ! $(grep -qs "^$SIGNOFF_BY" "$MESSAGE_FILE") ; then
echo -e "\n$SIGNOFF_BY" >> "$MESSAGE_FILE"
fi
exit 0

View File

@@ -2,14 +2,15 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
#
message(STATUS "Falco unit tests build enabled")
@@ -17,67 +18,72 @@ message(STATUS "Falco unit tests build enabled")
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG v1.14.0
)
FetchContent_MakeAvailable(googletest)
# Create a libscap_test_var.h file with some variables used by our tests
# for example the kmod path or the bpf path.
configure_file (
${CMAKE_CURRENT_SOURCE_DIR}/falco_test_var.h.in
${CMAKE_CURRENT_BINARY_DIR}/falco_test_var.h
# Create a libscap_test_var.h file with some variables used by our tests for example the kmod path
# or the bpf path.
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/falco_test_var.h.in ${CMAKE_CURRENT_BINARY_DIR}/falco_test_var.h
)
add_executable(falco_unit_tests
test_falco_engine.cpp
engine/test_add_source.cpp
engine/test_alt_rule_loader.cpp
engine/test_enable_rule.cpp
engine/test_falco_utils.cpp
engine/test_filter_details_resolver.cpp
engine/test_filter_macro_resolver.cpp
engine/test_filter_warning_resolver.cpp
engine/test_plugin_requirements.cpp
engine/test_rule_loader.cpp
engine/test_rulesets.cpp
falco/test_configuration.cpp
falco/test_configuration_rule_selection.cpp
falco/app/actions/test_select_event_sources.cpp
falco/app/actions/test_load_config.cpp
add_executable(
falco_unit_tests
test_falco_engine.cpp
engine/test_add_source.cpp
engine/test_alt_rule_loader.cpp
engine/test_enable_rule.cpp
engine/test_extra_output.cpp
engine/test_falco_utils.cpp
engine/test_filter_details_resolver.cpp
engine/test_filter_macro_resolver.cpp
engine/test_filter_warning_resolver.cpp
engine/test_plugin_requirements.cpp
engine/test_rule_loader.cpp
engine/test_rulesets.cpp
falco/test_configuration.cpp
falco/test_configuration_rule_selection.cpp
falco/test_configuration_config_files.cpp
falco/test_configuration_env_vars.cpp
falco/test_configuration_output_options.cpp
falco/test_configuration_schema.cpp
falco/app/actions/test_select_event_sources.cpp
falco/app/actions/test_load_config.cpp
)
if (CMAKE_SYSTEM_NAME MATCHES "Linux")
target_sources(falco_unit_tests
PRIVATE
falco/test_atomic_signal_handler.cpp
falco/app/actions/test_configure_interesting_sets.cpp
falco/app/actions/test_configure_syscall_buffer_num.cpp
)
if(CMAKE_SYSTEM_NAME MATCHES "Linux")
target_sources(
falco_unit_tests
PRIVATE falco/test_atomic_signal_handler.cpp
falco/app/actions/test_configure_interesting_sets.cpp
falco/app/actions/test_configure_syscall_buffer_num.cpp
)
endif()
target_include_directories(falco_unit_tests
PRIVATE
${CMAKE_SOURCE_DIR}/userspace
${CMAKE_BINARY_DIR}/userspace/falco # we need it to include indirectly `config_falco.h` file
${CMAKE_SOURCE_DIR}/userspace/engine # we need it to include indirectly `falco_common.h` file
${CMAKE_CURRENT_BINARY_DIR} # we need it to include `falco_test_var.h`
target_include_directories(
falco_unit_tests
PRIVATE ${CMAKE_SOURCE_DIR}/userspace
${CMAKE_BINARY_DIR}/userspace/falco # we need it to include indirectly `config_falco.h`
# file
${CMAKE_SOURCE_DIR}/userspace/engine # we need it to include indirectly `falco_common.h`
# file
${CMAKE_CURRENT_BINARY_DIR} # we need it to include `falco_test_var.h`
)
get_target_property(FALCO_APPLICATION_LIBRARIES falco_application LINK_LIBRARIES)
target_link_libraries(falco_unit_tests
falco_application
GTest::gtest
GTest::gtest_main
${FALCO_APPLICATION_LIBRARIES}
target_link_libraries(
falco_unit_tests falco_application GTest::gtest GTest::gtest_main
${FALCO_APPLICATION_LIBRARIES}
)
if (EMSCRIPTEN)
if(EMSCRIPTEN)
target_compile_options(falco_unit_tests PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0")
target_link_options(falco_unit_tests PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0")
target_link_options(falco_unit_tests PRIVATE "-sALLOW_MEMORY_GROWTH=1")
target_link_options(falco_unit_tests PRIVATE "-sALLOW_MEMORY_GROWTH=1")
target_link_options(falco_unit_tests PRIVATE "-sEXPORTED_FUNCTIONS=['_main','_htons','_ntohs']")
endif()

View File

@@ -26,36 +26,30 @@ static std::string syscall_source_name = "syscall";
// for the underlying ruleset. This allows testing of
// ruleset_for_source
namespace
{
class test_ruleset_factory : public evttype_index_ruleset_factory
{
namespace {
class test_ruleset_factory : public evttype_index_ruleset_factory {
public:
explicit test_ruleset_factory(std::shared_ptr<sinsp_filter_factory> factory):
evttype_index_ruleset_factory(factory)
{
evttype_index_ruleset_factory(factory) {
ruleset = evttype_index_ruleset_factory::new_ruleset();
}
virtual ~test_ruleset_factory() = default;
inline std::shared_ptr<filter_ruleset> new_ruleset() override
{
return ruleset;
}
inline std::shared_ptr<filter_ruleset> new_ruleset() override { return ruleset; }
std::shared_ptr<filter_ruleset> ruleset;
};
}; // namespace
}; // namespace
TEST(AddSource, basic)
{
TEST(AddSource, basic) {
falco_engine engine;
sinsp inspector;
sinsp_filter_check_list filterchecks;
auto filter_factory = std::make_shared<sinsp_filter_factory>(&inspector, filterchecks);
auto formatter_factory = std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto formatter_factory =
std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto ruleset_factory = std::make_shared<test_ruleset_factory>(filter_factory);
falco_source syscall_source;
@@ -66,9 +60,9 @@ TEST(AddSource, basic)
syscall_source.formatter_factory = formatter_factory;
size_t source_idx = engine.add_source(syscall_source_name,
filter_factory,
formatter_factory,
ruleset_factory);
filter_factory,
formatter_factory,
ruleset_factory);
ASSERT_TRUE(engine.is_source_valid(syscall_source_name));

View File

@@ -32,42 +32,35 @@ limitations under the License.
#include "rule_loader_collector.h"
#include "rule_loader_compiler.h"
namespace
{
namespace {
struct test_object_info
{
struct test_object_info {
std::string name;
std::string property;
};
struct test_compile_output : public rule_loader::compile_output
{
struct test_compile_output : public rule_loader::compile_output {
test_compile_output() = default;
~test_compile_output() = default;
std::set<std::string> defined_test_properties;
};
class test_compiler : public rule_loader::compiler
{
class test_compiler : public rule_loader::compiler {
public:
test_compiler() = default;
virtual ~test_compiler() = default;
std::unique_ptr<rule_loader::compile_output> new_compile_output() override
{
std::unique_ptr<rule_loader::compile_output> new_compile_output() override {
return std::make_unique<test_compile_output>();
}
void compile(
rule_loader::configuration& cfg,
const rule_loader::collector& col,
rule_loader::compile_output& out) const override;
void compile(rule_loader::configuration& cfg,
const rule_loader::collector& col,
rule_loader::compile_output& out) const override;
};
class test_collector : public rule_loader::collector
{
class test_collector : public rule_loader::collector {
public:
test_collector() = default;
virtual ~test_collector() = default;
@@ -75,32 +68,27 @@ public:
indexed_vector<test_object_info> test_object_infos;
};
class test_reader : public rule_loader::reader
{
class test_reader : public rule_loader::reader {
public:
test_reader() = default;
virtual ~test_reader() = default;
protected:
rule_loader::context create_context(const YAML::Node& item,
const rule_loader::context& parent)
{
const rule_loader::context& parent) {
return rule_loader::context(item,
rule_loader::context::EXTENSION_ITEM,
"test object",
parent);
rule_loader::context::EXTENSION_ITEM,
"test object",
parent);
};
void read_item(rule_loader::configuration& cfg,
rule_loader::collector& collector,
const YAML::Node& item,
const rule_loader::context& parent) override
{
test_collector& test_col =
dynamic_cast<test_collector&>(collector);
rule_loader::collector& collector,
const YAML::Node& item,
const rule_loader::context& parent) override {
test_collector& test_col = dynamic_cast<test_collector&>(collector);
if(item["test_object"].IsDefined())
{
if(item["test_object"].IsDefined()) {
rule_loader::context tmp = create_context(item, parent);
test_object_info obj;
std::string name;
@@ -113,37 +101,29 @@ protected:
obj.property = property;
test_col.test_object_infos.insert(obj, obj.name);
}
else
{
} else {
rule_loader::reader::read_item(cfg, collector, item, parent);
}
};
};
class test_ruleset : public evttype_index_ruleset
{
class test_ruleset : public evttype_index_ruleset {
public:
explicit test_ruleset(std::shared_ptr<sinsp_filter_factory> factory):
evttype_index_ruleset(factory){};
evttype_index_ruleset(factory) {};
virtual ~test_ruleset() = default;
void add_compile_output(
const rule_loader::compile_output& compile_output,
falco_common::priority_type min_priority,
const std::string& source)
{
evttype_index_ruleset::add_compile_output(compile_output,
min_priority,
source);
void add_compile_output(const rule_loader::compile_output& compile_output,
falco_common::priority_type min_priority,
const std::string& source) {
evttype_index_ruleset::add_compile_output(compile_output, min_priority, source);
std::shared_ptr<filter_ruleset> ruleset;
get_engine_state().get_ruleset(source, ruleset);
EXPECT_EQ(this, ruleset.get());
const test_compile_output& test_output =
dynamic_cast<const test_compile_output&>(compile_output);
dynamic_cast<const test_compile_output&>(compile_output);
defined_properties = test_output.defined_test_properties;
};
@@ -151,40 +131,31 @@ public:
std::set<std::string> defined_properties;
};
class test_ruleset_factory : public filter_ruleset_factory
{
class test_ruleset_factory : public filter_ruleset_factory {
public:
explicit test_ruleset_factory(std::shared_ptr<sinsp_filter_factory> factory):
m_filter_factory(factory)
{
}
m_filter_factory(factory) {}
virtual ~test_ruleset_factory() = default;
inline std::shared_ptr<filter_ruleset> new_ruleset() override
{
inline std::shared_ptr<filter_ruleset> new_ruleset() override {
return std::make_shared<test_ruleset>(m_filter_factory);
}
std::shared_ptr<sinsp_filter_factory> m_filter_factory;
};
}; // namespace
}; // namespace
void test_compiler::compile(
rule_loader::configuration& cfg,
const rule_loader::collector& col,
rule_loader::compile_output& out) const
{
void test_compiler::compile(rule_loader::configuration& cfg,
const rule_loader::collector& col,
rule_loader::compile_output& out) const {
rule_loader::compiler::compile(cfg, col, out);
const test_collector& test_col =
dynamic_cast<const test_collector&>(col);
const test_collector& test_col = dynamic_cast<const test_collector&>(col);
test_compile_output& test_output =
dynamic_cast<test_compile_output&>(out);
test_compile_output& test_output = dynamic_cast<test_compile_output&>(out);
for(auto& test_obj : test_col.test_object_infos)
{
for(auto& test_obj : test_col.test_object_infos) {
test_output.defined_test_properties.insert(test_obj.property);
}
}
@@ -230,12 +201,13 @@ static std::string content = R"END(
static std::string syscall_source_name = "syscall";
static std::shared_ptr<rule_loader::configuration> create_configuration(sinsp& inspector,
sinsp_filter_check_list& filterchecks,
indexed_vector<falco_source>& sources)
{
static std::shared_ptr<rule_loader::configuration> create_configuration(
sinsp& inspector,
sinsp_filter_check_list& filterchecks,
indexed_vector<falco_source>& sources) {
auto filter_factory = std::make_shared<sinsp_filter_factory>(&inspector, filterchecks);
auto formatter_factory = std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto formatter_factory =
std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto ruleset_factory = std::make_shared<evttype_index_ruleset_factory>(filter_factory);
falco_source syscall_source;
@@ -247,17 +219,15 @@ static std::shared_ptr<rule_loader::configuration> create_configuration(sinsp& i
sources.insert(syscall_source, syscall_source_name);
return std::make_shared<rule_loader::configuration>(content,
sources,
"test configuration");
return std::make_shared<rule_loader::configuration>(content, sources, "test configuration");
}
static void load_rules(sinsp& inspector,
sinsp_filter_check_list& filterchecks,
std::unique_ptr<rule_loader::compile_output>& compile_output,
indexed_vector<falco_source>& sources)
{
std::shared_ptr<rule_loader::configuration> cfg = create_configuration(inspector, filterchecks, sources);
sinsp_filter_check_list& filterchecks,
std::unique_ptr<rule_loader::compile_output>& compile_output,
indexed_vector<falco_source>& sources) {
std::shared_ptr<rule_loader::configuration> cfg =
create_configuration(inspector, filterchecks, sources);
rule_loader::reader reader;
rule_loader::collector collector;
@@ -270,8 +240,7 @@ static void load_rules(sinsp& inspector,
compiler.compile(*cfg, collector, *compile_output);
}
TEST(engine_loader_alt_loader, load_rules)
{
TEST(engine_loader_alt_loader, load_rules) {
sinsp inspector;
sinsp_filter_check_list filterchecks;
std::unique_ptr<rule_loader::compile_output> compile_output;
@@ -292,8 +261,7 @@ TEST(engine_loader_alt_loader, load_rules)
EXPECT_TRUE(compile_output->rules.at("test debug rule") != nullptr);
}
TEST(engine_loader_alt_loader, pass_compile_output_to_ruleset)
{
TEST(engine_loader_alt_loader, pass_compile_output_to_ruleset) {
sinsp inspector;
sinsp_filter_check_list filterchecks;
std::unique_ptr<rule_loader::compile_output> compile_output;
@@ -304,8 +272,8 @@ TEST(engine_loader_alt_loader, pass_compile_output_to_ruleset)
std::shared_ptr<filter_ruleset> ruleset = sources.at(syscall_source_name)->ruleset;
ruleset->add_compile_output(*compile_output,
falco_common::PRIORITY_INFORMATIONAL,
syscall_source_name);
falco_common::PRIORITY_INFORMATIONAL,
syscall_source_name);
// Enable all rules for a ruleset id. Because the compile
// output contained one rule with priority >= INFO, that rule
@@ -316,14 +284,14 @@ TEST(engine_loader_alt_loader, pass_compile_output_to_ruleset)
EXPECT_EQ(ruleset->enabled_count(ruleset_id), 1);
}
TEST(engine_loader_alt_loader, falco_engine_alternate_loader)
{
TEST(engine_loader_alt_loader, falco_engine_alternate_loader) {
falco_engine engine;
sinsp inspector;
sinsp_filter_check_list filterchecks;
auto filter_factory = std::make_shared<sinsp_filter_factory>(&inspector, filterchecks);
auto formatter_factory = std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto formatter_factory =
std::make_shared<sinsp_evt_formatter_factory>(&inspector, filterchecks);
auto ruleset_factory = std::make_shared<test_ruleset_factory>(filter_factory);
engine.add_source(syscall_source_name, filter_factory, formatter_factory, ruleset_factory);
@@ -345,7 +313,8 @@ TEST(engine_loader_alt_loader, falco_engine_alternate_loader)
EXPECT_EQ(collector->test_object_infos.size(), 2);
std::shared_ptr<filter_ruleset> ruleset = engine.ruleset_for_source(syscall_source_name);
std::set<std::string>& defined_properties = std::dynamic_pointer_cast<test_ruleset>(ruleset)->defined_properties;
std::set<std::string>& defined_properties =
std::dynamic_pointer_cast<test_ruleset>(ruleset)->defined_properties;
EXPECT_TRUE(defined_properties.find("my-value") != defined_properties.end());
EXPECT_TRUE(defined_properties.find("other-value") != defined_properties.end());

View File

@@ -72,8 +72,6 @@ static std::string multi_rule = R"END(
tags: [exec]
)END";
// This must be kept in line with the (private) falco_engine::s_default_ruleset
static const std::string default_ruleset = "falco-default-ruleset";
@@ -82,8 +80,7 @@ static const std::string ruleset_2 = "ruleset-2";
static const std::string ruleset_3 = "ruleset-3";
static const std::string ruleset_4 = "ruleset-4";
TEST_F(test_falco_engine, enable_rule_name)
{
TEST_F(test_falco_engine, enable_rule_name) {
load_rules(single_rule, "single_rule.yaml");
// No rules should be enabled yet for any custom rulesets
@@ -119,8 +116,7 @@ TEST_F(test_falco_engine, enable_rule_name)
EXPECT_EQ(2, m_engine->num_rules_for_ruleset(ruleset_3));
}
TEST_F(test_falco_engine, enable_rule_tags)
{
TEST_F(test_falco_engine, enable_rule_tags) {
std::set<std::string> process_tags = {"process"};
load_rules(single_rule, "single_rule.yaml");
@@ -147,8 +143,7 @@ TEST_F(test_falco_engine, enable_rule_tags)
EXPECT_EQ(0, m_engine->num_rules_for_ruleset(ruleset_2));
}
TEST_F(test_falco_engine, enable_disabled_rule_by_tag)
{
TEST_F(test_falco_engine, enable_disabled_rule_by_tag) {
std::set<std::string> exec_process_tags = {"exec process"};
load_rules(single_rule, "single_rule.yaml");
@@ -163,8 +158,7 @@ TEST_F(test_falco_engine, enable_disabled_rule_by_tag)
EXPECT_EQ(2, m_engine->num_rules_for_ruleset(default_ruleset));
}
TEST_F(test_falco_engine, enable_rule_id)
{
TEST_F(test_falco_engine, enable_rule_id) {
uint16_t ruleset_1_id;
uint16_t ruleset_2_id;
uint16_t ruleset_3_id;
@@ -204,8 +198,7 @@ TEST_F(test_falco_engine, enable_rule_id)
EXPECT_EQ(2, m_engine->num_rules_for_ruleset(ruleset_3));
}
TEST_F(test_falco_engine, enable_rule_name_exact)
{
TEST_F(test_falco_engine, enable_rule_name_exact) {
load_rules(single_rule, "single_rule.yaml");
EXPECT_EQ(1, m_engine->num_rules_for_ruleset(default_ruleset));
@@ -247,8 +240,7 @@ TEST_F(test_falco_engine, enable_rule_name_exact)
EXPECT_EQ(2, m_engine->num_rules_for_ruleset(ruleset_4));
}
TEST_F(test_falco_engine, enable_rule_name_wildcard)
{
TEST_F(test_falco_engine, enable_rule_name_wildcard) {
load_rules(multi_rule, "multi_rule.yaml");
EXPECT_EQ(1, m_engine->num_rules_for_ruleset(default_ruleset));
@@ -283,4 +275,3 @@ TEST_F(test_falco_engine, enable_rule_name_wildcard)
EXPECT_EQ(1, m_engine->num_rules_for_ruleset(ruleset_3));
EXPECT_EQ(3, m_engine->num_rules_for_ruleset(ruleset_4));
}

View File

@@ -0,0 +1,154 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2024 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include "../test_falco_engine.h"
TEST_F(test_falco_engine, extra_format_all) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: user=%user.name command=%proc.cmdline file=%fd.name
priority: INFO
)END";
m_engine->add_extra_output_format("evt.type=%evt.type", "", {}, "", false);
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
EXPECT_EQ(get_compiled_rule_output("legit_rule"),
"user=%user.name command=%proc.cmdline file=%fd.name evt.type=%evt.type");
}
TEST_F(test_falco_engine, extra_format_by_rule) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: out 1
priority: INFO
- rule: another_rule
desc: legit rule description
condition: evt.type=open
output: out 2
priority: INFO
)END";
m_engine->add_extra_output_format("evt.type=%evt.type", "", {}, "legit_rule", false);
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
EXPECT_EQ(get_compiled_rule_output("legit_rule"), "out 1 evt.type=%evt.type");
EXPECT_EQ(get_compiled_rule_output("another_rule"), "out 2");
}
TEST_F(test_falco_engine, extra_format_by_tag_rule) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: out 1
priority: INFO
tags: [tag1]
- rule: another_rule
desc: legit rule description
condition: evt.type=open
output: out 2
priority: INFO
tags: [tag1]
- rule: a_third_rule
desc: legit rule description
condition: evt.type=open
output: out 3
priority: INFO
tags: [tag1, tag2]
)END";
m_engine->add_extra_output_format("extra 1", "", {"tag1"}, "", false);
m_engine->add_extra_output_format("extra 2", "", {}, "another_rule", false);
m_engine->add_extra_output_format("extra 3", "", {"tag1", "tag2"}, "", false);
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
EXPECT_EQ(get_compiled_rule_output("legit_rule"), "out 1 extra 1");
EXPECT_EQ(get_compiled_rule_output("another_rule"), "out 2 extra 1 extra 2");
EXPECT_EQ(get_compiled_rule_output("a_third_rule"), "out 3 extra 1 extra 3");
}
TEST_F(test_falco_engine, extra_format_replace_container_info) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: out 1 (%container.info)
priority: INFO
tags: [tag1]
- rule: another_rule
desc: legit rule description
condition: evt.type=open
output: out 2
priority: INFO
tags: [tag1]
)END";
m_engine->add_extra_output_format("extra 1", "", {}, "", true);
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
EXPECT_EQ(get_compiled_rule_output("legit_rule"), "out 1 (extra 1)");
EXPECT_EQ(get_compiled_rule_output("another_rule"), "out 2 extra 1");
}
TEST_F(test_falco_engine, extra_format_do_not_replace_container_info) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: out 1 (%container.info)
priority: INFO
tags: [tag1]
)END";
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
auto output = get_compiled_rule_output("legit_rule");
EXPECT_TRUE(output.find("%container.info") == output.npos);
}
TEST_F(test_falco_engine, extra_fields_all) {
std::string rules_content = R"END(
- rule: legit_rule
desc: legit rule description
condition: evt.type=open
output: user=%user.name command=%proc.cmdline file=%fd.name
priority: INFO
)END";
std::unordered_map<std::string, std::string> extra_formatted_fields = {
{"my_field", "hello %evt.num"}};
for(auto const& f : extra_formatted_fields) {
m_engine->add_extra_output_formatted_field(f.first, f.second, "", {}, "");
}
ASSERT_TRUE(load_rules(rules_content, "legit_rules.yaml")) << m_load_result_string;
EXPECT_EQ(get_compiled_rule_formatted_fields("legit_rule"), extra_formatted_fields);
}

View File

@@ -18,8 +18,7 @@ limitations under the License.
#include <gtest/gtest.h>
#include <engine/falco_utils.h>
TEST(FalcoUtils, is_unix_scheme)
{
TEST(FalcoUtils, is_unix_scheme) {
/* Wrong prefix */
ASSERT_EQ(falco::utils::network::is_unix_scheme("something:///run/falco/falco.sock"), false);
@@ -38,15 +37,14 @@ TEST(FalcoUtils, is_unix_scheme)
ASSERT_EQ(falco::utils::network::is_unix_scheme(url_char), true);
}
TEST(FalcoUtils, parse_prometheus_interval)
{
TEST(FalcoUtils, parse_prometheus_interval) {
/* Test matrix around correct time conversions. */
ASSERT_EQ(falco::utils::parse_prometheus_interval("1ms"), 1UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1s"), 1000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1m"), 60000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1h"), 3600000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1d"), 86400000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1w"), 604800000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1w"), 604800000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1y"), (unsigned long)31536000000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("300ms"), 300UL);
@@ -57,8 +55,11 @@ TEST(FalcoUtils, parse_prometheus_interval)
ASSERT_EQ(falco::utils::parse_prometheus_interval("60m"), 3600000UL);
/* Test matrix for concatenated time interval examples. */
ASSERT_EQ(falco::utils::parse_prometheus_interval("1h3m2s1ms"), 3600000UL + 3 * 60000UL + 2 * 1000UL + 1UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1y1w1d1h1m1s1ms"),(unsigned long) 31536000000UL + 604800000UL + 86400000UL + 3600000UL + 60000UL + 1000UL + 1UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1h3m2s1ms"),
3600000UL + 3 * 60000UL + 2 * 1000UL + 1UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("1y1w1d1h1m1s1ms"),
(unsigned long)31536000000UL + 604800000UL + 86400000UL + 3600000UL + 60000UL +
1000UL + 1UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("2h5m"), 2 * 3600000UL + 5 * 60000UL);
ASSERT_EQ(falco::utils::parse_prometheus_interval("2h 5m"), 2 * 3600000UL + 5 * 60000UL);
@@ -73,16 +74,16 @@ TEST(FalcoUtils, parse_prometheus_interval)
ASSERT_EQ(falco::utils::parse_prometheus_interval("200"), 0UL);
}
TEST(FalcoUtils, sanitize_metric_name)
{
ASSERT_EQ(falco::utils::sanitize_metric_name("Testing rule 2 (CVE-2244)"), "Testing_rule_2_CVE_2244");
ASSERT_EQ(falco::utils::sanitize_metric_name("Testing rule__:2)"), "Testing_rule_:2");
ASSERT_EQ(falco::utils::sanitize_metric_name("This@is_a$test rule123"), "This_is_a_test_rule123");
ASSERT_EQ(falco::utils::sanitize_metric_name("RULEwith:special#characters"), "RULEwith:special_characters");
TEST(FalcoUtils, sanitize_rule_name) {
ASSERT_EQ(falco::utils::sanitize_rule_name("Testing rule 2 (CVE-2244)"),
"Testing_rule_2_CVE_2244");
ASSERT_EQ(falco::utils::sanitize_rule_name("Testing rule__:2)"), "Testing_rule_:2");
ASSERT_EQ(falco::utils::sanitize_rule_name("This@is_a$test rule123"), "This_is_a_test_rule123");
ASSERT_EQ(falco::utils::sanitize_rule_name("RULEwith:special#characters"),
"RULEwith:special_characters");
}
TEST(FalcoUtils, matches_wildcard)
{
TEST(FalcoUtils, matches_wildcard) {
ASSERT_TRUE(falco::utils::matches_wildcard("*", "anything"));
ASSERT_TRUE(falco::utils::matches_wildcard("**", "anything"));
ASSERT_TRUE(falco::utils::matches_wildcard("*", ""));

View File

@@ -18,33 +18,33 @@ limitations under the License.
#include <gtest/gtest.h>
#include <engine/filter_details_resolver.h>
TEST(DetailsResolver, resolve_ast) {
std::string cond =
"(spawned_process or evt.type = open) and (proc.name icontains cat or proc.name in "
"(known_procs, ps))";
auto ast = libsinsp::filter::parser(cond).parse();
filter_details details;
details.known_macros.insert("spawned_process");
details.known_lists.insert("known_procs");
filter_details_resolver resolver;
resolver.run(ast.get(), details);
TEST(DetailsResolver, resolve_ast)
{
std::string cond = "(spawned_process or evt.type = open) and (proc.name icontains cat or proc.name in (known_procs, ps))";
auto ast = libsinsp::filter::parser(cond).parse();
filter_details details;
details.known_macros.insert("spawned_process");
details.known_lists.insert("known_procs");
filter_details_resolver resolver;
resolver.run(ast.get(), details);
// Assert fields
ASSERT_EQ(details.fields.size(), 2);
ASSERT_NE(details.fields.find("evt.type"), details.fields.end());
ASSERT_NE(details.fields.find("proc.name"), details.fields.end());
// Assert fields
ASSERT_EQ(details.fields.size(), 2);
ASSERT_NE(details.fields.find("evt.type"), details.fields.end());
ASSERT_NE(details.fields.find("proc.name"), details.fields.end());
// Assert macros
ASSERT_EQ(details.macros.size(), 1);
ASSERT_NE(details.macros.find("spawned_process"), details.macros.end());
// Assert macros
ASSERT_EQ(details.macros.size(), 1);
ASSERT_NE(details.macros.find("spawned_process"), details.macros.end());
// Assert operators
ASSERT_EQ(details.operators.size(), 3);
ASSERT_NE(details.operators.find("="), details.operators.end());
ASSERT_NE(details.operators.find("icontains"), details.operators.end());
ASSERT_NE(details.operators.find("in"), details.operators.end());
// Assert operators
ASSERT_EQ(details.operators.size(), 3);
ASSERT_NE(details.operators.find("="), details.operators.end());
ASSERT_NE(details.operators.find("icontains"), details.operators.end());
ASSERT_NE(details.operators.find("in"), details.operators.end());
// Assert lists
ASSERT_EQ(details.lists.size(), 1);
ASSERT_NE(details.lists.find("known_procs"), details.lists.end());
// Assert lists
ASSERT_EQ(details.lists.size(), 1);
ASSERT_NE(details.lists.find("known_procs"), details.lists.end());
}

View File

@@ -21,33 +21,37 @@ limitations under the License.
namespace filter_ast = libsinsp::filter::ast;
static std::vector<filter_macro_resolver::value_info>::const_iterator find_value(
const std::vector<filter_macro_resolver::value_info>& values,
const std::string& ref)
{
const std::vector<filter_macro_resolver::value_info>& values,
const std::string& ref) {
return std::find_if(
values.begin(),
values.end(),
[&ref](const filter_macro_resolver::value_info& v)
{ return v.first == ref; });
values.begin(),
values.end(),
[&ref](const filter_macro_resolver::value_info& v) { return v.first == ref; });
}
#define MACRO_NAME "test_macro"
#define MACRO_A_NAME "test_macro_1"
#define MACRO_B_NAME "test_macro_2"
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST)
{
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST) {
filter_ast::pos_info macro_pos(12, 85, 27);
std::shared_ptr<filter_ast::expr> macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""), "exists");
std::shared_ptr<filter_ast::expr> macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""),
"exists");
std::vector<std::unique_ptr<filter_ast::expr>> filter_and;
filter_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""), "exists"));
filter_and.push_back(filter_ast::not_expr::create(filter_ast::identifier_expr::create(MACRO_NAME, macro_pos)));
filter_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""),
"exists"));
filter_and.push_back(filter_ast::not_expr::create(
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos)));
std::shared_ptr<filter_ast::expr> filter = filter_ast::and_expr::create(filter_and);
std::vector<std::unique_ptr<filter_ast::expr>> expected_and;
expected_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""), "exists"));
expected_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""),
"exists"));
expected_and.push_back(filter_ast::not_expr::create(clone(macro.get())));
std::shared_ptr<filter_ast::expr> expected = filter_ast::and_expr::create(expected_and);
@@ -69,13 +73,15 @@ TEST(MacroResolver, should_resolve_macros_on_a_filter_AST)
ASSERT_TRUE(filter->is_equal(expected.get()));
}
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_single_node)
{
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_single_node) {
filter_ast::pos_info macro_pos(12, 85, 27);
std::shared_ptr<filter_ast::expr> macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""), "exists");
std::shared_ptr<filter_ast::expr> macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""),
"exists");
std::shared_ptr<filter_ast::expr> filter = filter_ast::identifier_expr::create(MACRO_NAME, macro_pos);
std::shared_ptr<filter_ast::expr> filter =
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos);
filter_macro_resolver resolver;
resolver.set_macro(MACRO_NAME, macro);
@@ -99,13 +105,16 @@ TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_single_node)
ASSERT_TRUE(filter->is_equal(macro.get()));
}
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_multiple_macros)
{
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_multiple_macros) {
filter_ast::pos_info a_macro_pos(11, 75, 43);
filter_ast::pos_info b_macro_pos(91, 21, 9);
std::shared_ptr<filter_ast::expr> a_macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""), "exists");
std::shared_ptr<filter_ast::expr> b_macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("another.field", ""), "exists");
std::shared_ptr<filter_ast::expr> a_macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""),
"exists");
std::shared_ptr<filter_ast::expr> b_macro = filter_ast::unary_check_expr::create(
filter_ast::field_expr::create("another.field", ""),
"exists");
std::vector<std::unique_ptr<filter_ast::expr>> filter_or;
filter_or.push_back(filter_ast::identifier_expr::create(MACRO_A_NAME, a_macro_pos));
@@ -143,24 +152,31 @@ TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_multiple_macros)
ASSERT_TRUE(filter->is_equal(expected_filter.get()));
}
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_nested_macros)
{
TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_nested_macros) {
filter_ast::pos_info a_macro_pos(47, 1, 76);
filter_ast::pos_info b_macro_pos(111, 65, 2);
std::vector<std::unique_ptr<filter_ast::expr>> a_macro_and;
a_macro_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""), "exists"));
a_macro_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""),
"exists"));
a_macro_and.push_back(filter_ast::identifier_expr::create(MACRO_B_NAME, b_macro_pos));
std::shared_ptr<filter_ast::expr> a_macro = filter_ast::and_expr::create(a_macro_and);
std::shared_ptr<filter_ast::expr> b_macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("another.field", ""), "exists");
std::shared_ptr<filter_ast::expr> b_macro = filter_ast::unary_check_expr::create(
filter_ast::field_expr::create("another.field", ""),
"exists");
std::shared_ptr<filter_ast::expr> filter = filter_ast::identifier_expr::create(MACRO_A_NAME, a_macro_pos);
std::shared_ptr<filter_ast::expr> filter =
filter_ast::identifier_expr::create(MACRO_A_NAME, a_macro_pos);
std::vector<std::unique_ptr<filter_ast::expr>> expected_and;
expected_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""), "exists"));
expected_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("another.field", ""), "exists"));
expected_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""),
"exists"));
expected_and.push_back(filter_ast::unary_check_expr::create(
filter_ast::field_expr::create("another.field", ""),
"exists"));
std::shared_ptr<filter_ast::expr> expected_filter = filter_ast::and_expr::create(expected_and);
filter_macro_resolver resolver;
@@ -191,13 +207,15 @@ TEST(MacroResolver, should_resolve_macros_on_a_filter_AST_nested_macros)
ASSERT_TRUE(filter->is_equal(expected_filter.get()));
}
TEST(MacroResolver, should_find_unknown_macros)
{
TEST(MacroResolver, should_find_unknown_macros) {
filter_ast::pos_info macro_pos(9, 4, 2);
std::vector<std::unique_ptr<filter_ast::expr>> filter_and;
filter_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""), "exists"));
filter_and.push_back(filter_ast::not_expr::create(filter_ast::identifier_expr::create(MACRO_NAME, macro_pos)));
filter_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("evt.name", ""),
"exists"));
filter_and.push_back(filter_ast::not_expr::create(
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos)));
std::shared_ptr<filter_ast::expr> filter = filter_ast::and_expr::create(filter_and);
filter_macro_resolver resolver;
@@ -208,17 +226,19 @@ TEST(MacroResolver, should_find_unknown_macros)
ASSERT_TRUE(resolver.get_resolved_macros().empty());
}
TEST(MacroResolver, should_find_unknown_nested_macros)
{
TEST(MacroResolver, should_find_unknown_nested_macros) {
filter_ast::pos_info a_macro_pos(32, 84, 9);
filter_ast::pos_info b_macro_pos(1, 0, 5);
std::vector<std::unique_ptr<filter_ast::expr>> a_macro_and;
a_macro_and.push_back(filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""), "exists"));
a_macro_and.push_back(
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("one.field", ""),
"exists"));
a_macro_and.push_back(filter_ast::identifier_expr::create(MACRO_B_NAME, b_macro_pos));
std::shared_ptr<filter_ast::expr> a_macro = filter_ast::and_expr::create(a_macro_and);
std::shared_ptr<filter_ast::expr> filter = filter_ast::identifier_expr::create(MACRO_A_NAME, a_macro_pos);
std::shared_ptr<filter_ast::expr> filter =
filter_ast::identifier_expr::create(MACRO_A_NAME, a_macro_pos);
auto expected_filter = clone(a_macro.get());
filter_macro_resolver resolver;
@@ -234,14 +254,17 @@ TEST(MacroResolver, should_find_unknown_nested_macros)
ASSERT_TRUE(filter->is_equal(expected_filter.get()));
}
TEST(MacroResolver, should_undefine_macro)
{
TEST(MacroResolver, should_undefine_macro) {
filter_ast::pos_info macro_pos_1(12, 9, 3);
filter_ast::pos_info macro_pos_2(9, 6, 3);
std::shared_ptr<filter_ast::expr> macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""), "exists");
std::shared_ptr<filter_ast::expr> a_filter = filter_ast::identifier_expr::create(MACRO_NAME, macro_pos_1);
std::shared_ptr<filter_ast::expr> b_filter = filter_ast::identifier_expr::create(MACRO_NAME, macro_pos_2);
std::shared_ptr<filter_ast::expr> macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""),
"exists");
std::shared_ptr<filter_ast::expr> a_filter =
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos_1);
std::shared_ptr<filter_ast::expr> b_filter =
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos_2);
filter_macro_resolver resolver;
resolver.set_macro(MACRO_NAME, macro);
@@ -261,11 +284,13 @@ TEST(MacroResolver, should_undefine_macro)
}
/* checks that the macro AST is cloned and not shared across resolved filters */
TEST(MacroResolver, should_clone_macro_AST)
{
TEST(MacroResolver, should_clone_macro_AST) {
filter_ast::pos_info macro_pos(5, 2, 8888);
std::shared_ptr<filter_ast::unary_check_expr> macro = filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""), "exists");
std::shared_ptr<filter_ast::expr> filter = filter_ast::identifier_expr::create(MACRO_NAME, macro_pos);
std::shared_ptr<filter_ast::unary_check_expr> macro =
filter_ast::unary_check_expr::create(filter_ast::field_expr::create("test.field", ""),
"exists");
std::shared_ptr<filter_ast::expr> filter =
filter_ast::identifier_expr::create(MACRO_NAME, macro_pos);
filter_macro_resolver resolver;
resolver.set_macro(MACRO_NAME, macro);

View File

@@ -18,16 +18,14 @@ limitations under the License.
#include <gtest/gtest.h>
#include <engine/filter_warning_resolver.h>
static bool warns(const std::string& condition)
{
static bool warns(const std::string& condition) {
std::set<falco::load_result::warning_code> w;
auto ast = libsinsp::filter::parser(condition).parse();
filter_warning_resolver().run(ast.get(), w);
return !w.empty();
}
TEST(WarningResolver, warnings_in_filtering_conditions)
{
TEST(WarningResolver, warnings_in_filtering_conditions) {
ASSERT_FALSE(warns("ka.field exists"));
ASSERT_FALSE(warns("some.field = <NA>"));
ASSERT_TRUE(warns("jevt.field = <NA>"));

View File

@@ -20,22 +20,19 @@ limitations under the License.
#include <gtest/gtest.h>
static bool check_requirements(std::string& err,
const std::vector<falco_engine::plugin_version_requirement>& plugins,
const std::string& ruleset_content)
{
const std::vector<falco_engine::plugin_version_requirement>& plugins,
const std::string& ruleset_content) {
falco_engine e;
falco::load_result::rules_contents_t c = {{"test", ruleset_content}};
auto res = e.load_rules(c.begin()->second, c.begin()->first);
if(!res->successful())
{
if(!res->successful()) {
return false;
}
return e.check_plugin_requirements(plugins, err);
}
TEST(PluginRequirements, check_plugin_requirements_success)
{
TEST(PluginRequirements, check_plugin_requirements_success) {
std::string error;
/* No requirement */
@@ -47,7 +44,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: k8saudit
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin newer version */
ASSERT_TRUE(check_requirements(error, {{"k8saudit", "0.2.0"}}, R"(
@@ -55,7 +52,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: k8saudit
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins */
ASSERT_TRUE(check_requirements(error, {{"k8saudit", "0.1.0"}, {"json", "0.3.0"}}, R"(
@@ -65,7 +62,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: json
version: 0.3.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin multiple versions */
ASSERT_TRUE(check_requirements(error, {{"k8saudit", "0.2.0"}}, R"(
@@ -76,7 +73,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: k8saudit
version: 0.2.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin with alternatives */
ASSERT_TRUE(check_requirements(error, {{"k8saudit-other", "0.5.0"}}, R"(
@@ -87,7 +84,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: k8saudit-other
version: 0.4.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins with alternatives */
ASSERT_TRUE(check_requirements(error, {{"k8saudit-other", "0.5.0"}, {"json2", "0.5.0"}}, R"(
@@ -103,7 +100,7 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: json2
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins with alternatives with multiple versions */
ASSERT_TRUE(check_requirements(error, {{"k8saudit-other", "0.7.0"}, {"json2", "0.5.0"}}, R"(
@@ -125,11 +122,10 @@ TEST(PluginRequirements, check_plugin_requirements_success)
- name: k8saudit-other
version: 0.7.0
)")) << error
<< std::endl;
<< std::endl;
}
TEST(PluginRequirements, check_plugin_requirements_reject)
{
TEST(PluginRequirements, check_plugin_requirements_reject) {
std::string error;
/* No plugin loaded */
@@ -138,7 +134,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin wrong name */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.1.0"}}, R"(
@@ -146,7 +142,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit2
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin wrong version */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.1.0"}}, R"(
@@ -154,7 +150,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit
version: 0.2.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.1.0"}}, R"(
@@ -164,7 +160,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: json
version: 0.3.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin multiple versions */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.1.0"}}, R"(
@@ -175,7 +171,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit
version: 0.2.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin with alternatives */
ASSERT_FALSE(check_requirements(error, {{"k8saudit2", "0.5.0"}}, R"(
@@ -186,7 +182,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit-other
version: 0.4.0
)")) << error
<< std::endl;
<< std::endl;
/* Single plugin with overlapping alternatives */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.5.0"}}, R"(
@@ -197,7 +193,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit
version: 0.4.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins with alternatives */
ASSERT_FALSE(check_requirements(error, {{"k8saudit-other", "0.5.0"}, {"json3", "0.5.0"}}, R"(
@@ -213,7 +209,7 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: json2
version: 0.1.0
)")) << error
<< std::endl;
<< std::endl;
/* Multiple plugins with alternatives with multiple versions */
ASSERT_FALSE(check_requirements(error, {{"k8saudit", "0.7.0"}, {"json2", "0.5.0"}}, R"(
@@ -235,5 +231,5 @@ TEST(PluginRequirements, check_plugin_requirements_reject)
- name: k8saudit-other
version: 0.7.0
)")) << error
<< std::endl;
<< std::endl;
}

File diff suppressed because it is too large Load Diff

View File

@@ -23,32 +23,28 @@ limitations under the License.
#define RULESET_2 2
/* Helpers methods */
static std::shared_ptr<sinsp_filter_factory> create_factory(sinsp* inspector, filter_check_list& list)
{
static std::shared_ptr<sinsp_filter_factory> create_factory(sinsp* inspector,
filter_check_list& list) {
return std::make_shared<sinsp_filter_factory>(inspector, list);
}
static std::shared_ptr<filter_ruleset> create_ruleset(std::shared_ptr<sinsp_filter_factory> f)
{
static std::shared_ptr<filter_ruleset> create_ruleset(std::shared_ptr<sinsp_filter_factory> f) {
return std::make_shared<evttype_index_ruleset>(f);
}
static std::shared_ptr<libsinsp::filter::ast::expr> create_ast(std::shared_ptr<sinsp_filter_factory> f)
{
static std::shared_ptr<libsinsp::filter::ast::expr> create_ast(
std::shared_ptr<sinsp_filter_factory> f) {
libsinsp::filter::parser parser("evt.type=open");
return parser.parse();
}
static std::shared_ptr<sinsp_filter> create_filter(
std::shared_ptr<sinsp_filter_factory> f,
libsinsp::filter::ast::expr* ast)
{
static std::shared_ptr<sinsp_filter> create_filter(std::shared_ptr<sinsp_filter_factory> f,
libsinsp::filter::ast::expr* ast) {
sinsp_filter_compiler compiler(f, ast);
return std::shared_ptr<sinsp_filter>(compiler.compile());
}
TEST(Ruleset, enable_disable_rules_using_names)
{
TEST(Ruleset, enable_disable_rules_using_names) {
sinsp inspector;
sinsp_filter_check_list filterlist;
@@ -140,8 +136,7 @@ TEST(Ruleset, enable_disable_rules_using_names)
ASSERT_EQ(r->enabled_count(RULESET_2), 0);
}
TEST(Ruleset, enable_disable_rules_using_tags)
{
TEST(Ruleset, enable_disable_rules_using_tags) {
sinsp inspector;
sinsp_filter_check_list filterlist;

View File

@@ -19,5 +19,17 @@ limitations under the License.
#include <falco/app/state.h>
#include <falco/app/actions/actions.h>
#define EXPECT_ACTION_OK(r) { auto result = r; EXPECT_TRUE(result.success); EXPECT_TRUE(result.proceed); EXPECT_EQ(result.errstr, ""); }
#define EXPECT_ACTION_FAIL(r) { auto result = r; EXPECT_FALSE(result.success); EXPECT_FALSE(result.proceed); EXPECT_NE(result.errstr, ""); }
#define EXPECT_ACTION_OK(r) \
{ \
auto result = r; \
EXPECT_TRUE(result.success); \
EXPECT_TRUE(result.proceed); \
EXPECT_EQ(result.errstr, ""); \
}
#define EXPECT_ACTION_FAIL(r) \
{ \
auto result = r; \
EXPECT_FALSE(result.success); \
EXPECT_FALSE(result.proceed); \
EXPECT_NE(result.errstr, ""); \
}

View File

@@ -23,23 +23,21 @@ limitations under the License.
#include <falco/app/app.h>
#include "app_action_helpers.h"
#define ASSERT_NAMES_EQ(a, b) { \
EXPECT_EQ(_order(a).size(), _order(b).size()); \
ASSERT_EQ(_order(a), _order(b)); \
}
#define ASSERT_NAMES_EQ(a, b) \
{ \
EXPECT_EQ(_order(a).size(), _order(b).size()); \
ASSERT_EQ(_order(a), _order(b)); \
}
#define ASSERT_NAMES_CONTAIN(a, b) { \
ASSERT_NAMES_EQ(unordered_set_intersection(a, b), b); \
}
#define ASSERT_NAMES_CONTAIN(a, b) \
{ ASSERT_NAMES_EQ(unordered_set_intersection(a, b), b); }
#define ASSERT_NAMES_NOCONTAIN(a, b) { \
ASSERT_NAMES_EQ(unordered_set_intersection(a, b), strset_t({})); \
}
#define ASSERT_NAMES_NOCONTAIN(a, b) \
{ ASSERT_NAMES_EQ(unordered_set_intersection(a, b), strset_t({})); }
using strset_t = std::unordered_set<std::string>;
static std::set<std::string> _order(const strset_t& s)
{
static std::set<std::string> _order(const strset_t& s) {
return std::set<std::string>(s.begin(), s.end());
}
@@ -48,38 +46,31 @@ static std::string s_sample_ruleset = "sample-ruleset";
static std::string s_sample_source = falco_common::syscall_source;
static strset_t s_sample_filters = {
"evt.type=connect or evt.type=accept or evt.type=accept4 or evt.type=umount2",
"evt.type in (open, ptrace, mmap, execve, read, container)",
"evt.type in (open, execve, mprotect) and not evt.type=mprotect"};
"evt.type=connect or evt.type=accept or evt.type=accept4 or evt.type=umount2",
"evt.type in (open, ptrace, mmap, execve, read, container)",
"evt.type in (open, execve, mprotect) and not evt.type=mprotect"};
static strset_t s_sample_generic_filters = {
"evt.type=syncfs or evt.type=fanotify_init"};
static strset_t s_sample_generic_filters = {"evt.type=syncfs or evt.type=fanotify_init"};
static strset_t s_sample_nonsyscall_filters = {
"evt.type in (procexit, switch, pluginevent, container)"};
"evt.type in (procexit, switch, pluginevent, container)"};
static std::string ruleset_from_filters(const strset_t& filters)
{
static std::string ruleset_from_filters(const strset_t& filters) {
std::string dummy_rules;
falco::load_result::rules_contents_t content = {{"dummy_rules.yaml", dummy_rules}};
int n_rules = 0;
for (const auto& f : filters)
{
for(const auto& f : filters) {
n_rules++;
dummy_rules +=
"- rule: Dummy Rule " + std::to_string(n_rules) + "\n"
+ " output: Dummy Output " + std::to_string(n_rules) + "\n"
+ " condition: " + f + "\n"
+ " desc: Dummy Desc " + std::to_string(n_rules) + "\n"
+ " priority: CRITICAL\n\n";
dummy_rules += "- rule: Dummy Rule " + std::to_string(n_rules) + "\n" +
" output: Dummy Output " + std::to_string(n_rules) + "\n" +
" condition: " + f + "\n" + " desc: Dummy Desc " +
std::to_string(n_rules) + "\n" + " priority: CRITICAL\n\n";
}
return dummy_rules;
}
TEST_F(test_falco_engine, engine_codes_syscalls_set)
{
TEST_F(test_falco_engine, engine_codes_syscalls_set) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
auto enabled_count = m_engine->num_rules_for_ruleset(s_sample_ruleset);
@@ -88,20 +79,37 @@ TEST_F(test_falco_engine, engine_codes_syscalls_set)
// test if event code names were extracted from each rule in test ruleset.
auto rules_event_set = m_engine->event_codes_for_ruleset(s_sample_source);
auto rules_event_names = libsinsp::events::event_set_to_names(rules_event_set);
ASSERT_NAMES_EQ(rules_event_names, strset_t({
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read", "container", "asyncevent"}));
ASSERT_NAMES_EQ(rules_event_names,
strset_t({"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read",
"container",
"asyncevent"}));
// test if sc code names were extracted from each rule in test ruleset.
// note, this is not supposed to contain "container", as that's an event
// not mapped through the ppm_sc_code enumerative.
auto rules_sc_set = m_engine->sc_codes_for_ruleset(s_sample_source);
auto rules_sc_names = libsinsp::events::sc_set_to_event_names(rules_sc_set);
ASSERT_NAMES_EQ(rules_sc_names, strset_t({
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read"}));
ASSERT_NAMES_EQ(rules_sc_names,
strset_t({"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read"}));
}
TEST_F(test_falco_engine, preconditions_postconditions)
{
TEST_F(test_falco_engine, preconditions_postconditions) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s1;
@@ -131,8 +139,7 @@ TEST_F(test_falco_engine, preconditions_postconditions)
ASSERT_EQ(prev_selection_size, s1.selected_sc_set.size());
}
TEST_F(test_falco_engine, engine_codes_nonsyscalls_set)
{
TEST_F(test_falco_engine, engine_codes_nonsyscalls_set) {
auto filters = s_sample_filters;
filters.insert(s_sample_generic_filters.begin(), s_sample_generic_filters.end());
filters.insert(s_sample_nonsyscall_filters.begin(), s_sample_nonsyscall_filters.end());
@@ -149,22 +156,44 @@ TEST_F(test_falco_engine, engine_codes_nonsyscalls_set)
// PPME_GENERIC_E will cause all names of generic events to be added!
// This is a good example of information loss from ppm_event_code <-> ppm_sc_code.
auto generic_names = libsinsp::events::event_set_to_names({ppm_event_code::PPME_GENERIC_E});
auto expected_names = strset_t({
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read", "container", // ruleset
"procexit", "switch", "pluginevent", "asyncevent"}); // from non-syscall event filters
auto expected_names = strset_t({"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read",
"container", // ruleset
"procexit",
"switch",
"pluginevent",
"asyncevent"}); // from non-syscall event filters
expected_names.insert(generic_names.begin(), generic_names.end());
ASSERT_NAMES_EQ(rules_event_names, expected_names);
auto rules_sc_set = m_engine->sc_codes_for_ruleset(s_sample_source);
auto rules_sc_names = libsinsp::events::sc_set_to_event_names(rules_sc_set);
ASSERT_NAMES_EQ(rules_sc_names, strset_t({
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read",
"procexit", "switch", "syncfs", "fanotify_init", // from generic event filters
}));
ASSERT_NAMES_EQ(rules_sc_names,
strset_t({
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read",
"procexit",
"switch",
"syncfs",
"fanotify_init", // from generic event filters
}));
}
TEST_F(test_falco_engine, selection_not_allevents)
{
TEST_F(test_falco_engine, selection_not_allevents) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s2;
@@ -184,10 +213,22 @@ TEST_F(test_falco_engine, selection_not_allevents)
ASSERT_GT(s2.selected_sc_set.size(), 1);
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s2.selected_sc_set);
auto expected_sc_names = strset_t({
// note: we expect the "read" syscall to have been erased
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", // from ruleset
"clone", "clone3", "fork", "vfork", // from sinsp state set (spawned_process)
"socket", "bind", "close" // from sinsp state set (network, files)
// note: we expect the "read" syscall to have been erased
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve", // from ruleset
"clone",
"clone3",
"fork",
"vfork", // from sinsp state set (spawned_process)
"socket",
"bind",
"close" // from sinsp state set (network, files)
});
ASSERT_NAMES_CONTAIN(selected_sc_names, expected_sc_names);
@@ -199,8 +240,7 @@ TEST_F(test_falco_engine, selection_not_allevents)
// check that final selected set is exactly sinsp state + ruleset
auto rule_set = s2.engine->sc_codes_for_ruleset(s_sample_source, s_sample_ruleset);
auto state_set = libsinsp::events::sinsp_state_sc_set();
for (const auto &erased : ignored_set)
{
for(const auto& erased : ignored_set) {
rule_set.remove(erased);
state_set.remove(erased);
}
@@ -210,8 +250,7 @@ TEST_F(test_falco_engine, selection_not_allevents)
ASSERT_EQ(s2.selected_sc_set, union_set);
}
TEST_F(test_falco_engine, selection_allevents)
{
TEST_F(test_falco_engine, selection_allevents) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s3;
@@ -229,10 +268,23 @@ TEST_F(test_falco_engine, selection_allevents)
ASSERT_GT(s3.selected_sc_set.size(), 1);
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s3.selected_sc_set);
auto expected_sc_names = strset_t({
// note: we expect the "read" syscall to not be erased
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read", // from ruleset
"clone", "clone3", "fork", "vfork", // from sinsp state set (spawned_process)
"socket", "bind", "close" // from sinsp state set (network, files)
// note: we expect the "read" syscall to not be erased
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read", // from ruleset
"clone",
"clone3",
"fork",
"vfork", // from sinsp state set (spawned_process)
"socket",
"bind",
"close" // from sinsp state set (network, files)
});
ASSERT_NAMES_CONTAIN(selected_sc_names, expected_sc_names);
@@ -245,8 +297,7 @@ TEST_F(test_falco_engine, selection_allevents)
ASSERT_EQ(s3.selected_sc_set, union_set);
}
TEST_F(test_falco_engine, selection_generic_evts)
{
TEST_F(test_falco_engine, selection_generic_evts) {
falco::app::state s4;
// run app action with fake engine and without the `-A` option
s4.options.all_events = false;
@@ -262,14 +313,28 @@ TEST_F(test_falco_engine, selection_generic_evts)
ASSERT_GT(s4.selected_sc_set.size(), 1);
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s4.selected_sc_set);
auto expected_sc_names = strset_t({
// note: we expect the "read" syscall to not be erased
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", // from ruleset
"syncfs", "fanotify_init", // from ruleset (generic events)
"clone", "clone3", "fork", "vfork", // from sinsp state set (spawned_process)
"socket", "bind", "close" // from sinsp state set (network, files)
// note: we expect the "read" syscall to not be erased
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve", // from ruleset
"syncfs",
"fanotify_init", // from ruleset (generic events)
"clone",
"clone3",
"fork",
"vfork", // from sinsp state set (spawned_process)
"socket",
"bind",
"close" // from sinsp state set (network, files)
});
ASSERT_NAMES_CONTAIN(selected_sc_names, expected_sc_names);
auto unexpected_sc_names = libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
auto unexpected_sc_names =
libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
ASSERT_NAMES_NOCONTAIN(selected_sc_names, unexpected_sc_names);
}
@@ -278,8 +343,7 @@ TEST_F(test_falco_engine, selection_generic_evts)
// (either default or custom positive set)
// - events in the custom negative set are removed from the selected set
// - if `-A` is not set, events from the IO set are removed from the selected set
TEST_F(test_falco_engine, selection_custom_base_set)
{
TEST_F(test_falco_engine, selection_custom_base_set) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s5;
@@ -295,17 +359,24 @@ TEST_F(test_falco_engine, selection_custom_base_set)
ASSERT_TRUE(result.success);
ASSERT_EQ(result.errstr, "");
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s5.selected_sc_set);
auto expected_sc_names = strset_t({
// note: `syncfs` has been added due to the custom base set, and `accept`
// has been remove due to the negative base set.
// note: `read` is not ignored due to the "-A" option being set.
// note: `accept` is not included even though it is matched by the rules,
// which means that the custom negation base set has precedence over the
// final selection set as a whole
// note(jasondellaluce): "accept4" should be added, however old versions
// of the ACCEPT4 event are actually named "accept" in the event table
"connect", "umount2", "open", "ptrace", "mmap", "execve", "read", "syncfs", "procexit"
});
auto expected_sc_names =
strset_t({// note: `syncfs` has been added due to the custom base set, and `accept`
// has been remove due to the negative base set.
// note: `read` is not ignored due to the "-A" option being set.
// note: `accept` is not included even though it is matched by the rules,
// which means that the custom negation base set has precedence over the
// final selection set as a whole
// note(jasondellaluce): "accept4" should be added, however old versions
// of the ACCEPT4 event are actually named "accept" in the event table
"connect",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read",
"syncfs",
"procexit"});
ASSERT_NAMES_EQ(selected_sc_names, expected_sc_names);
// non-empty custom base set (both positive and negative with collision)
@@ -325,10 +396,18 @@ TEST_F(test_falco_engine, selection_custom_base_set)
ASSERT_TRUE(result.success);
ASSERT_EQ(result.errstr, "");
selected_sc_names = libsinsp::events::sc_set_to_event_names(s5.selected_sc_set);
expected_sc_names = strset_t({
// note: accept is not negated anymore
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "read", "syncfs", "procexit"
});
expected_sc_names = strset_t({// note: accept is not negated anymore
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"read",
"syncfs",
"procexit"});
ASSERT_NAMES_EQ(selected_sc_names, expected_sc_names);
// non-empty custom base set (only negative)
@@ -338,8 +417,8 @@ TEST_F(test_falco_engine, selection_custom_base_set)
ASSERT_EQ(result.errstr, "");
selected_sc_names = libsinsp::events::sc_set_to_event_names(s5.selected_sc_set);
expected_sc_names = unordered_set_union(
libsinsp::events::sc_set_to_event_names(default_base_set),
strset_t({ "connect", "umount2", "open", "ptrace", "mmap", "execve", "read"}));
libsinsp::events::sc_set_to_event_names(default_base_set),
strset_t({"connect", "umount2", "open", "ptrace", "mmap", "execve", "read"}));
expected_sc_names.erase("accept");
// note(jasondellaluce): "accept4" should be included, however old versions
// of the ACCEPT4 event are actually named "accept" in the event table
@@ -353,18 +432,24 @@ TEST_F(test_falco_engine, selection_custom_base_set)
ASSERT_TRUE(result.success);
ASSERT_EQ(result.errstr, "");
selected_sc_names = libsinsp::events::sc_set_to_event_names(s5.selected_sc_set);
expected_sc_names = strset_t({
// note: read is both part of the custom base set and the rules set,
// but we expect the unset -A option to take precedence
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "procexit"
});
expected_sc_names = strset_t({// note: read is both part of the custom base set and the rules
// set, but we expect the unset -A option to take precedence
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"procexit"});
ASSERT_NAMES_EQ(selected_sc_names, expected_sc_names);
auto unexpected_sc_names = libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
auto unexpected_sc_names =
libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
ASSERT_NAMES_NOCONTAIN(selected_sc_names, unexpected_sc_names);
}
TEST_F(test_falco_engine, selection_custom_base_set_repair)
{
TEST_F(test_falco_engine, selection_custom_base_set_repair) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s6;
@@ -383,18 +468,29 @@ TEST_F(test_falco_engine, selection_custom_base_set_repair)
ASSERT_TRUE(result.success);
ASSERT_EQ(result.errstr, "");
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s6.selected_sc_set);
auto expected_sc_names = strset_t({
// note: expecting syscalls from mock rules and `sinsp_repair_state_sc_set` enforced syscalls
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "procexit", \
"bind", "socket", "clone3", "close", "setuid"
});
auto expected_sc_names = strset_t({// note: expecting syscalls from mock rules and
// `sinsp_repair_state_sc_set` enforced syscalls
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"procexit",
"bind",
"socket",
"clone3",
"close",
"setuid"});
ASSERT_NAMES_CONTAIN(selected_sc_names, expected_sc_names);
auto unexpected_sc_names = libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
auto unexpected_sc_names =
libsinsp::events::sc_set_to_event_names(falco::app::ignored_sc_set());
ASSERT_NAMES_NOCONTAIN(selected_sc_names, unexpected_sc_names);
}
TEST_F(test_falco_engine, selection_empty_custom_base_set_repair)
{
TEST_F(test_falco_engine, selection_empty_custom_base_set_repair) {
load_rules(ruleset_from_filters(s_sample_filters), "dummy_ruleset.yaml");
falco::app::state s7;
@@ -410,23 +506,34 @@ TEST_F(test_falco_engine, selection_empty_custom_base_set_repair)
ASSERT_TRUE(result.success);
ASSERT_EQ(result.errstr, "");
auto selected_sc_names = libsinsp::events::sc_set_to_event_names(s7.selected_sc_set);
auto expected_sc_names = strset_t({
// note: expecting syscalls from mock rules and `sinsp_repair_state_sc_set` enforced syscalls
"connect", "accept", "accept4", "umount2", "open", "ptrace", "mmap", "execve", "procexit", \
"bind", "socket", "clone3", "close", "setuid"
});
auto expected_sc_names = strset_t({// note: expecting syscalls from mock rules and
// `sinsp_repair_state_sc_set` enforced syscalls
"connect",
"accept",
"accept4",
"umount2",
"open",
"ptrace",
"mmap",
"execve",
"procexit",
"bind",
"socket",
"clone3",
"close",
"setuid"});
ASSERT_NAMES_CONTAIN(selected_sc_names, expected_sc_names);
auto s7_state_set = libsinsp::events::sinsp_repair_state_sc_set(s7_rules_set);
ASSERT_EQ(s7.selected_sc_set, s7_state_set);
ASSERT_EQ(s7.selected_sc_set.size(), s7_state_set.size());
}
TEST(ConfigureInterestingSets, ignored_set_expected_size)
{
TEST(ConfigureInterestingSets, ignored_set_expected_size) {
// unit test fence to make sure we don't have unexpected regressions
// in the ignored set, to be updated in the future
ASSERT_EQ(falco::app::ignored_sc_set().size(), 14);
// we don't expect to ignore any syscall in the default base set
ASSERT_EQ(falco::app::ignored_sc_set().intersect(libsinsp::events::sinsp_state_sc_set()).size(), 0);
ASSERT_EQ(falco::app::ignored_sc_set().intersect(libsinsp::events::sinsp_state_sc_set()).size(),
0);
}

View File

@@ -17,13 +17,11 @@ limitations under the License.
#include "app_action_helpers.h"
TEST(ActionConfigureSyscallBufferNum, variable_number_of_CPUs)
{
TEST(ActionConfigureSyscallBufferNum, variable_number_of_CPUs) {
auto action = falco::app::actions::configure_syscall_buffer_num;
ssize_t online_cpus = sysconf(_SC_NPROCESSORS_ONLN);
if(online_cpus <= 0)
{
if(online_cpus <= 0) {
FAIL() << "cannot get the number of online CPUs from the system\n";
}

View File

@@ -19,8 +19,7 @@ limitations under the License.
#include "falco_test_var.h"
#ifndef __EMSCRIPTEN__
TEST(ActionLoadConfig, check_kmod_engine_config)
{
TEST(ActionLoadConfig, check_kmod_engine_config) {
falco::app::state s = {};
s.options.conf_filename = TEST_ENGINE_KMOD_CONFIG;
EXPECT_ACTION_OK(falco::app::actions::load_config(s));
@@ -47,8 +46,7 @@ TEST(ActionLoadConfig, check_kmod_engine_config)
EXPECT_TRUE(s.config->m_gvisor.m_root.empty());
}
TEST(ActionLoadConfig, check_modern_engine_config)
{
TEST(ActionLoadConfig, check_modern_engine_config) {
falco::app::state s = {};
s.options.conf_filename = TEST_ENGINE_MODERN_CONFIG;
EXPECT_ACTION_OK(falco::app::actions::load_config(s));

View File

@@ -17,85 +17,82 @@ limitations under the License.
#include "app_action_helpers.h"
TEST(ActionSelectEventSources, pre_post_conditions)
{
auto action = falco::app::actions::select_event_sources;
TEST(ActionSelectEventSources, pre_post_conditions) {
auto action = falco::app::actions::select_event_sources;
// requires sources to be already loaded
{
falco::app::state s;
EXPECT_ACTION_FAIL(action(s));
}
// requires sources to be already loaded
{
falco::app::state s;
EXPECT_ACTION_FAIL(action(s));
}
// ignore source selection in capture mode
{
falco::app::state s;
s.config->m_engine_mode = engine_kind_t::REPLAY;
EXPECT_TRUE(s.is_capture_mode());
EXPECT_ACTION_OK(action(s));
}
// ignore source selection in capture mode
{
falco::app::state s;
s.config->m_engine_mode = engine_kind_t::REPLAY;
EXPECT_TRUE(s.is_capture_mode());
EXPECT_ACTION_OK(action(s));
}
// enable all loaded sources by default, even with multiple calls
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.loaded_sources.size(), s.enabled_sources.size());
for (const auto& v : s.loaded_sources)
{
ASSERT_TRUE(s.enabled_sources.find(v) != s.enabled_sources.end());
}
s.loaded_sources.push_back("another_source");
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.loaded_sources.size(), s.enabled_sources.size());
for (const auto& v : s.loaded_sources)
{
ASSERT_TRUE(s.enabled_sources.find(v) != s.enabled_sources.end());
}
}
// enable all loaded sources by default, even with multiple calls
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.loaded_sources.size(), s.enabled_sources.size());
for(const auto& v : s.loaded_sources) {
ASSERT_TRUE(s.enabled_sources.find(v) != s.enabled_sources.end());
}
s.loaded_sources.push_back("another_source");
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.loaded_sources.size(), s.enabled_sources.size());
for(const auto& v : s.loaded_sources) {
ASSERT_TRUE(s.enabled_sources.find(v) != s.enabled_sources.end());
}
}
// enable only selected sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.enable_sources = {"syscall"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.enabled_sources.size(), 1);
EXPECT_EQ(*s.enabled_sources.begin(), "syscall");
}
// enable only selected sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.enable_sources = {"syscall"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.enabled_sources.size(), 1);
EXPECT_EQ(*s.enabled_sources.begin(), "syscall");
}
// enable all loaded sources expect the disabled ones
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"syscall"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.enabled_sources.size(), 1);
EXPECT_EQ(*s.enabled_sources.begin(), "some_source");
}
// enable all loaded sources expect the disabled ones
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"syscall"};
EXPECT_ACTION_OK(action(s));
EXPECT_EQ(s.enabled_sources.size(), 1);
EXPECT_EQ(*s.enabled_sources.begin(), "some_source");
}
// enable unknown sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.enable_sources = {"some_other_source"};
EXPECT_ACTION_FAIL(action(s));
}
// enable unknown sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.enable_sources = {"some_other_source"};
EXPECT_ACTION_FAIL(action(s));
}
// disable unknown sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"some_other_source"};
EXPECT_ACTION_FAIL(action(s));
}
// disable unknown sources
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"some_other_source"};
EXPECT_ACTION_FAIL(action(s));
}
// mix enable and disable sources options
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"syscall"};
s.options.enable_sources = {"syscall"};
EXPECT_ACTION_FAIL(action(s));
}
// mix enable and disable sources options
{
falco::app::state s;
s.loaded_sources = {"syscall", "some_source"};
s.options.disable_sources = {"syscall"};
s.options.enable_sources = {"syscall"};
EXPECT_ACTION_FAIL(action(s));
}
}

View File

@@ -16,7 +16,7 @@ limitations under the License.
*/
#include <falco/atomic_signal_handler.h>
#include <falco/logger.h>
#include <engine/logger.h>
#include <gtest/gtest.h>
@@ -25,13 +25,11 @@ limitations under the License.
#include <memory>
#include <vector>
TEST(AtomicSignalHandler, lock_free_implementation)
{
TEST(AtomicSignalHandler, lock_free_implementation) {
ASSERT_TRUE(falco::atomic_signal_handler().is_lock_free());
}
TEST(AtomicSignalHandler, handle_once_wait_consistency)
{
TEST(AtomicSignalHandler, handle_once_wait_consistency) {
constexpr const auto thread_num = 10;
constexpr const std::chrono::seconds thread_wait_sec{2};
constexpr const std::chrono::seconds handler_wait_sec{1};
@@ -40,33 +38,27 @@ TEST(AtomicSignalHandler, handle_once_wait_consistency)
falco::atomic_signal_handler handler;
// launch a bunch of threads all syncing on the same handler
struct task_result_t
{
struct task_result_t {
bool handled;
std::chrono::seconds duration_secs;
};
std::vector<std::future<task_result_t>> futures;
for (int i = 0; i < thread_num; i++)
{
futures.emplace_back(std::async(std::launch::async,
[&handler, thread_wait_sec]() {
auto start = std::chrono::high_resolution_clock::now();
task_result_t res;
res.handled = false;
while (!handler.handled())
{
if (handler.triggered())
{
res.handled = handler.handle([thread_wait_sec]() {
std::this_thread::sleep_for(thread_wait_sec);
});
}
for(int i = 0; i < thread_num; i++) {
futures.emplace_back(std::async(std::launch::async, [&handler, thread_wait_sec]() {
auto start = std::chrono::high_resolution_clock::now();
task_result_t res;
res.handled = false;
while(!handler.handled()) {
if(handler.triggered()) {
res.handled = handler.handle(
[thread_wait_sec]() { std::this_thread::sleep_for(thread_wait_sec); });
}
auto diff = std::chrono::high_resolution_clock::now() - start;
res.duration_secs = std::chrono::duration_cast<std::chrono::seconds>(diff);
return res;
}));
}
auto diff = std::chrono::high_resolution_clock::now() - start;
res.duration_secs = std::chrono::duration_cast<std::chrono::seconds>(diff);
return res;
}));
}
// wait a bit, then trigger the signal handler from the main thread
@@ -74,12 +66,10 @@ TEST(AtomicSignalHandler, handle_once_wait_consistency)
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_for(handler_wait_sec);
handler.trigger();
for (int i = 0; i < thread_num; i++)
{
for(int i = 0; i < thread_num; i++) {
// wait for all threads to finish and get the results from the futures
auto res = futures[i].get();
if (res.handled)
{
if(res.handled) {
total_handled++;
}
ASSERT_GE(res.duration_secs, thread_wait_sec);
@@ -94,9 +84,8 @@ TEST(AtomicSignalHandler, handle_once_wait_consistency)
ASSERT_EQ(total_handled, 1);
}
TEST(AtomicSignalHandler, handle_and_reset)
{
auto do_nothing = []{};
TEST(AtomicSignalHandler, handle_and_reset) {
auto do_nothing = [] {};
falco::atomic_signal_handler handler;
ASSERT_FALSE(handler.triggered());

View File

@@ -18,27 +18,20 @@ limitations under the License.
#include <gtest/gtest.h>
#include <falco/configuration.h>
#ifdef _WIN32
#define SET_ENV_VAR(env_var_name, env_var_value) _putenv_s(env_var_name, env_var_value)
#else
#define SET_ENV_VAR(env_var_name, env_var_value) setenv(env_var_name, env_var_value, 1)
#endif
static std::string sample_yaml =
"base_value:\n"
" id: 1\n"
" name: 'sample_name'\n"
" subvalue:\n"
" subvalue2:\n"
" boolean: true\n"
"base_value_2:\n"
" sample_list:\n"
" - elem1\n"
" - elem2\n"
" - elem3\n";
"base_value:\n"
" id: 1\n"
" name: 'sample_name'\n"
" subvalue:\n"
" subvalue2:\n"
" boolean: true\n"
"base_value_2:\n"
" sample_list:\n"
" - elem1\n"
" - elem2\n"
" - elem3\n";
TEST(Configuration, configuration_exceptions)
{
TEST(Configuration, configuration_exceptions) {
yaml_helper conf;
/* Broken YAML */
@@ -49,8 +42,7 @@ TEST(Configuration, configuration_exceptions)
EXPECT_NO_THROW(conf.load_from_string(sample_yaml));
}
TEST(Configuration, configuration_reload)
{
TEST(Configuration, configuration_reload) {
yaml_helper conf;
/* Clear and reload config */
@@ -62,8 +54,7 @@ TEST(Configuration, configuration_reload)
ASSERT_TRUE(conf.is_defined("base_value"));
}
TEST(Configuration, read_yaml_fields)
{
TEST(Configuration, read_yaml_fields) {
yaml_helper conf;
conf.load_from_string(sample_yaml);
@@ -78,9 +69,12 @@ TEST(Configuration, read_yaml_fields)
ASSERT_EQ(conf.get_scalar<bool>("base_value.subvalue.subvalue2.boolean", false), true);
/* get list field elements */
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[0]", "none").c_str(), "elem1");
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[1]", "none").c_str(), "elem2");
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[2]", "none").c_str(), "elem3");
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[0]", "none").c_str(),
"elem1");
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[1]", "none").c_str(),
"elem2");
ASSERT_STREQ(conf.get_scalar<std::string>("base_value_2.sample_list[2]", "none").c_str(),
"elem3");
/* get sequence */
std::vector<std::string> seq;
@@ -91,751 +85,100 @@ TEST(Configuration, read_yaml_fields)
ASSERT_STREQ(seq[2].c_str(), "elem3");
}
TEST(Configuration, modify_yaml_fields)
{
TEST(Configuration, modify_yaml_fields) {
std::string key = "base_value.subvalue.subvalue2.boolean";
yaml_helper conf;
/* Get original value */
conf.load_from_string(sample_yaml);
/* Get original value */
conf.load_from_string(sample_yaml);
ASSERT_EQ(conf.get_scalar<bool>(key, false), true);
/* Modify the original value */
conf.set_scalar<bool>(key, false);
/* Modify the original value */
conf.set_scalar<bool>(key, false);
ASSERT_EQ(conf.get_scalar<bool>(key, true), false);
/* Modify it again */
conf.set_scalar<bool>(key, true);
/* Modify it again */
conf.set_scalar<bool>(key, true);
ASSERT_EQ(conf.get_scalar<bool>(key, false), true);
}
TEST(Configuration, configuration_config_files_secondary_fail)
{
/* Test that a secondary config file is not able to include anything, triggering an exception. */
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
yaml_helper::configs_key + ":\n"
" - conf_4.yaml\n"
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
TEST(Configuration, configuration_webserver_ip) {
falco_configuration falco_config;
ASSERT_ANY_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}
TEST(Configuration, configuration_config_files_ok)
{
/* Test that every included config file was correctly parsed */
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo3: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
const std::string conf_yaml_4 =
"base_value_4:\n"
" id: 4\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
outfile.open("conf_4.yaml");
outfile << conf_yaml_4;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(loaded_conf_files.size(), 3);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.config.is_defined("foo3"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo3", ""), "bar3");
ASSERT_TRUE(falco_config.config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_3.id", 0), 3);
ASSERT_TRUE(falco_config.config.is_defined("base_value_3.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value_3.name", ""), "foo3");
ASSERT_FALSE(falco_config.config.is_defined("base_value_4.id")); // conf_4 is not included
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
std::filesystem::remove("conf_4.yaml");
}
TEST(Configuration, configuration_config_files_relative_main)
{
/*
* Test that relative path are treated as relative to cwd and not to main config folder,
* and that absolute includes are ok too.
*/
const auto temp_main = std::filesystem::temp_directory_path() / "main.yaml";
// So, conf_2 will be looked up in the same folder as main config file,
// while conf_3, since is absolute, will be looked up in the absolute path (and found!).
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
" - conf_2.yaml\n"
" - " +
std::filesystem::current_path().string() + "/conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo3: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
std::ofstream outfile(temp_main.string());
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file(temp_main.string(), loaded_conf_files, cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(loaded_conf_files.size(), 3);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_3.id", 0), 3);
std::filesystem::remove(temp_main.string());
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
}
TEST(Configuration, configuration_config_files_override)
{
/* Test that included config files are able to override configs from main file */
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"base_value:\n"
" id: 3\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(loaded_conf_files.size(), 3);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 3); // overridden!
ASSERT_FALSE(falco_config.config.is_defined("base_value.name")); // no more present since entire `base_value` block was overridden
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_FALSE(falco_config.config.is_defined("base_value_3.id")); // not defined
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
}
TEST(Configuration, configuration_config_files_unexistent)
{
/* Test that including an unexistent file just skips it */
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
" - conf_5.yaml\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main
ASSERT_EQ(loaded_conf_files.size(), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_scalar_config_files)
{
/* Test that a single file can be included as a scalar (thanks to get_sequence_from_node magic) */
const std::string main_conf_yaml =
yaml_helper::configs_key + ": conf_2.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main + conf_2
ASSERT_EQ(loaded_conf_files.size(), 2);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}
TEST(Configuration, configuration_config_files_empty_config_files)
{
/* Test that empty includes list is accepted */
const std::string main_conf_yaml =
yaml_helper::configs_key + ":\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main
ASSERT_EQ(loaded_conf_files.size(), 1);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_self)
{
/* Test that main config file cannot include itself */
const std::string main_conf_yaml =
yaml_helper::configs_key + ": main.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_ANY_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_directory)
{
/*
* Test that when main config file includes a config directory,
* the config directory is parsed in lexicographic order,
* and only regular files are parsed.
*/
// Main config includes whole temp directory
const std::string main_conf_yaml =
yaml_helper::configs_key + ": " + std::filesystem::temp_directory_path().string() + "/test\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo2: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
const std::string conf_yaml_4 =
"foo4: bar4\n";
std::filesystem::create_directory(std::filesystem::temp_directory_path() / "test");
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open(std::filesystem::temp_directory_path()/"test/conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open(std::filesystem::temp_directory_path()/"test/conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
// Create a directory and create a config inside it. We will later check that it was not parsed
std::filesystem::create_directory(std::filesystem::temp_directory_path() / "test" / "foo");
outfile.open(std::filesystem::temp_directory_path()/"test/foo/conf_4.yaml");
outfile << conf_yaml_4;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main + conf_2 + conf_3.
// test/foo is not parsed.
ASSERT_EQ(loaded_conf_files.size(), 3);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_3.id", 0), 3);
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar3");
ASSERT_FALSE(falco_config.config.is_defined("foo4"));
std::filesystem::remove("main");
std::filesystem::remove_all(std::filesystem::temp_directory_path()/"test");
}
TEST(Configuration, configuration_config_files_cmdline)
{
/* Test that we support including configs files from cmdline option */
const std::string main_conf_yaml =
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
// Pass "config_files=..." cmdline option
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back((yaml_helper::configs_key+"=conf_2.yaml"));
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_file("main.yaml", loaded_conf_files, cmdline_config_options));
// main + conf_2
ASSERT_EQ(loaded_conf_files.size(), 2);
ASSERT_TRUE(falco_config.config.is_defined("foo"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.config.is_defined("foo2"));
ASSERT_EQ(falco_config.config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.config.get_scalar<int>("base_value_2.id", 0), 2);
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}
TEST(Configuration, configuration_environment_variables)
{
// Set an environment variable for testing purposes
std::string env_var_value = "envVarValue";
std::string env_var_name = "ENV_VAR";
SET_ENV_VAR(env_var_name.c_str(), env_var_value.c_str());
std::string embedded_env_var_value = "${ENV_VAR}";
std::string embedded_env_var_name = "ENV_VAR_EMBEDDED";
SET_ENV_VAR(embedded_env_var_name.c_str(), embedded_env_var_value.c_str());
std::string bool_env_var_value = "true";
std::string bool_env_var_name = "ENV_VAR_BOOL";
SET_ENV_VAR(bool_env_var_name.c_str(), bool_env_var_value.c_str());
std::string int_env_var_value = "12";
std::string int_env_var_name = "ENV_VAR_INT";
SET_ENV_VAR(int_env_var_name.c_str(), int_env_var_value.c_str());
std::string empty_env_var_value = "";
std::string empty_env_var_name = "ENV_VAR_EMPTY";
SET_ENV_VAR(empty_env_var_name.c_str(), empty_env_var_value.c_str());
std::string default_value = "default";
std::string env_var_sample_yaml =
"base_value:\n"
" id: $ENV_VAR\n"
" name: '${ENV_VAR}'\n"
" string: my_string\n"
" invalid: $${ENV_VAR}\n"
" invalid_env: $$ENV_VAR\n"
" invalid_double_env: $${ENV_VAR}$${ENV_VAR}\n"
" invalid_embedded_env: $${${ENV_VAR}}\n"
" invalid_valid_env: $${ENV_VAR}${ENV_VAR}\n"
" escaped: \"${ENV_VAR}\"\n"
" subvalue:\n"
" subvalue2:\n"
" boolean: ${UNSED_XX_X_X_VAR}\n"
"base_value_2:\n"
" sample_list:\n"
" - ${ENV_VAR}\n"
" - ' ${ENV_VAR}'\n"
" - '${ENV_VAR} '\n"
" - $UNSED_XX_X_X_VAR\n"
"paths:\n"
" - ${ENV_VAR}/foo\n"
" - $ENV_VAR/foo\n"
" - /foo/${ENV_VAR}/\n"
" - /${ENV_VAR}/${ENV_VAR}${ENV_VAR}/foo\n"
" - ${ENV_VAR_EMBEDDED}/foo\n"
"is_test: ${ENV_VAR_BOOL}\n"
"num_test: ${ENV_VAR_INT}\n"
"empty_test: ${ENV_VAR_EMPTY}\n"
"plugins:\n"
" - name: k8saudit\n"
" library_path: /foo/${ENV_VAR}/libk8saudit.so\n"
" open_params: ${ENV_VAR_INT}\n";
yaml_helper conf;
conf.load_from_string(env_var_sample_yaml);
/* Check if the base values are defined */
ASSERT_TRUE(conf.is_defined("base_value"));
ASSERT_TRUE(conf.is_defined("base_value_2"));
ASSERT_TRUE(conf.is_defined("paths"));
ASSERT_FALSE(conf.is_defined("unknown_base_value"));
/* Test fetching of a regular string without any environment variable */
auto base_value_string = conf.get_scalar<std::string>("base_value.string", default_value);
ASSERT_EQ(base_value_string, "my_string");
/* Test fetching of escaped environment variable format. Should return the string as-is after stripping the leading `$` */
auto base_value_invalid = conf.get_scalar<std::string>("base_value.invalid", default_value);
ASSERT_EQ(base_value_invalid, "${ENV_VAR}");
/* Test fetching of invalid escaped environment variable format. Should return the string as-is */
auto base_value_invalid_env = conf.get_scalar<std::string>("base_value.invalid_env", default_value);
ASSERT_EQ(base_value_invalid_env, "$$ENV_VAR");
/* Test fetching of 2 escaped environment variables side by side. Should return the string as-is after stripping the leading `$` */
auto base_value_double_invalid = conf.get_scalar<std::string>("base_value.invalid_double_env", default_value);
ASSERT_EQ(base_value_double_invalid, "${ENV_VAR}${ENV_VAR}");
/*
* Test fetching of escaped environment variable format with inside an env variable.
* Should return the string as-is after stripping the leading `$` with the resolved env variable within
*/
auto base_value_embedded_invalid = conf.get_scalar<std::string>("base_value.invalid_embedded_env", default_value);
ASSERT_EQ(base_value_embedded_invalid, "${" + env_var_value + "}");
/*
* Test fetching of an escaped env variable plus an env variable side by side.
* Should return the escaped one trimming the leading `$` plus the second one resolved.
*/
auto base_value_valid_invalid = conf.get_scalar<std::string>("base_value.invalid_valid_env", default_value);
ASSERT_EQ(base_value_valid_invalid, "${ENV_VAR}" + env_var_value);
/* Test fetching of strings that contain environment variables */
auto base_value_id = conf.get_scalar<std::string>("base_value.id", default_value);
ASSERT_EQ(base_value_id, "$ENV_VAR"); // Does not follow the `${VAR}` format, so it should be treated as a regular string
auto base_value_name = conf.get_scalar<std::string>("base_value.name", default_value);
ASSERT_EQ(base_value_name, env_var_value); // Proper environment variable format
auto base_value_escaped = conf.get_scalar<std::string>("base_value.escaped", default_value);
ASSERT_EQ(base_value_escaped, env_var_value); // Environment variable within quotes
/* Test fetching of an undefined environment variable. Resolves to empty string. */
auto unknown_boolean = conf.get_scalar<std::string>("base_value.subvalue.subvalue2.boolean", default_value);
ASSERT_EQ(unknown_boolean, "");
/* Test fetching of environment variables from a list */
auto base_value_2_list_0 = conf.get_scalar<std::string>("base_value_2.sample_list[0]", default_value);
ASSERT_EQ(base_value_2_list_0, env_var_value); // Proper environment variable format
auto base_value_2_list_1 = conf.get_scalar<std::string>("base_value_2.sample_list[1]", default_value);
ASSERT_EQ(base_value_2_list_1, " " + env_var_value); // Environment variable preceded by a space, still extracted env var with leading space
auto base_value_2_list_2 = conf.get_scalar<std::string>("base_value_2.sample_list[2]", default_value);
ASSERT_EQ(base_value_2_list_2, env_var_value + " "); // Environment variable followed by a space, still extracted env var with trailing space
auto base_value_2_list_3 = conf.get_scalar<std::string>("base_value_2.sample_list[3]", default_value);
ASSERT_EQ(base_value_2_list_3, "$UNSED_XX_X_X_VAR"); // Does not follow the `${VAR}` format, so should be treated as a regular string
/* Test expansion of environment variables within strings */
auto path_list_0 = conf.get_scalar<std::string>("paths[0]", default_value);
ASSERT_EQ(path_list_0, env_var_value + "/foo"); // Even if env var is part of bigger string, it gets expanded
auto path_list_1 = conf.get_scalar<std::string>("paths[1]", default_value);
ASSERT_EQ(path_list_1, "$ENV_VAR/foo"); // Does not follow the `${VAR}` format, so should be treated as a regular string
auto path_list_2 = conf.get_scalar<std::string>("paths[2]", default_value);
ASSERT_EQ(path_list_2, "/foo/" + env_var_value + "/"); // Even when env var is in the middle of a string. it gets expanded
auto path_list_3 = conf.get_scalar<std::string>("paths[3]", default_value);
ASSERT_EQ(path_list_3, "/" + env_var_value + "/" + env_var_value + env_var_value + "/foo"); // Even when the string contains multiple env vars they are correctly expanded
auto path_list_4 = conf.get_scalar<std::string>("paths[4]", default_value);
ASSERT_EQ(path_list_4, env_var_value + "/foo"); // Even when the env var contains another env var, it gets correctly double-expanded
/* Check that variable expansion is type-aware */
auto boolean = conf.get_scalar<bool>("is_test", false);
ASSERT_EQ(boolean, true); // `true` can be parsed to bool.
auto boolean_as_str = conf.get_scalar<std::string>("is_test", "false");
ASSERT_EQ(boolean_as_str, "true"); // `true` can be parsed to string.
auto boolean_as_int = conf.get_scalar<int32_t>("is_test", 0);
ASSERT_EQ(boolean_as_int, 0); // `true` cannot be parsed to integer.
auto integer = conf.get_scalar<int32_t>("num_test", -1);
ASSERT_EQ(integer, 12);
// An env var that resolves to an empty string returns ""
auto empty_default_str = conf.get_scalar<std::string>("empty_test", default_value);
ASSERT_EQ(empty_default_str, "");
std::list<falco_configuration::plugin_config> plugins;
conf.get_sequence<std::list<falco_configuration::plugin_config>>(plugins, std::string("plugins"));
std::vector<falco_configuration::plugin_config> m_plugins{ std::make_move_iterator(std::begin(plugins)),
std::make_move_iterator(std::end(plugins)) };
ASSERT_EQ(m_plugins[0].m_name, "k8saudit");
ASSERT_EQ(m_plugins[0].m_library_path, "/foo/" + env_var_value + "/libk8saudit.so");
ASSERT_EQ(m_plugins[0].m_open_params, "12");
/* Clear the set environment variables after testing */
SET_ENV_VAR(env_var_name.c_str(), "");
SET_ENV_VAR(embedded_env_var_name.c_str(), "");
SET_ENV_VAR(bool_env_var_name.c_str(), "");
SET_ENV_VAR(int_env_var_name.c_str(), "");
SET_ENV_VAR(empty_env_var_name.c_str(), "");
}
TEST(Configuration, configuration_webserver_ip)
{
falco_configuration falco_config;
std::vector<std::string> valid_addresses = {"127.0.0.1",
"1.127.0.1",
"1.1.127.1",
"1.1.1.127",
"::",
"::1",
"1200:0000:AB00:1234:0000:2552:7777:1313",
"1200::AB00:1234:0000:2552:7777:1313",
"1200:0000:AB00:1234::2552:7777:1313",
"21DA:D3:0:2F3B:2AA:FF:FE28:9C5A",
"FE80:0000:0000:0000:0202:B3FF:FE1E:8329",
"0.0.0.0",
"9.255.255.255",
"11.0.0.0",
"126.255.255.255",
"129.0.0.0",
"169.253.255.255",
"169.255.0.0",
"172.15.255.255",
"172.32.0.0",
"191.0.1.255",
"192.88.98.255",
"192.88.100.0",
"192.167.255.255",
"192.169.0.0",
"198.17.255.255",
"223.255.255.255"};
for (const std::string &address: valid_addresses) {
std::string option = "webserver.listen_address=";
option.append(address);
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back(option);
EXPECT_NO_THROW(falco_config.init_from_content("", cmdline_config_options));
ASSERT_EQ(falco_config.m_webserver_config.m_listen_address, address);
}
std::vector<std::string> invalid_addresses = {"327.0.0.1",
"1.327.0.1",
"1.1.327.1",
"1.1.1.327",
"12 7.0.0.1",
"127. 0.0.1",
"127.0. 0.1",
"127.0.0. 1",
"!27.0.0.1",
"1200: 0000:AB00:1234:0000:2552:7777:1313",
"1200:0000: AB00:1234:0000:2552:7777:1313",
"1200:0000:AB00: 1234:0000:2552:7777:1313",
"1200:0000:AB00:1234: 0000:2552:7777:1313",
"1200:0000:AB00:1234:0000: 2552:7777:1313",
"1200:0000:AB00:1234:0000:2552: 7777:1313",
"1200:0000:AB00:1234:0000:2552:7777: 1313",
"1200:0000:AB00:1234:0000:2552:7777:131G",
"1200:0000:AB00:1234:0000:2552:77Z7:1313",
"1200:0000:AB00:1234:0000:2G52:7777:1313",
"1200:0000:AB00:1234:0O00:2552:7777:1313",
"1200:0000:AB00:H234:0000:2552:7777:1313",
"1200:0000:IB00:1234:0000:2552:7777:1313",
"1200:0O00:AB00:1234:0000:2552:7777:1313",
"12O0:0000:AB00:1234:0000:2552:7777:1313",};
for (const std::string &address: invalid_addresses) {
std::string option = "webserver.listen_address=";
option.append(address);
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back(option);
EXPECT_ANY_THROW(falco_config.init_from_content("", cmdline_config_options));
}
std::vector<std::string> valid_addresses = {"127.0.0.1",
"1.127.0.1",
"1.1.127.1",
"1.1.1.127",
"::",
"::1",
"1200:0000:AB00:1234:0000:2552:7777:1313",
"1200::AB00:1234:0000:2552:7777:1313",
"1200:0000:AB00:1234::2552:7777:1313",
"21DA:D3:0:2F3B:2AA:FF:FE28:9C5A",
"FE80:0000:0000:0000:0202:B3FF:FE1E:8329",
"0.0.0.0",
"9.255.255.255",
"11.0.0.0",
"126.255.255.255",
"129.0.0.0",
"169.253.255.255",
"169.255.0.0",
"172.15.255.255",
"172.32.0.0",
"191.0.1.255",
"192.88.98.255",
"192.88.100.0",
"192.167.255.255",
"192.169.0.0",
"198.17.255.255",
"223.255.255.255"};
for(const std::string &address : valid_addresses) {
std::string option = "webserver.listen_address=";
option.append(address);
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back(option);
EXPECT_NO_THROW(falco_config.init_from_content("", cmdline_config_options));
ASSERT_EQ(falco_config.m_webserver_config.m_listen_address, address);
}
std::vector<std::string> invalid_addresses = {
"327.0.0.1",
"1.327.0.1",
"1.1.327.1",
"1.1.1.327",
"12 7.0.0.1",
"127. 0.0.1",
"127.0. 0.1",
"127.0.0. 1",
"!27.0.0.1",
"1200: 0000:AB00:1234:0000:2552:7777:1313",
"1200:0000: AB00:1234:0000:2552:7777:1313",
"1200:0000:AB00: 1234:0000:2552:7777:1313",
"1200:0000:AB00:1234: 0000:2552:7777:1313",
"1200:0000:AB00:1234:0000: 2552:7777:1313",
"1200:0000:AB00:1234:0000:2552: 7777:1313",
"1200:0000:AB00:1234:0000:2552:7777: 1313",
"1200:0000:AB00:1234:0000:2552:7777:131G",
"1200:0000:AB00:1234:0000:2552:77Z7:1313",
"1200:0000:AB00:1234:0000:2G52:7777:1313",
"1200:0000:AB00:1234:0O00:2552:7777:1313",
"1200:0000:AB00:H234:0000:2552:7777:1313",
"1200:0000:IB00:1234:0000:2552:7777:1313",
"1200:0O00:AB00:1234:0000:2552:7777:1313",
"12O0:0000:AB00:1234:0000:2552:7777:1313",
};
for(const std::string &address : invalid_addresses) {
std::string option = "webserver.listen_address=";
option.append(address);
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back(option);
EXPECT_ANY_THROW(falco_config.init_from_content("", cmdline_config_options));
}
}

View File

@@ -0,0 +1,489 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include <falco/configuration.h>
TEST(Configuration, configuration_config_files_secondary_fail) {
/* Test that a secondary config file is not able to include anything, triggering an exception.
*/
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 = yaml_helper::configs_key +
":\n"
" - conf_4.yaml\n"
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
ASSERT_ANY_THROW(falco_config.init_from_file("main.yaml", cmdline_config_options));
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}
TEST(Configuration, configuration_config_files_ok) {
/* Test that every included config file was correctly parsed */
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo3: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
const std::string conf_yaml_4 =
"base_value_4:\n"
" id: 4\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
outfile.open("conf_4.yaml");
outfile << conf_yaml_4;
outfile.close();
std::vector<std::string> cmdline_config_options;
std::vector<std::string> loaded_conf_files;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(res.size(), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.m_config.is_defined("foo3"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo3", ""), "bar3");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_3.id", 0), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_3.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value_3.name", ""), "foo3");
ASSERT_FALSE(falco_config.m_config.is_defined("base_value_4.id")); // conf_4 is not included
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
std::filesystem::remove("conf_4.yaml");
}
TEST(Configuration, configuration_config_files_relative_main) {
/*
* Test that relative path are treated as relative to cwd and not to main config folder,
* and that absolute includes are ok too.
*/
const auto temp_main = std::filesystem::temp_directory_path() / "main.yaml";
// So, conf_2 will be looked up in the same folder as main config file,
// while conf_3, since is absolute, will be looked up in the absolute path (and found!).
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
" - conf_2.yaml\n"
" - " +
std::filesystem::current_path().string() +
"/conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo3: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
std::ofstream outfile(temp_main.string());
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file(temp_main.string(), cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(res.size(), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_3.id", 0), 3);
std::filesystem::remove(temp_main.string());
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
}
TEST(Configuration, configuration_config_files_override) {
/* Test that included config files are able to override configs from main file */
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
" - conf_2.yaml\n"
" - conf_3.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"base_value:\n"
" id: 3\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open("conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main + conf_2 + conf_3
ASSERT_EQ(res.size(), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 3); // overridden!
ASSERT_FALSE(falco_config.m_config.is_defined(
"base_value.name")); // no more present since entire `base_value` block was overridden
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_FALSE(falco_config.m_config.is_defined("base_value_3.id")); // not defined
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
std::filesystem::remove("conf_3.yaml");
}
TEST(Configuration, configuration_config_files_unexistent) {
/* Test that including an unexistent file just skips it */
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
" - conf_5.yaml\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main
ASSERT_EQ(res.size(), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_scalar_config_files) {
/* Test that a single file can be included as a scalar (thanks to get_sequence_from_node magic)
*/
const std::string main_conf_yaml = yaml_helper::configs_key +
": conf_2.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main + conf_2
ASSERT_EQ(res.size(), 2);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}
TEST(Configuration, configuration_config_files_empty_config_files) {
/* Test that empty includes list is accepted */
const std::string main_conf_yaml = yaml_helper::configs_key +
":\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main
ASSERT_EQ(res.size(), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_self) {
/* Test that main config file cannot include itself */
const std::string main_conf_yaml = yaml_helper::configs_key +
": main.yaml\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
ASSERT_ANY_THROW(falco_config.init_from_file("main.yaml", cmdline_config_options));
std::filesystem::remove("main.yaml");
}
TEST(Configuration, configuration_config_files_directory) {
/*
* Test that when main config file includes a config directory,
* the config directory is parsed in lexicographic order,
* and only regular files are parsed.
*/
// Main config includes whole temp directory
const std::string main_conf_yaml = yaml_helper::configs_key + ": " +
std::filesystem::temp_directory_path().string() +
"/test\n"
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
const std::string conf_yaml_3 =
"foo2: bar3\n"
"base_value_3:\n"
" id: 3\n"
" name: foo3\n";
const std::string conf_yaml_4 = "foo4: bar4\n";
std::filesystem::create_directory(std::filesystem::temp_directory_path() / "test");
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open(std::filesystem::temp_directory_path() / "test/conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
outfile.open(std::filesystem::temp_directory_path() / "test/conf_3.yaml");
outfile << conf_yaml_3;
outfile.close();
// Create a directory and create a config inside it. We will later check that it was not parsed
std::filesystem::create_directory(std::filesystem::temp_directory_path() / "test" / "foo");
outfile.open(std::filesystem::temp_directory_path() / "test/foo/conf_4.yaml");
outfile << conf_yaml_4;
outfile.close();
std::vector<std::string> cmdline_config_options;
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main + conf_2 + conf_3.
// test/foo is not parsed.
ASSERT_EQ(res.size(), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_3.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_3.id", 0), 3);
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar3");
ASSERT_FALSE(falco_config.m_config.is_defined("foo4"));
std::filesystem::remove("main");
std::filesystem::remove_all(std::filesystem::temp_directory_path() / "test");
}
TEST(Configuration, configuration_config_files_cmdline) {
/* Test that we support including configs files from cmdline option */
const std::string main_conf_yaml =
"foo: bar\n"
"base_value:\n"
" id: 1\n"
" name: foo\n";
const std::string conf_yaml_2 =
"foo2: bar2\n"
"base_value_2:\n"
" id: 2\n";
std::ofstream outfile("main.yaml");
outfile << main_conf_yaml;
outfile.close();
outfile.open("conf_2.yaml");
outfile << conf_yaml_2;
outfile.close();
// Pass "config_files=..." cmdline option
std::vector<std::string> cmdline_config_options;
cmdline_config_options.push_back((yaml_helper::configs_key + "=conf_2.yaml"));
falco_configuration falco_config;
config_loaded_res res;
ASSERT_NO_THROW(res = falco_config.init_from_file("main.yaml", cmdline_config_options));
// main + conf_2
ASSERT_EQ(res.size(), 2);
ASSERT_TRUE(falco_config.m_config.is_defined("foo"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo", ""), "bar");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value.id", 0), 1);
ASSERT_TRUE(falco_config.m_config.is_defined("base_value.name"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("base_value.name", ""), "foo");
ASSERT_TRUE(falco_config.m_config.is_defined("foo2"));
ASSERT_EQ(falco_config.m_config.get_scalar<std::string>("foo2", ""), "bar2");
ASSERT_TRUE(falco_config.m_config.is_defined("base_value_2.id"));
ASSERT_EQ(falco_config.m_config.get_scalar<int>("base_value_2.id", 0), 2);
std::filesystem::remove("main.yaml");
std::filesystem::remove("conf_2.yaml");
}

View File

@@ -0,0 +1,227 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include <falco/configuration.h>
#ifdef _WIN32
#define SET_ENV_VAR(env_var_name, env_var_value) _putenv_s(env_var_name, env_var_value)
#else
#define SET_ENV_VAR(env_var_name, env_var_value) setenv(env_var_name, env_var_value, 1)
#endif
TEST(Configuration, configuration_environment_variables) {
// Set an environment variable for testing purposes
std::string env_var_value = "envVarValue";
std::string env_var_name = "ENV_VAR";
SET_ENV_VAR(env_var_name.c_str(), env_var_value.c_str());
std::string embedded_env_var_value = "${ENV_VAR}";
std::string embedded_env_var_name = "ENV_VAR_EMBEDDED";
SET_ENV_VAR(embedded_env_var_name.c_str(), embedded_env_var_value.c_str());
std::string bool_env_var_value = "true";
std::string bool_env_var_name = "ENV_VAR_BOOL";
SET_ENV_VAR(bool_env_var_name.c_str(), bool_env_var_value.c_str());
std::string int_env_var_value = "12";
std::string int_env_var_name = "ENV_VAR_INT";
SET_ENV_VAR(int_env_var_name.c_str(), int_env_var_value.c_str());
std::string empty_env_var_value = "";
std::string empty_env_var_name = "ENV_VAR_EMPTY";
SET_ENV_VAR(empty_env_var_name.c_str(), empty_env_var_value.c_str());
std::string default_value = "default";
std::string env_var_sample_yaml =
"base_value:\n"
" id: $ENV_VAR\n"
" name: '${ENV_VAR}'\n"
" string: my_string\n"
" invalid: $${ENV_VAR}\n"
" invalid_env: $$ENV_VAR\n"
" invalid_double_env: $${ENV_VAR}$${ENV_VAR}\n"
" invalid_embedded_env: $${${ENV_VAR}}\n"
" invalid_valid_env: $${ENV_VAR}${ENV_VAR}\n"
" escaped: \"${ENV_VAR}\"\n"
" subvalue:\n"
" subvalue2:\n"
" boolean: ${UNSED_XX_X_X_VAR}\n"
"base_value_2:\n"
" sample_list:\n"
" - ${ENV_VAR}\n"
" - ' ${ENV_VAR}'\n"
" - '${ENV_VAR} '\n"
" - $UNSED_XX_X_X_VAR\n"
"paths:\n"
" - ${ENV_VAR}/foo\n"
" - $ENV_VAR/foo\n"
" - /foo/${ENV_VAR}/\n"
" - /${ENV_VAR}/${ENV_VAR}${ENV_VAR}/foo\n"
" - ${ENV_VAR_EMBEDDED}/foo\n"
"is_test: ${ENV_VAR_BOOL}\n"
"num_test: ${ENV_VAR_INT}\n"
"empty_test: ${ENV_VAR_EMPTY}\n"
"plugins:\n"
" - name: k8saudit\n"
" library_path: /foo/${ENV_VAR}/libk8saudit.so\n"
" open_params: ${ENV_VAR_INT}\n";
yaml_helper conf;
conf.load_from_string(env_var_sample_yaml);
/* Check if the base values are defined */
ASSERT_TRUE(conf.is_defined("base_value"));
ASSERT_TRUE(conf.is_defined("base_value_2"));
ASSERT_TRUE(conf.is_defined("paths"));
ASSERT_FALSE(conf.is_defined("unknown_base_value"));
/* Test fetching of a regular string without any environment variable */
auto base_value_string = conf.get_scalar<std::string>("base_value.string", default_value);
ASSERT_EQ(base_value_string, "my_string");
/* Test fetching of escaped environment variable format. Should return the string as-is after
* stripping the leading `$` */
auto base_value_invalid = conf.get_scalar<std::string>("base_value.invalid", default_value);
ASSERT_EQ(base_value_invalid, "${ENV_VAR}");
/* Test fetching of invalid escaped environment variable format. Should return the string as-is
*/
auto base_value_invalid_env =
conf.get_scalar<std::string>("base_value.invalid_env", default_value);
ASSERT_EQ(base_value_invalid_env, "$$ENV_VAR");
/* Test fetching of 2 escaped environment variables side by side. Should return the string as-is
* after stripping the leading `$` */
auto base_value_double_invalid =
conf.get_scalar<std::string>("base_value.invalid_double_env", default_value);
ASSERT_EQ(base_value_double_invalid, "${ENV_VAR}${ENV_VAR}");
/*
* Test fetching of escaped environment variable format with inside an env variable.
* Should return the string as-is after stripping the leading `$` with the resolved env variable
* within
*/
auto base_value_embedded_invalid =
conf.get_scalar<std::string>("base_value.invalid_embedded_env", default_value);
ASSERT_EQ(base_value_embedded_invalid, "${" + env_var_value + "}");
/*
* Test fetching of an escaped env variable plus an env variable side by side.
* Should return the escaped one trimming the leading `$` plus the second one resolved.
*/
auto base_value_valid_invalid =
conf.get_scalar<std::string>("base_value.invalid_valid_env", default_value);
ASSERT_EQ(base_value_valid_invalid, "${ENV_VAR}" + env_var_value);
/* Test fetching of strings that contain environment variables */
auto base_value_id = conf.get_scalar<std::string>("base_value.id", default_value);
ASSERT_EQ(base_value_id, "$ENV_VAR"); // Does not follow the `${VAR}` format, so it should be
// treated as a regular string
auto base_value_name = conf.get_scalar<std::string>("base_value.name", default_value);
ASSERT_EQ(base_value_name, env_var_value); // Proper environment variable format
auto base_value_escaped = conf.get_scalar<std::string>("base_value.escaped", default_value);
ASSERT_EQ(base_value_escaped, env_var_value); // Environment variable within quotes
/* Test fetching of an undefined environment variable. Resolves to empty string. */
auto unknown_boolean =
conf.get_scalar<std::string>("base_value.subvalue.subvalue2.boolean", default_value);
ASSERT_EQ(unknown_boolean, "");
/* Test fetching of environment variables from a list */
auto base_value_2_list_0 =
conf.get_scalar<std::string>("base_value_2.sample_list[0]", default_value);
ASSERT_EQ(base_value_2_list_0, env_var_value); // Proper environment variable format
auto base_value_2_list_1 =
conf.get_scalar<std::string>("base_value_2.sample_list[1]", default_value);
ASSERT_EQ(base_value_2_list_1,
" " + env_var_value); // Environment variable preceded by a space, still extracted
// env var with leading space
auto base_value_2_list_2 =
conf.get_scalar<std::string>("base_value_2.sample_list[2]", default_value);
ASSERT_EQ(base_value_2_list_2,
env_var_value + " "); // Environment variable followed by a space, still extracted
// env var with trailing space
auto base_value_2_list_3 =
conf.get_scalar<std::string>("base_value_2.sample_list[3]", default_value);
ASSERT_EQ(base_value_2_list_3, "$UNSED_XX_X_X_VAR"); // Does not follow the `${VAR}` format, so
// should be treated as a regular string
/* Test expansion of environment variables within strings */
auto path_list_0 = conf.get_scalar<std::string>("paths[0]", default_value);
ASSERT_EQ(
path_list_0,
env_var_value + "/foo"); // Even if env var is part of bigger string, it gets expanded
auto path_list_1 = conf.get_scalar<std::string>("paths[1]", default_value);
ASSERT_EQ(path_list_1, "$ENV_VAR/foo"); // Does not follow the `${VAR}` format, so should be
// treated as a regular string
auto path_list_2 = conf.get_scalar<std::string>("paths[2]", default_value);
ASSERT_EQ(path_list_2,
"/foo/" + env_var_value +
"/"); // Even when env var is in the middle of a string. it gets expanded
auto path_list_3 = conf.get_scalar<std::string>("paths[3]", default_value);
ASSERT_EQ(path_list_3,
"/" + env_var_value + "/" + env_var_value + env_var_value +
"/foo"); // Even when the string contains multiple env vars they are
// correctly expanded
auto path_list_4 = conf.get_scalar<std::string>("paths[4]", default_value);
ASSERT_EQ(path_list_4, env_var_value + "/foo"); // Even when the env var contains another env
// var, it gets correctly double-expanded
/* Check that variable expansion is type-aware */
auto boolean = conf.get_scalar<bool>("is_test", false);
ASSERT_EQ(boolean, true); // `true` can be parsed to bool.
auto boolean_as_str = conf.get_scalar<std::string>("is_test", "false");
ASSERT_EQ(boolean_as_str, "true"); // `true` can be parsed to string.
auto boolean_as_int = conf.get_scalar<int32_t>("is_test", 0);
ASSERT_EQ(boolean_as_int, 0); // `true` cannot be parsed to integer.
auto integer = conf.get_scalar<int32_t>("num_test", -1);
ASSERT_EQ(integer, 12);
// An env var that resolves to an empty string returns ""
auto empty_default_str = conf.get_scalar<std::string>("empty_test", default_value);
ASSERT_EQ(empty_default_str, "");
std::list<falco_configuration::plugin_config> plugins;
conf.get_sequence<std::list<falco_configuration::plugin_config>>(plugins,
std::string("plugins"));
std::vector<falco_configuration::plugin_config> m_plugins{
std::make_move_iterator(std::begin(plugins)),
std::make_move_iterator(std::end(plugins))};
ASSERT_EQ(m_plugins[0].m_name, "k8saudit");
ASSERT_EQ(m_plugins[0].m_library_path, "/foo/" + env_var_value + "/libk8saudit.so");
ASSERT_EQ(m_plugins[0].m_open_params, "12");
/* Clear the set environment variables after testing */
SET_ENV_VAR(env_var_name.c_str(), "");
SET_ENV_VAR(embedded_env_var_name.c_str(), "");
SET_ENV_VAR(bool_env_var_name.c_str(), "");
SET_ENV_VAR(int_env_var_name.c_str(), "");
SET_ENV_VAR(empty_env_var_name.c_str(), "");
}

View File

@@ -0,0 +1,123 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2024 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include <falco/configuration.h>
TEST(ConfigurationRuleOutputOptions, parse_yaml) {
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_content(R"(
append_output:
- match:
source: syscall
tags: ["persistence"]
rule: some rule name
extra_output: "gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]"
- match:
tags: ["persistence", "execution"]
extra_fields:
- proc.aname[2]: "%proc.aname[2]"
- proc.aname[3]: "%proc.aname[3]"
- proc.aname[4]: "%proc.aname[4]"
extra_output: "gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]"
- match:
source: k8s_audit
extra_fields:
- ka.verb
- static_field: "static content"
)",
{}));
EXPECT_EQ(falco_config.m_append_output.size(), 3);
EXPECT_EQ(falco_config.m_append_output[0].m_source, "syscall");
EXPECT_EQ(falco_config.m_append_output[0].m_tags.size(), 1);
EXPECT_EQ(falco_config.m_append_output[0].m_tags.count("persistence"), 1);
EXPECT_EQ(falco_config.m_append_output[0].m_rule, "some rule name");
EXPECT_EQ(falco_config.m_append_output[0].m_formatted_fields.size(), 0);
EXPECT_EQ(falco_config.m_append_output[0].m_format,
"gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[1].m_tags.size(), 2);
EXPECT_EQ(falco_config.m_append_output[1].m_tags.count("persistence"), 1);
EXPECT_EQ(falco_config.m_append_output[1].m_tags.count("execution"), 1);
EXPECT_EQ(falco_config.m_append_output[1].m_format,
"gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields.size(), 3);
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[2]"],
"%proc.aname[2]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[3]"],
"%proc.aname[3]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[4]"],
"%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[2].m_source, "k8s_audit");
EXPECT_EQ(falco_config.m_append_output[2].m_formatted_fields.size(), 1);
EXPECT_EQ(falco_config.m_append_output[2].m_formatted_fields["static_field"], "static content");
EXPECT_EQ(falco_config.m_append_output[2].m_raw_fields.size(), 1);
EXPECT_EQ(falco_config.m_append_output[2].m_raw_fields.count("ka.verb"), 1);
}
TEST(ConfigurationRuleOutputOptions, cli_options) {
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_content(
"",
std::vector<std::string>{
R"(append_output[]={"match": {"source": "syscall", "tags": ["persistence"], "rule": "some rule name"}, "extra_output": "gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]"})",
R"(append_output[]={"match": {"tags": ["persistence", "execution"]}, "extra_fields": [{"proc.aname[2]": "%proc.aname[2]"}, {"proc.aname[3]": "%proc.aname[3]"}, {"proc.aname[4]": "%proc.aname[4]"}], "extra_output": "gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]"})",
R"(append_output[]={"match": {"source": "k8s_audit"}, "extra_fields": ["ka.verb", {"static_field": "static content"}]})"}));
EXPECT_EQ(falco_config.m_append_output.size(), 3);
EXPECT_EQ(falco_config.m_append_output[0].m_source, "syscall");
EXPECT_EQ(falco_config.m_append_output[0].m_tags.size(), 1);
EXPECT_EQ(falco_config.m_append_output[0].m_tags.count("persistence"), 1);
EXPECT_EQ(falco_config.m_append_output[0].m_rule, "some rule name");
EXPECT_EQ(falco_config.m_append_output[0].m_formatted_fields.size(), 0);
EXPECT_EQ(falco_config.m_append_output[0].m_format,
"gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[1].m_tags.size(), 2);
EXPECT_EQ(falco_config.m_append_output[1].m_tags.count("persistence"), 1);
EXPECT_EQ(falco_config.m_append_output[1].m_tags.count("execution"), 1);
EXPECT_EQ(falco_config.m_append_output[1].m_format,
"gparent=%proc.aname[2] ggparent=%proc.aname[3] gggparent=%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields.size(), 3);
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[2]"],
"%proc.aname[2]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[3]"],
"%proc.aname[3]");
EXPECT_EQ(falco_config.m_append_output[1].m_formatted_fields["proc.aname[4]"],
"%proc.aname[4]");
EXPECT_EQ(falco_config.m_append_output[2].m_source, "k8s_audit");
EXPECT_EQ(falco_config.m_append_output[2].m_formatted_fields.size(), 1);
EXPECT_EQ(falco_config.m_append_output[2].m_formatted_fields["static_field"], "static content");
EXPECT_EQ(falco_config.m_append_output[2].m_raw_fields.size(), 1);
EXPECT_EQ(falco_config.m_append_output[2].m_raw_fields.count("ka.verb"), 1);
}

View File

@@ -18,10 +18,9 @@ limitations under the License.
#include <gtest/gtest.h>
#include <falco/configuration.h>
TEST(ConfigurationRuleSelection, parse_yaml)
{
TEST(ConfigurationRuleSelection, parse_yaml) {
falco_configuration falco_config;
EXPECT_NO_THROW(falco_config.init_from_content(R"(
ASSERT_NO_THROW(falco_config.init_from_content(R"(
rules:
- enable:
rule: 'Terminal Shell in Container'
@@ -31,30 +30,57 @@ rules:
- enable:
rule: 'hello*'
)", {}));
)",
{}));
ASSERT_EQ(falco_config.m_rules_selection.size(), 3);
EXPECT_EQ(falco_config.m_rules_selection.size(), 3);
ASSERT_EQ(falco_config.m_rules_selection[0].m_op, falco_configuration::rule_selection_operation::enable);
ASSERT_EQ(falco_config.m_rules_selection[0].m_rule, "Terminal Shell in Container");
EXPECT_EQ(falco_config.m_rules_selection[0].m_op,
falco_configuration::rule_selection_operation::enable);
EXPECT_EQ(falco_config.m_rules_selection[0].m_rule, "Terminal Shell in Container");
ASSERT_EQ(falco_config.m_rules_selection[1].m_op, falco_configuration::rule_selection_operation::disable);
ASSERT_EQ(falco_config.m_rules_selection[1].m_tag, "experimental");
EXPECT_EQ(falco_config.m_rules_selection[1].m_op,
falco_configuration::rule_selection_operation::disable);
EXPECT_EQ(falco_config.m_rules_selection[1].m_tag, "experimental");
ASSERT_EQ(falco_config.m_rules_selection[2].m_op, falco_configuration::rule_selection_operation::enable);
ASSERT_EQ(falco_config.m_rules_selection[2].m_rule, "hello*");
EXPECT_EQ(falco_config.m_rules_selection[2].m_op,
falco_configuration::rule_selection_operation::enable);
EXPECT_EQ(falco_config.m_rules_selection[2].m_rule, "hello*");
}
TEST(ConfigurationRuleSelection, cli_options)
{
TEST(ConfigurationRuleSelection, cli_options) {
falco_configuration falco_config;
EXPECT_NO_THROW(falco_config.init_from_content("", std::vector<std::string>{"rules[].disable.tag=maturity_incubating", "rules[].enable.rule=Adding ssh keys to authorized_keys"}));
ASSERT_NO_THROW(falco_config.init_from_content(
"",
std::vector<std::string>{"rules[].disable.tag=maturity_incubating",
"rules[].enable.rule=Adding ssh keys to authorized_keys"}));
ASSERT_EQ(falco_config.m_rules_selection.size(), 2);
EXPECT_EQ(falco_config.m_rules_selection.size(), 2);
ASSERT_EQ(falco_config.m_rules_selection[0].m_op, falco_configuration::rule_selection_operation::disable);
ASSERT_EQ(falco_config.m_rules_selection[0].m_tag, "maturity_incubating");
EXPECT_EQ(falco_config.m_rules_selection[0].m_op,
falco_configuration::rule_selection_operation::disable);
EXPECT_EQ(falco_config.m_rules_selection[0].m_tag, "maturity_incubating");
ASSERT_EQ(falco_config.m_rules_selection[1].m_op, falco_configuration::rule_selection_operation::enable);
ASSERT_EQ(falco_config.m_rules_selection[1].m_rule, "Adding ssh keys to authorized_keys");
EXPECT_EQ(falco_config.m_rules_selection[1].m_op,
falco_configuration::rule_selection_operation::enable);
EXPECT_EQ(falco_config.m_rules_selection[1].m_rule, "Adding ssh keys to authorized_keys");
}
TEST(ConfigurationRuleSelection, cli_options_object) {
falco_configuration falco_config;
ASSERT_NO_THROW(falco_config.init_from_content(
"",
std::vector<std::string>{
R"(rules[]={"disable": {"tag": "maturity_incubating"}})",
R"(rules[]={"enable": {"rule": "Adding ssh keys to authorized_keys"}})"}));
EXPECT_EQ(falco_config.m_rules_selection.size(), 2);
EXPECT_EQ(falco_config.m_rules_selection[0].m_op,
falco_configuration::rule_selection_operation::disable);
EXPECT_EQ(falco_config.m_rules_selection[0].m_tag, "maturity_incubating");
EXPECT_EQ(falco_config.m_rules_selection[1].m_op,
falco_configuration::rule_selection_operation::enable);
EXPECT_EQ(falco_config.m_rules_selection[1].m_rule, "Adding ssh keys to authorized_keys");
}

View File

@@ -0,0 +1,172 @@
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <gtest/gtest.h>
#include <falco/configuration.h>
#include <falco_test_var.h>
#include <nlohmann/json.hpp>
#define EXPECT_VALIDATION_STATUS(res, status) \
do { \
for(const auto& pair : res) { \
auto validation_status = pair.second; \
EXPECT_TRUE(sinsp_utils::startswith(validation_status, status)) << validation_status; \
} \
} while(0)
// Read Falco config from current repo-path
TEST(Configuration, schema_validate_config) {
falco_configuration falco_config;
config_loaded_res res;
if(!std::filesystem::exists(TEST_FALCO_CONFIG)) {
GTEST_SKIP() << "Falco config not present under " << TEST_FALCO_CONFIG;
}
EXPECT_NO_THROW(res = falco_config.init_from_file(TEST_FALCO_CONFIG, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
}
TEST(Configuration, schema_ok) {
falco_configuration falco_config;
config_loaded_res res;
/* OK YAML */
std::string config =
"falco_libs:\n"
" thread_table_size: 50\n";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
}
TEST(Configuration, schema_wrong_key) {
falco_configuration falco_config;
config_loaded_res res;
/* Miss-typed key YAML */
std::string config =
"falco_libss:\n"
" thread_table_size: 50\n";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_failed);
}
TEST(Configuration, schema_wrong_type) {
falco_configuration falco_config;
/* Wrong value type YAML */
std::string config = "falco_libs: 512\n";
// We expect an exception since `falco_configuration::load_yaml()`
// will fail to parse `falco_libs` node.
ASSERT_ANY_THROW(falco_config.init_from_content(config, {}));
}
TEST(Configuration, schema_wrong_embedded_key) {
falco_configuration falco_config;
config_loaded_res res;
/* Miss-typed sub-key YAML */
std::string config =
"falco_libs:\n"
" thread_table_sizeee: 50\n";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_failed);
}
TEST(Configuration, plugin_init_config) {
falco_configuration falco_config;
config_loaded_res res;
std::string config = R"(
plugins:
- name: k8saudit
library_path: libk8saudit.so
init_config:
maxEventSize: 262144
sslCertificate: /etc/falco/falco.pem
)";
auto plugin_config_json = nlohmann::json::parse(
R"({"maxEventSize": 262144, "sslCertificate": "/etc/falco/falco.pem"})");
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
auto parsed_init_config = nlohmann::json::parse(falco_config.m_plugins[0].m_init_config);
EXPECT_EQ(parsed_init_config, plugin_config_json);
config = R"(
plugins:
- name: k8saudit
library_path: libk8saudit.so
init_config: '{"maxEventSize": 262144, "sslCertificate": "/etc/falco/falco.pem"}'
)";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
parsed_init_config = nlohmann::json::parse(falco_config.m_plugins[0].m_init_config);
EXPECT_EQ(parsed_init_config, plugin_config_json);
config = R"(
plugins:
- name: k8saudit
library_path: libk8saudit.so
init_config: ""
)";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
EXPECT_EQ(falco_config.m_plugins[0].m_init_config, "");
config = R"(
plugins:
- name: k8saudit
library_path: libk8saudit.so
init_config: null
)";
EXPECT_NO_THROW(res = falco_config.init_from_content(config, {}));
EXPECT_VALIDATION_STATUS(res, yaml_helper::validation_ok);
EXPECT_EQ(falco_config.m_plugins[0].m_init_config, "");
}
TEST(Configuration, schema_yaml_helper_validator) {
yaml_helper conf;
falco_configuration falco_config;
/* Broken YAML */
std::string sample_yaml =
"falco_libs:\n"
" thread_table_size: 50\n";
// Ok, we don't ask for any validation
EXPECT_NO_THROW(conf.load_from_string(sample_yaml));
// We pass a string variable but not a schema
std::vector<std::string> validation;
EXPECT_NO_THROW(conf.load_from_string(sample_yaml, nlohmann::json{}, &validation));
EXPECT_EQ(validation[0], yaml_helper::validation_none);
// We pass a schema but not a string storage for the validation; no validation takes place
EXPECT_NO_THROW(conf.load_from_string(sample_yaml, falco_config.m_config_schema, nullptr));
// We pass everything
EXPECT_NO_THROW(conf.load_from_string(sample_yaml, falco_config.m_config_schema, &validation));
EXPECT_EQ(validation[0], yaml_helper::validation_ok);
}

View File

@@ -2,3 +2,4 @@
#define TEST_ENGINE_KMOD_CONFIG "${CMAKE_SOURCE_DIR}/unit_tests/falco/test_configs/engine_kmod_config.yaml"
#define TEST_ENGINE_MODERN_CONFIG "${CMAKE_SOURCE_DIR}/unit_tests/falco/test_configs/engine_modern_config.yaml"
#define TEST_FALCO_CONFIG "${CMAKE_SOURCE_DIR}/falco.yaml"

View File

@@ -1,7 +1,6 @@
#include "test_falco_engine.h"
test_falco_engine::test_falco_engine()
{
test_falco_engine::test_falco_engine() {
// create a falco engine ready to load the ruleset
m_filter_factory = std::make_shared<sinsp_filter_factory>(&m_inspector, m_filterlist);
m_formatter_factory = std::make_shared<sinsp_evt_formatter_factory>(&m_inspector, m_filterlist);
@@ -9,8 +8,8 @@ test_falco_engine::test_falco_engine()
m_engine->add_source(m_sample_source, m_filter_factory, m_formatter_factory);
}
bool test_falco_engine::load_rules(const std::string& rules_content, const std::string& rules_filename)
{
bool test_falco_engine::load_rules(const std::string& rules_content,
const std::string& rules_filename) {
bool ret = false;
falco::load_result::rules_contents_t rc = {{rules_filename, rules_content}};
m_load_result = m_engine->load_rules(rules_content, rules_filename);
@@ -18,8 +17,7 @@ bool test_falco_engine::load_rules(const std::string& rules_content, const std::
m_load_result_json = m_load_result->as_json(rc);
ret = m_load_result->successful();
if (ret)
{
if(ret) {
m_engine->enable_rule("", true, m_sample_ruleset);
}
@@ -27,30 +25,24 @@ bool test_falco_engine::load_rules(const std::string& rules_content, const std::
}
// This must be kept in line with the (private) falco_engine::s_default_ruleset
uint64_t test_falco_engine::num_rules_for_ruleset(const std::string& ruleset)
{
uint64_t test_falco_engine::num_rules_for_ruleset(const std::string& ruleset) {
return m_engine->num_rules_for_ruleset(ruleset);
}
bool test_falco_engine::has_warnings() const
{
bool test_falco_engine::has_warnings() const {
return m_load_result->has_warnings();
}
bool test_falco_engine::check_warning_message(const std::string& warning_msg) const
{
if(!m_load_result->has_warnings())
{
bool test_falco_engine::check_warning_message(const std::string& warning_msg) const {
if(!m_load_result->has_warnings()) {
return false;
}
for(const auto &warn : m_load_result_json["warnings"])
{
for(const auto& warn : m_load_result_json["warnings"]) {
std::string msg = warn["message"];
// Debug:
// printf("msg: %s\n", msg.c_str());
if(msg.find(warning_msg) != std::string::npos)
{
if(msg.find(warning_msg) != std::string::npos) {
return true;
}
}
@@ -58,21 +50,17 @@ bool test_falco_engine::check_warning_message(const std::string& warning_msg) co
return false;
}
bool test_falco_engine::check_error_message(const std::string& error_msg) const
{
bool test_falco_engine::check_error_message(const std::string& error_msg) const {
// if the loading is successful there are no errors
if(m_load_result->successful())
{
if(m_load_result->successful()) {
return false;
}
for(const auto &err : m_load_result_json["errors"])
{
for(const auto& err : m_load_result_json["errors"]) {
std::string msg = err["message"];
// Debug:
// printf("msg: %s\n", msg.c_str());
if(msg.find(error_msg) != std::string::npos)
{
if(msg.find(error_msg) != std::string::npos) {
return true;
}
}
@@ -80,8 +68,20 @@ bool test_falco_engine::check_error_message(const std::string& error_msg) const
return false;
}
std::string test_falco_engine::get_compiled_rule_condition(std::string rule_name) const
{
std::string test_falco_engine::get_compiled_rule_condition(std::string rule_name) const {
auto rule_description = m_engine->describe_rule(&rule_name, {});
return rule_description["rules"][0]["details"]["condition_compiled"].template get<std::string>();
return rule_description["rules"][0]["details"]["condition_compiled"]
.template get<std::string>();
}
std::string test_falco_engine::get_compiled_rule_output(std::string rule_name) const {
auto rule_description = m_engine->describe_rule(&rule_name, {});
return rule_description["rules"][0]["details"]["output_compiled"].template get<std::string>();
}
std::unordered_map<std::string, std::string> test_falco_engine::get_compiled_rule_formatted_fields(
std::string rule_name) const {
auto rule_description = m_engine->describe_rule(&rule_name, {});
return rule_description["rules"][0]["details"]["extra_output_formatted_fields"]
.template get<std::unordered_map<std::string, std::string>>();
}

View File

@@ -6,9 +6,9 @@
#include "rule_loading_messages.h"
#include <gtest/gtest.h>
#include <unordered_map>
class test_falco_engine : public testing::Test
{
class test_falco_engine : public testing::Test {
protected:
test_falco_engine();
@@ -19,6 +19,9 @@ protected:
bool check_warning_message(const std::string& warning_msg) const;
bool check_error_message(const std::string& error_msg) const;
std::string get_compiled_rule_condition(std::string rule_name = "") const;
std::string get_compiled_rule_output(std::string rule_name = "") const;
std::unordered_map<std::string, std::string> get_compiled_rule_formatted_fields(
std::string rule_name) const;
std::string m_sample_ruleset = "sample-ruleset";
std::string m_sample_source = falco_common::syscall_source;

View File

@@ -2,46 +2,40 @@
#
# Copyright (C) 2023 The Falco Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
# Unless required by applicable law or agreed to in writing, software distributed under the License
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing permissions and limitations under
# the License.
add_library(falco_engine STATIC
falco_common.cpp
falco_engine.cpp
falco_load_result.cpp
falco_utils.cpp
filter_ruleset.cpp
evttype_index_ruleset.cpp
formats.cpp
filter_details_resolver.cpp
filter_macro_resolver.cpp
filter_warning_resolver.cpp
stats_manager.cpp
rule_loader.cpp
rule_loader_reader.cpp
rule_loader_collector.cpp
rule_loader_compiler.cpp
add_library(
falco_engine STATIC
falco_common.cpp
falco_engine.cpp
falco_load_result.cpp
falco_utils.cpp
filter_ruleset.cpp
evttype_index_ruleset.cpp
formats.cpp
filter_details_resolver.cpp
filter_macro_resolver.cpp
filter_warning_resolver.cpp
logger.cpp
stats_manager.cpp
rule_loader.cpp
rule_loader_reader.cpp
rule_loader_collector.cpp
rule_loader_compiler.cpp
)
if (EMSCRIPTEN)
if(EMSCRIPTEN)
target_compile_options(falco_engine PRIVATE "-sDISABLE_EXCEPTION_CATCHING=0")
endif()
target_include_directories(falco_engine
PUBLIC
${CMAKE_CURRENT_SOURCE_DIR}
${TBB_INCLUDE_DIR}
)
target_include_directories(falco_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${TBB_INCLUDE_DIR})
target_link_libraries(falco_engine
PUBLIC
sinsp
nlohmann_json::nlohmann_json
yaml-cpp
)
target_link_libraries(falco_engine PUBLIC sinsp nlohmann_json::nlohmann_json yaml-cpp)

View File

@@ -17,124 +17,48 @@ limitations under the License.
#include "evttype_index_ruleset.h"
#include "falco_utils.h"
#include "../falco/logger.h"
#include "logger.h"
#include <algorithm>
evttype_index_ruleset::evttype_index_ruleset(
std::shared_ptr<sinsp_filter_factory> f): m_filter_factory(f)
{
}
evttype_index_ruleset::evttype_index_ruleset(std::shared_ptr<sinsp_filter_factory> f):
m_filter_factory(f) {}
evttype_index_ruleset::~evttype_index_ruleset()
{
}
evttype_index_ruleset::~evttype_index_ruleset() {}
evttype_index_ruleset::ruleset_filters::ruleset_filters()
{
}
evttype_index_ruleset::ruleset_filters::~ruleset_filters()
{
}
void evttype_index_ruleset::ruleset_filters::add_wrapper_to_list(filter_wrapper_list &wrappers, std::shared_ptr<filter_wrapper> wrap)
{
// This is O(n) but it's also uncommon
// (when loading rules only).
auto pos = std::find(wrappers.begin(),
wrappers.end(),
wrap);
if(pos == wrappers.end())
{
wrappers.push_back(wrap);
}
}
void evttype_index_ruleset::ruleset_filters::remove_wrapper_from_list(filter_wrapper_list &wrappers, std::shared_ptr<filter_wrapper> wrap)
{
// This is O(n) but it's also uncommon
// (when loading rules only).
auto pos = std::find(wrappers.begin(),
wrappers.end(),
wrap);
if(pos != wrappers.end())
{
wrappers.erase(pos);
}
}
void evttype_index_ruleset::ruleset_filters::add_filter(std::shared_ptr<filter_wrapper> wrap)
{
if(wrap->event_codes.empty())
{
// Should run for all event types
add_wrapper_to_list(m_filter_all_event_types, wrap);
}
else
{
for(auto &etype : wrap->event_codes)
{
if(m_filter_by_event_type.size() <= etype)
{
m_filter_by_event_type.resize(etype + 1);
}
add_wrapper_to_list(m_filter_by_event_type[etype], wrap);
void evttype_index_ruleset::add(const falco_rule &rule,
std::shared_ptr<sinsp_filter> filter,
std::shared_ptr<libsinsp::filter::ast::expr> condition) {
try {
auto wrap = std::make_shared<evttype_index_wrapper>();
wrap->m_rule = rule;
wrap->m_filter = filter;
if(rule.source == falco_common::syscall_source) {
wrap->m_sc_codes = libsinsp::filter::ast::ppm_sc_codes(condition.get());
wrap->m_event_codes = libsinsp::filter::ast::ppm_event_codes(condition.get());
} else {
wrap->m_sc_codes = {};
wrap->m_event_codes = {ppm_event_code::PPME_PLUGINEVENT_E};
}
}
wrap->m_event_codes.insert(ppm_event_code::PPME_ASYNCEVENT_E);
m_filters.insert(wrap);
add_wrapper(wrap);
} catch(const sinsp_exception &e) {
throw falco_exception(std::string(e.what()));
}
}
void evttype_index_ruleset::ruleset_filters::remove_filter(std::shared_ptr<filter_wrapper> wrap)
{
if(wrap->event_codes.empty())
{
remove_wrapper_from_list(m_filter_all_event_types, wrap);
}
else
{
for(auto &etype : wrap->event_codes)
{
if( etype < m_filter_by_event_type.size() )
{
remove_wrapper_from_list(m_filter_by_event_type[etype], wrap);
}
}
}
m_filters.erase(wrap);
void evttype_index_ruleset::on_loading_complete() {
print_enabled_rules_falco_logger();
}
uint64_t evttype_index_ruleset::ruleset_filters::num_filters()
{
return m_filters.size();
}
bool evttype_index_ruleset::ruleset_filters::run(sinsp_evt *evt, falco_rule& match)
{
if(evt->get_type() < m_filter_by_event_type.size())
{
for(const auto &wrap : m_filter_by_event_type[evt->get_type()])
{
if(wrap->filter->run(evt))
{
match = wrap->rule;
return true;
}
}
}
// Finally, try filters that are not specific to an event type.
for(const auto &wrap : m_filter_all_event_types)
{
if(wrap->filter->run(evt))
{
match = wrap->rule;
bool evttype_index_ruleset::run_wrappers(sinsp_evt *evt,
filter_wrapper_list &wrappers,
uint16_t ruleset_id,
falco_rule &match) {
for(auto &wrap : wrappers) {
if(wrap->m_filter->run(evt)) {
match = wrap->m_rule;
return true;
}
}
@@ -142,33 +66,15 @@ bool evttype_index_ruleset::ruleset_filters::run(sinsp_evt *evt, falco_rule& mat
return false;
}
bool evttype_index_ruleset::ruleset_filters::run(sinsp_evt *evt, std::vector<falco_rule>& matches)
{
bool evttype_index_ruleset::run_wrappers(sinsp_evt *evt,
filter_wrapper_list &wrappers,
uint16_t ruleset_id,
std::vector<falco_rule> &matches) {
bool match_found = false;
if(evt->get_type() < m_filter_by_event_type.size())
{
for(const auto &wrap : m_filter_by_event_type[evt->get_type()])
{
if(wrap->filter->run(evt))
{
matches.push_back(wrap->rule);
match_found = true;
}
}
}
if(match_found)
{
return true;
}
// Finally, try filters that are not specific to an event type.
for(const auto &wrap : m_filter_all_event_types)
{
if(wrap->filter->run(evt))
{
matches.push_back(wrap->rule);
for(auto &wrap : wrappers) {
if(wrap->m_filter->run(evt)) {
matches.push_back(wrap->m_rule);
match_found = true;
}
}
@@ -176,234 +82,15 @@ bool evttype_index_ruleset::ruleset_filters::run(sinsp_evt *evt, std::vector<fal
return match_found;
}
libsinsp::events::set<ppm_sc_code> evttype_index_ruleset::ruleset_filters::sc_codes()
{
libsinsp::events::set<ppm_sc_code> res;
for(const auto &wrap : m_filters)
{
res.insert(wrap->sc_codes.begin(), wrap->sc_codes.end());
}
return res;
}
libsinsp::events::set<ppm_event_code> evttype_index_ruleset::ruleset_filters::event_codes()
{
libsinsp::events::set<ppm_event_code> res;
for(const auto &wrap : m_filters)
{
res.insert(wrap->event_codes.begin(), wrap->event_codes.end());
}
return res;
}
void evttype_index_ruleset::add(
const falco_rule& rule,
std::shared_ptr<sinsp_filter> filter,
std::shared_ptr<libsinsp::filter::ast::expr> condition)
{
try
{
auto wrap = std::make_shared<filter_wrapper>();
wrap->rule = rule;
wrap->filter = filter;
if(rule.source == falco_common::syscall_source)
{
wrap->sc_codes = libsinsp::filter::ast::ppm_sc_codes(condition.get());
wrap->event_codes = libsinsp::filter::ast::ppm_event_codes(condition.get());
}
else
{
wrap->sc_codes = { };
wrap->event_codes = { ppm_event_code::PPME_PLUGINEVENT_E };
}
wrap->event_codes.insert(ppm_event_code::PPME_ASYNCEVENT_E);
m_filters.insert(wrap);
}
catch (const sinsp_exception& e)
{
throw falco_exception(std::string(e.what()));
}
}
void evttype_index_ruleset::on_loading_complete()
{
print_enabled_rules_falco_logger();
}
void evttype_index_ruleset::print_enabled_rules_falco_logger()
{
void evttype_index_ruleset::print_enabled_rules_falco_logger() {
falco_logger::log(falco_logger::level::DEBUG, "Enabled rules:\n");
int n = 0;
for (const auto& ruleset_ptr : m_rulesets)
{
if (ruleset_ptr)
{
for (const auto& wrap : ruleset_ptr->get_filters())
{
n++;
falco_logger::log(falco_logger::level::DEBUG, std::string(" ") + wrap->rule.name + "\n");
}
}
}
falco_logger::log(falco_logger::level::DEBUG, "(" + std::to_string(n) + ") enabled rules in total\n");
}
void evttype_index_ruleset::clear()
{
for (size_t i = 0; i < m_rulesets.size(); i++)
{
m_rulesets[i] = std::make_shared<ruleset_filters>();
}
m_filters.clear();
}
void evttype_index_ruleset::enable(const std::string &pattern, match_type match, uint16_t ruleset_id)
{
enable_disable(pattern, match, true, ruleset_id);
}
void evttype_index_ruleset::disable(const std::string &pattern, match_type match, uint16_t ruleset_id)
{
enable_disable(pattern, match, false, ruleset_id);
}
void evttype_index_ruleset::enable_disable(const std::string &pattern, match_type match, bool enabled, uint16_t ruleset_id)
{
while(m_rulesets.size() < (size_t)ruleset_id + 1)
{
m_rulesets.emplace_back(std::make_shared<ruleset_filters>());
}
for(const auto &wrap : m_filters)
{
bool matches;
std::string::size_type pos;
switch(match)
{
case match_type::exact:
pos = wrap->rule.name.find(pattern);
matches = (pattern == "" || (pos == 0 &&
pattern.size() == wrap->rule.name.size()));
break;
case match_type::substring:
matches = (pattern == "" || (wrap->rule.name.find(pattern) != std::string::npos));
break;
case match_type::wildcard:
matches = falco::utils::matches_wildcard(pattern, wrap->rule.name);
break;
default:
// should never happen
matches = false;
}
if(matches)
{
if(enabled)
{
m_rulesets[ruleset_id]->add_filter(wrap);
}
else
{
m_rulesets[ruleset_id]->remove_filter(wrap);
}
}
}
}
void evttype_index_ruleset::enable_tags(const std::set<std::string> &tags, uint16_t ruleset_id)
{
enable_disable_tags(tags, true, ruleset_id);
}
void evttype_index_ruleset::disable_tags(const std::set<std::string> &tags, uint16_t ruleset_id)
{
enable_disable_tags(tags, false, ruleset_id);
}
void evttype_index_ruleset::enable_disable_tags(const std::set<std::string> &tags, bool enabled, uint16_t ruleset_id)
{
while(m_rulesets.size() < (size_t)ruleset_id + 1)
{
m_rulesets.emplace_back(std::make_shared<ruleset_filters>());
}
for(const auto &wrap : m_filters)
{
std::set<std::string> intersect;
set_intersection(tags.begin(), tags.end(),
wrap->rule.tags.begin(), wrap->rule.tags.end(),
inserter(intersect, intersect.begin()));
if(!intersect.empty())
{
if(enabled)
{
m_rulesets[ruleset_id]->add_filter(wrap);
}
else
{
m_rulesets[ruleset_id]->remove_filter(wrap);
}
}
}
}
uint64_t evttype_index_ruleset::enabled_count(uint16_t ruleset_id)
{
while(m_rulesets.size() < (size_t)ruleset_id + 1)
{
m_rulesets.emplace_back(std::make_shared<ruleset_filters>());
}
return m_rulesets[ruleset_id]->num_filters();
}
bool evttype_index_ruleset::run(sinsp_evt *evt, falco_rule& match, uint16_t ruleset_id)
{
if(m_rulesets.size() < (size_t)ruleset_id + 1)
{
return false;
}
return m_rulesets[ruleset_id]->run(evt, match);
}
bool evttype_index_ruleset::run(sinsp_evt *evt, std::vector<falco_rule>& matches, uint16_t ruleset_id)
{
if(m_rulesets.size() < (size_t)ruleset_id + 1)
{
return false;
}
return m_rulesets[ruleset_id]->run(evt, matches);
}
void evttype_index_ruleset::enabled_evttypes(std::set<uint16_t> &evttypes, uint16_t ruleset_id)
{
evttypes.clear();
for (const auto& e : enabled_event_codes(ruleset_id))
{
evttypes.insert((uint16_t) e);
}
}
libsinsp::events::set<ppm_sc_code> evttype_index_ruleset::enabled_sc_codes(uint16_t ruleset)
{
if(m_rulesets.size() < (size_t)ruleset + 1)
{
return {};
}
return m_rulesets[ruleset]->sc_codes();
}
libsinsp::events::set<ppm_event_code> evttype_index_ruleset::enabled_event_codes(uint16_t ruleset)
{
if(m_rulesets.size() < (size_t)ruleset + 1)
{
return {};
}
return m_rulesets[ruleset]->event_codes();
auto logger = [](std::shared_ptr<evttype_index_wrapper> wrap) {
falco_logger::log(falco_logger::level::DEBUG, std::string(" ") + wrap->name() + "\n");
};
uint64_t num_filters = iterate(logger);
falco_logger::log(falco_logger::level::DEBUG,
"(" + std::to_string(num_filters) + ") enabled rules in total\n");
}

View File

@@ -17,162 +17,65 @@ limitations under the License.
#pragma once
#include "indexable_ruleset.h"
#include <string>
#include <set>
#include <vector>
#include <list>
#include <map>
#include "filter_ruleset.h"
#include <libsinsp/sinsp.h>
#include <libsinsp/filter.h>
#include <libsinsp/event.h>
/*!
\brief A filter_ruleset that indexes enabled rules by event type,
and performs linear search on each event type bucket
\brief A filter_ruleset that indexes enabled rules by event type,
and performs linear search on each event type bucket
*/
class evttype_index_ruleset: public filter_ruleset
{
struct evttype_index_wrapper {
const std::string &name() { return m_rule.name; }
const std::set<std::string> &tags() { return m_rule.tags; }
const libsinsp::events::set<ppm_sc_code> &sc_codes() { return m_sc_codes; }
const libsinsp::events::set<ppm_event_code> &event_codes() { return m_event_codes; }
falco_rule m_rule;
libsinsp::events::set<ppm_sc_code> m_sc_codes;
libsinsp::events::set<ppm_event_code> m_event_codes;
std::shared_ptr<sinsp_filter> m_filter;
};
class evttype_index_ruleset : public indexable_ruleset<evttype_index_wrapper> {
public:
explicit evttype_index_ruleset(std::shared_ptr<sinsp_filter_factory> factory);
virtual ~evttype_index_ruleset();
void add(
const falco_rule& rule,
std::shared_ptr<sinsp_filter> filter,
std::shared_ptr<libsinsp::filter::ast::expr> condition) override;
void clear() override;
bool run(sinsp_evt *evt, falco_rule& match, uint16_t ruleset_id) override;
bool run(sinsp_evt *evt, std::vector<falco_rule>&matches, uint16_t ruleset_id) override;
uint64_t enabled_count(uint16_t ruleset_id) override;
// From filter_ruleset
void add(const falco_rule &rule,
std::shared_ptr<sinsp_filter> filter,
std::shared_ptr<libsinsp::filter::ast::expr> condition) override;
void on_loading_complete() override;
// From indexable_ruleset
bool run_wrappers(sinsp_evt *evt,
filter_wrapper_list &wrappers,
uint16_t ruleset_id,
falco_rule &match) override;
bool run_wrappers(sinsp_evt *evt,
filter_wrapper_list &wrappers,
uint16_t ruleset_id,
std::vector<falco_rule> &matches) override;
// Print each enabled rule when running Falco with falco logger
// log_level=debug; invoked within on_loading_complete()
void print_enabled_rules_falco_logger();
void enable(
const std::string &pattern,
match_type match,
uint16_t rulset_id) override;
void disable(
const std::string &pattern,
match_type match,
uint16_t rulset_id) override;
void enable_tags(
const std::set<std::string> &tags,
uint16_t rulset_id) override;
void disable_tags(
const std::set<std::string> &tags,
uint16_t rulset_id) override;
// note(jasondellaluce): this is deprecated, must use the new
// typing-improved `enabled_event_codes` and `enabled_sc_codes` instead
// todo(jasondellaluce): remove this in future code refactors
void enabled_evttypes(
std::set<uint16_t> &evttypes,
uint16_t ruleset) override;
libsinsp::events::set<ppm_sc_code> enabled_sc_codes(uint16_t ruleset) override;
libsinsp::events::set<ppm_event_code> enabled_event_codes(uint16_t ruleset) override;
private:
// Helper used by enable()/disable()
void enable_disable(
const std::string &pattern,
match_type match,
bool enabled,
uint16_t rulset_id);
// Helper used by enable_tags()/disable_tags()
void enable_disable_tags(
const std::set<std::string> &tags,
bool enabled,
uint16_t rulset_id);
struct filter_wrapper
{
falco_rule rule;
libsinsp::events::set<ppm_sc_code> sc_codes;
libsinsp::events::set<ppm_event_code> event_codes;
std::shared_ptr<sinsp_filter> filter;
};
typedef std::list<std::shared_ptr<filter_wrapper>> filter_wrapper_list;
// A group of filters all having the same ruleset
class ruleset_filters {
public:
ruleset_filters();
virtual ~ruleset_filters();
void add_filter(std::shared_ptr<filter_wrapper> wrap);
void remove_filter(std::shared_ptr<filter_wrapper> wrap);
uint64_t num_filters();
inline const std::set<std::shared_ptr<filter_wrapper>>& get_filters() const
{
return m_filters;
}
// Evaluate an event against the ruleset and return the first rule
// that matched.
bool run(sinsp_evt *evt, falco_rule& match);
// Evaluate an event against the ruleset and return all the
// matching rules.
bool run(sinsp_evt *evt, std::vector<falco_rule>& matches);
libsinsp::events::set<ppm_sc_code> sc_codes();
libsinsp::events::set<ppm_event_code> event_codes();
private:
void add_wrapper_to_list(filter_wrapper_list &wrappers, std::shared_ptr<filter_wrapper> wrap);
void remove_wrapper_from_list(filter_wrapper_list &wrappers, std::shared_ptr<filter_wrapper> wrap);
// Vector indexes from event type to a set of filters. There can
// be multiple filters for a given event type.
// NOTE: This is used only when the event sub-type is 0.
std::vector<filter_wrapper_list> m_filter_by_event_type;
filter_wrapper_list m_filter_all_event_types;
// All filters added. Used to make num_filters() fast.
std::set<std::shared_ptr<filter_wrapper>> m_filters;
};
// Vector indexes from ruleset id to set of rules.
std::vector<std::shared_ptr<ruleset_filters>> m_rulesets;
// All filters added. The set of enabled filters is held in m_rulesets
std::set<std::shared_ptr<filter_wrapper>> m_filters;
std::shared_ptr<sinsp_filter_factory> m_filter_factory;
std::vector<std::string> m_ruleset_names;
};
class evttype_index_ruleset_factory: public filter_ruleset_factory
{
class evttype_index_ruleset_factory : public filter_ruleset_factory {
public:
inline explicit evttype_index_ruleset_factory(
std::shared_ptr<sinsp_filter_factory> factory
): m_filter_factory(factory) { }
inline explicit evttype_index_ruleset_factory(std::shared_ptr<sinsp_filter_factory> factory):
m_filter_factory(factory) {}
inline std::shared_ptr<filter_ruleset> new_ruleset() override
{
inline std::shared_ptr<filter_ruleset> new_ruleset() override {
return std::make_shared<evttype_index_ruleset>(m_filter_factory);
}

View File

@@ -17,83 +17,57 @@ limitations under the License.
#include "falco_common.h"
static std::vector<std::string> priority_names = {
"Emergency",
"Alert",
"Critical",
"Error",
"Warning",
"Notice",
"Informational",
"Debug"
};
static std::vector<std::string> priority_names =
{"Emergency", "Alert", "Critical", "Error", "Warning", "Notice", "Informational", "Debug"};
static std::vector<std::string> rule_matching_names = {
"first",
"all"
};
static std::vector<std::string> rule_matching_names = {"first", "all"};
bool falco_common::parse_priority(const std::string& v, priority_type& out)
{
for (size_t i = 0; i < priority_names.size(); i++)
{
bool falco_common::parse_priority(const std::string& v, priority_type& out) {
for(size_t i = 0; i < priority_names.size(); i++) {
// note: for legacy reasons, "Info" and "Informational" has been used
// interchangeably and ambiguously, so this is the only edge case for
// which we can't apply strict equality check
if (!strcasecmp(v.c_str(), priority_names[i].c_str())
|| (i == PRIORITY_INFORMATIONAL && !strcasecmp(v.c_str(), "info")))
{
out = (priority_type) i;
if(!strcasecmp(v.c_str(), priority_names[i].c_str()) ||
(i == PRIORITY_INFORMATIONAL && !strcasecmp(v.c_str(), "info"))) {
out = (priority_type)i;
return true;
}
}
return false;
}
falco_common::priority_type falco_common::parse_priority(const std::string& v)
{
falco_common::priority_type falco_common::parse_priority(const std::string& v) {
falco_common::priority_type out;
if (!parse_priority(v, out))
{
if(!parse_priority(v, out)) {
throw falco_exception("Unknown priority value: " + v);
}
return out;
}
bool falco_common::format_priority(priority_type v, std::string& out, bool shortfmt)
{
if ((size_t) v < priority_names.size())
{
if (v == PRIORITY_INFORMATIONAL && shortfmt)
{
bool falco_common::format_priority(priority_type v, std::string& out, bool shortfmt) {
if((size_t)v < priority_names.size()) {
if(v == PRIORITY_INFORMATIONAL && shortfmt) {
out = "Info";
}
else
{
out = priority_names[(size_t) v];
} else {
out = priority_names[(size_t)v];
}
return true;
}
return false;
}
std::string falco_common::format_priority(priority_type v, bool shortfmt)
{
std::string falco_common::format_priority(priority_type v, bool shortfmt) {
std::string out;
if(!format_priority(v, out, shortfmt))
{
if(!format_priority(v, out, shortfmt)) {
throw falco_exception("Unknown priority enum value: " + std::to_string(v));
}
return out;
}
bool falco_common::parse_rule_matching(const std::string& v, rule_matching& out)
{
for (size_t i = 0; i < rule_matching_names.size(); i++)
{
if (!strcasecmp(v.c_str(), rule_matching_names[i].c_str()))
{
out = (rule_matching) i;
bool falco_common::parse_rule_matching(const std::string& v, rule_matching& out) {
for(size_t i = 0; i < rule_matching_names.size(); i++) {
if(!strcasecmp(v.c_str(), rule_matching_names[i].c_str())) {
out = (rule_matching)i;
return true;
}
}

View File

@@ -36,39 +36,34 @@ limitations under the License.
// be of this type.
//
struct falco_exception : std::runtime_error
{
struct falco_exception : std::runtime_error {
using std::runtime_error::runtime_error;
};
namespace falco_common
{
namespace falco_common {
const std::string syscall_source = sinsp_syscall_event_source_name;
const std::string syscall_source = sinsp_syscall_event_source_name;
// Same as numbers/indices into the above vector
enum priority_type
{
PRIORITY_EMERGENCY = 0,
PRIORITY_ALERT = 1,
PRIORITY_CRITICAL = 2,
PRIORITY_ERROR = 3,
PRIORITY_WARNING = 4,
PRIORITY_NOTICE = 5,
PRIORITY_INFORMATIONAL = 6,
PRIORITY_DEBUG = 7
};
bool parse_priority(const std::string& v, priority_type& out);
priority_type parse_priority(const std::string& v);
bool format_priority(priority_type v, std::string& out, bool shortfmt=false);
std::string format_priority(priority_type v, bool shortfmt=false);
enum rule_matching
{
FIRST = 0,
ALL = 1
};
bool parse_rule_matching(const std::string& v, rule_matching& out);
// Same as numbers/indices into the above vector
enum priority_type {
PRIORITY_EMERGENCY = 0,
PRIORITY_ALERT = 1,
PRIORITY_CRITICAL = 2,
PRIORITY_ERROR = 3,
PRIORITY_WARNING = 4,
PRIORITY_NOTICE = 5,
PRIORITY_INFORMATIONAL = 6,
PRIORITY_DEBUG = 7
};
bool parse_priority(const std::string& v, priority_type& out);
priority_type parse_priority(const std::string& v);
bool format_priority(priority_type v, std::string& out, bool shortfmt = false);
std::string format_priority(priority_type v, bool shortfmt = false);
enum rule_matching { FIRST = 0, ALL = 1 };
bool parse_rule_matching(const std::string& v, rule_matching& out);
}; // namespace falco_common
typedef std::unordered_map<std::string, std::pair<std::string, bool>> extra_output_field_t;

File diff suppressed because it is too large Load Diff

View File

@@ -41,10 +41,9 @@ limitations under the License.
// handled in a separate class falco_outputs.
//
class falco_engine
{
class falco_engine {
public:
explicit falco_engine(bool seed_rng=true);
explicit falco_engine(bool seed_rng = true);
virtual ~falco_engine();
// A given engine has a version which identifies the fields
@@ -55,10 +54,9 @@ public:
// Engine version used to be represented as a simple progressive
// number. With the new semver schema, the number now represents
// the semver minor number. This function converts the legacy version
// the semver minor number. This function converts the legacy version
// number to the new semver schema.
static inline sinsp_version get_implicit_version(uint32_t minor)
{
static inline sinsp_version get_implicit_version(uint32_t minor) {
return rule_loader::reader::get_implicit_engine_version(minor);
}
@@ -80,7 +78,8 @@ public:
//
// Load rules and returns a result object.
//
std::unique_ptr<falco::load_result> load_rules(const std::string &rules_content, const std::string &name);
std::unique_ptr<falco::load_result> load_rules(const std::string &rules_content,
const std::string &name);
//
// Enable/Disable any rules matching the provided substring.
@@ -91,30 +90,42 @@ public:
// for different sets of rules being active at once.
// The rules are matched against the rulesets of all the defined sources.
//
void enable_rule(const std::string &substring, bool enabled, const std::string &ruleset = s_default_ruleset);
void enable_rule(const std::string &substring,
bool enabled,
const std::string &ruleset = s_default_ruleset);
// Same as above but providing a ruleset id instead
void enable_rule(const std::string &substring, bool enabled, const uint16_t ruleset_id);
// Like enable_rule, but the rule name must be an exact match.
void enable_rule_exact(const std::string &rule_name, bool enabled, const std::string &ruleset = s_default_ruleset);
void enable_rule_exact(const std::string &rule_name,
bool enabled,
const std::string &ruleset = s_default_ruleset);
// Same as above but providing a ruleset id instead
void enable_rule_exact(const std::string &rule_name, bool enabled, const uint16_t ruleset_id);
// Like enable_rule, but wildcards are supported and substrings are not matched
void enable_rule_wildcard(const std::string &rule_name, bool enabled, const std::string &ruleset = s_default_ruleset);
void enable_rule_wildcard(const std::string &rule_name,
bool enabled,
const std::string &ruleset = s_default_ruleset);
// Same as above but providing a ruleset id instead
void enable_rule_wildcard(const std::string &rule_name, bool enabled, const uint16_t ruleset_id);
void enable_rule_wildcard(const std::string &rule_name,
bool enabled,
const uint16_t ruleset_id);
//
// Enable/Disable any rules with any of the provided tags (set, exact matches only)
//
void enable_rule_by_tag(const std::set<std::string> &tags, bool enabled, const std::string &ruleset = s_default_ruleset);
void enable_rule_by_tag(const std::set<std::string> &tags,
bool enabled,
const std::string &ruleset = s_default_ruleset);
// Same as above but providing a ruleset id instead
void enable_rule_by_tag(const std::set<std::string> &tags, bool enabled, const uint16_t ruleset_id);
void enable_rule_by_tag(const std::set<std::string> &tags,
bool enabled,
const uint16_t ruleset_id);
//
// Must be called after the engine has been configured and all rulesets
@@ -147,12 +158,13 @@ public:
// Print details on the given rule. If rule is NULL, print
// details on all rules.
//
nlohmann::json describe_rule(std::string *rule_name, const std::vector<std::shared_ptr<sinsp_plugin>>& plugins) const;
nlohmann::json describe_rule(std::string *rule_name,
const std::vector<std::shared_ptr<sinsp_plugin>> &plugins) const;
//
// Return const /ref to rules stored in the Falco engine.
//
inline const indexed_vector<falco_rule>& get_rules() const { return m_rules; }
inline const indexed_vector<falco_rule> &get_rules() const { return m_rules; }
//
// Print statistics on how many events matched each rule.
@@ -160,9 +172,10 @@ public:
void print_stats() const;
//
// Return const /ref to stats_manager to access current rules stats (how many events matched each rule so far).
// Return const /ref to stats_manager to access current rules stats (how many events matched
// each rule so far).
//
const stats_manager& get_rule_stats_manager() const;
const stats_manager &get_rule_stats_manager() const;
//
// Set the sampling ratio, which can affect which events are
@@ -176,15 +189,34 @@ public:
//
void set_sampling_multiplier(double sampling_multiplier);
//
// You can optionally add "extra" formatting fields to the end
// You can optionally add "extra" output to the end
// of all output expressions. You can also choose to replace
// %container.info with the extra information or add it to the
// end of the expression. This is used in open source falco to
// add k8s/container information to outputs when
// available.
//
void set_extra(const std::string &extra, bool replace_container_info);
void add_extra_output_format(const std::string &format,
const std::string &source,
const std::set<std::string> &tags,
const std::string &rule,
bool replace_container_info);
// You can optionally add fields that will only show up in the object
// output (e.g. json, gRPC) alongside other output_fields
// and not in the text message output.
// You can add two types of fields: formatted which will act like
// an additional output format that appears in the output field
void add_extra_output_formatted_field(const std::string &key,
const std::string &format,
const std::string &source,
const std::set<std::string> &tags,
const std::string &rule);
void add_extra_output_raw_field(const std::string &key,
const std::string &source,
const std::set<std::string> &tags,
const std::string &rule);
// Represents the result of matching an event against a set of
// rules.
@@ -196,6 +228,7 @@ public:
std::string format;
std::set<std::string> exception_fields;
std::set<std::string> tags;
extra_output_field_t extra_output_fields;
};
//
@@ -223,7 +256,9 @@ public:
// concurrently with the same source_idx would inherently cause data races
// and lead to undefined behavior.
std::unique_ptr<std::vector<rule_result>> process_event(std::size_t source_idx,
sinsp_evt *ev, uint16_t ruleset_id, falco_common::rule_matching strategy);
sinsp_evt *ev,
uint16_t ruleset_id,
falco_common::rule_matching strategy);
//
// Wrapper assuming the default ruleset.
@@ -231,7 +266,8 @@ public:
// This inherits the same thread-safety guarantees.
//
std::unique_ptr<std::vector<rule_result>> process_event(std::size_t source_idx,
sinsp_evt *ev, falco_common::rule_matching strategy);
sinsp_evt *ev,
falco_common::rule_matching strategy);
//
// Configure the engine to support events with the provided
@@ -239,17 +275,17 @@ public:
// Return source index for fast lookup.
//
std::size_t add_source(const std::string &source,
std::shared_ptr<sinsp_filter_factory> filter_factory,
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory);
std::shared_ptr<sinsp_filter_factory> filter_factory,
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory);
//
// Equivalent to above, but allows specifying a ruleset factory
// for the newly added source.
//
std::size_t add_source(const std::string &source,
std::shared_ptr<sinsp_filter_factory> filter_factory,
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory,
std::shared_ptr<filter_ruleset_factory> ruleset_factory);
std::shared_ptr<sinsp_filter_factory> filter_factory,
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory,
std::shared_ptr<filter_ruleset_factory> ruleset_factory);
// Return whether or not there is a valid filter/formatter
// factory for this source.
@@ -259,25 +295,27 @@ public:
// Given a source, return a formatter factory that can create
// filters for events of that source.
//
std::shared_ptr<sinsp_filter_factory> filter_factory_for_source(const std::string& source);
std::shared_ptr<sinsp_filter_factory> filter_factory_for_source(const std::string &source);
std::shared_ptr<sinsp_filter_factory> filter_factory_for_source(std::size_t source_idx);
//
// Given a source, return a formatter factory that can create
// formatters for an event.
//
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory_for_source(const std::string& source);
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory_for_source(std::size_t source_idx);
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory_for_source(
const std::string &source);
std::shared_ptr<sinsp_evt_formatter_factory> formatter_factory_for_source(
std::size_t source_idx);
//
// Given a source, return a ruleset factory that can create
// rulesets for that source.
//
std::shared_ptr<filter_ruleset_factory> ruleset_factory_for_source(const std::string& source);
std::shared_ptr<filter_ruleset_factory> ruleset_factory_for_source(const std::string &source);
std::shared_ptr<filter_ruleset_factory> ruleset_factory_for_source(std::size_t source_idx);
// Return the filter_ruleset used for a given source.
std::shared_ptr<filter_ruleset> ruleset_for_source(const std::string& source);
std::shared_ptr<filter_ruleset> ruleset_for_source(const std::string &source);
std::shared_ptr<filter_ruleset> ruleset_for_source(std::size_t source_idx);
//
@@ -288,24 +326,24 @@ public:
// todo(jasondellaluce): remove this in future code refactors
//
void evttypes_for_ruleset(const std::string &source,
std::set<uint16_t> &evttypes,
const std::string &ruleset = s_default_ruleset);
std::set<uint16_t> &evttypes,
const std::string &ruleset = s_default_ruleset);
//
// Given an event source and ruleset, return the set of ppm_sc_codes
// for which this ruleset can run and match events.
//
libsinsp::events::set<ppm_sc_code> sc_codes_for_ruleset(
const std::string &source,
const std::string &ruleset = s_default_ruleset);
const std::string &source,
const std::string &ruleset = s_default_ruleset);
//
// Given an event source and ruleset, return the set of ppm_event_codes
// for which this ruleset can run and match events.
//
libsinsp::events::set<ppm_event_code> event_codes_for_ruleset(
const std::string &source,
const std::string &ruleset = s_default_ruleset);
const std::string &source,
const std::string &ruleset = s_default_ruleset);
//
// Given a source and output string, return an
@@ -313,7 +351,7 @@ public:
// event.
//
std::shared_ptr<sinsp_evt_formatter> create_formatter(const std::string &source,
const std::string &output) const;
const std::string &output) const;
// The rule loader definition is aliased as it is exactly what we need
typedef rule_loader::plugin_version_info::requirement plugin_version_requirement;
@@ -325,47 +363,42 @@ public:
// the name of the plugin and the second element is its version.
// If false is returned, err is filled with error causing the check failure.
//
bool check_plugin_requirements(
const std::vector<plugin_version_requirement>& plugins,
std::string& err) const;
bool check_plugin_requirements(const std::vector<plugin_version_requirement> &plugins,
std::string &err) const;
nlohmann::json m_rule_schema;
private:
// Create a ruleset using the provided factory and set the
// engine state funcs for it.
std::shared_ptr<filter_ruleset> create_ruleset(std::shared_ptr<filter_ruleset_factory>& ruleset_factory);
std::shared_ptr<filter_ruleset> create_ruleset(
std::shared_ptr<filter_ruleset_factory> &ruleset_factory);
// Functions to retrieve state from this engine
void fill_engine_state_funcs(filter_ruleset::engine_state_funcs& engine_state);
void fill_engine_state_funcs(filter_ruleset::engine_state_funcs &engine_state);
filter_ruleset::engine_state_funcs m_engine_state;
// Throws falco_exception if the file can not be read
void read_file(const std::string& filename, std::string& contents);
void read_file(const std::string &filename, std::string &contents);
indexed_vector<falco_source> m_sources;
inline const falco_source* find_source(std::size_t index)
{
inline const falco_source *find_source(std::size_t index) {
const falco_source *source;
if(index == m_syscall_source_idx)
{
if(m_syscall_source == NULL)
{
if(index == m_syscall_source_idx) {
if(m_syscall_source == NULL) {
m_syscall_source = m_sources.at(m_syscall_source_idx);
if(!m_syscall_source)
{
if(!m_syscall_source) {
throw falco_exception("Unknown event source index " + std::to_string(index));
}
}
source = m_syscall_source;
}
else
{
} else {
source = m_sources.at(index);
if(!source)
{
if(!source) {
throw falco_exception("Unknown event source index " + std::to_string(index));
}
}
@@ -373,11 +406,9 @@ private:
return source;
}
inline const falco_source* find_source(const std::string& name) const
{
inline const falco_source *find_source(const std::string &name) const {
auto ret = m_sources.at(name);
if(!ret)
{
if(!ret) {
throw falco_exception("Unknown event source " + name);
}
return ret;
@@ -386,7 +417,7 @@ private:
// To allow the engine to be extremely fast for syscalls (can
// be > 1M events/sec), we save the syscall source/source_idx
// separately and check it explicitly in process_event()
const falco_source* m_syscall_source;
const falco_source *m_syscall_source;
std::atomic<size_t> m_syscall_source_idx;
//
@@ -397,31 +428,26 @@ private:
inline bool should_drop_evt() const;
// Retrieve json details from rules, macros, lists
void get_json_details(
nlohmann::json& out,
const falco_rule& r,
const rule_loader::rule_info& info,
const std::vector<std::shared_ptr<sinsp_plugin>>& plugins) const;
void get_json_details(
nlohmann::json& out,
const falco_macro& m,
const rule_loader::macro_info& info,
const std::vector<std::shared_ptr<sinsp_plugin>>& plugins) const;
void get_json_details(
nlohmann::json& out,
const falco_list& l,
const rule_loader::list_info& info,
const std::vector<std::shared_ptr<sinsp_plugin>>& plugins) const;
void get_json_evt_types(
nlohmann::json& out,
const std::string& source,
libsinsp::filter::ast::expr* ast) const;
void get_json_used_plugins(
nlohmann::json& out,
const std::string& source,
const std::unordered_set<std::string>& evttypes,
const std::unordered_set<std::string>& fields,
const std::vector<std::shared_ptr<sinsp_plugin>>& plugins) const;
void get_json_details(nlohmann::json &out,
const falco_rule &r,
const rule_loader::rule_info &info,
const std::vector<std::shared_ptr<sinsp_plugin>> &plugins) const;
void get_json_details(nlohmann::json &out,
const falco_macro &m,
const rule_loader::macro_info &info,
const std::vector<std::shared_ptr<sinsp_plugin>> &plugins) const;
void get_json_details(nlohmann::json &out,
const falco_list &l,
const rule_loader::list_info &info,
const std::vector<std::shared_ptr<sinsp_plugin>> &plugins) const;
void get_json_evt_types(nlohmann::json &out,
const std::string &source,
libsinsp::filter::ast::expr *ast) const;
void get_json_used_plugins(nlohmann::json &out,
const std::string &source,
const std::unordered_set<std::string> &evttypes,
const std::unordered_set<std::string> &fields,
const std::vector<std::shared_ptr<sinsp_plugin>> &plugins) const;
indexed_vector<falco_rule> m_rules;
std::shared_ptr<rule_loader::reader> m_rule_reader;
@@ -461,6 +487,6 @@ private:
static const std::string s_default_ruleset;
uint32_t m_default_ruleset_id;
std::string m_extra;
bool m_replace_container_info;
std::vector<rule_loader::extra_output_format_conf> m_extra_output_format;
std::vector<rule_loader::extra_output_field_conf> m_extra_output_fields;
};

View File

@@ -20,18 +20,20 @@ limitations under the License.
// The version of this Falco engine
#define FALCO_ENGINE_VERSION_MAJOR 0
#define FALCO_ENGINE_VERSION_MINOR 40
#define FALCO_ENGINE_VERSION_MINOR 43
#define FALCO_ENGINE_VERSION_PATCH 0
#define FALCO_ENGINE_VERSION \
__FALCO_ENGINE_STRINGIFY(FALCO_ENGINE_VERSION_MAJOR) "." \
__FALCO_ENGINE_STRINGIFY(FALCO_ENGINE_VERSION_MINOR) "." \
__FALCO_ENGINE_STRINGIFY(FALCO_ENGINE_VERSION_PATCH)
#define FALCO_ENGINE_VERSION \
__FALCO_ENGINE_STRINGIFY(FALCO_ENGINE_VERSION_MAJOR) \
"." __FALCO_ENGINE_STRINGIFY(FALCO_ENGINE_VERSION_MINOR) "." __FALCO_ENGINE_STRINGIFY( \
FALCO_ENGINE_VERSION_PATCH)
// This is the result of running the following command:
// FALCO="falco -c ./falco.yaml"
// echo $($FALCO --version | grep 'Engine:' | awk '{print $2}') $(echo $($FALCO --version | grep 'Schema version:' | awk '{print $3}') $($FALCO --list --markdown | grep '^`' | sort) $($FALCO --list-events | sort) | sha256sum)
// echo $($FALCO --version | grep 'Engine:' | awk '{print $2}') $(echo $($FALCO --version | grep
// 'Schema version:' | awk '{print $3}') $($FALCO --list --markdown | grep '^`' | sort) $($FALCO
// --list-events | sort) | sha256sum)
// It represents the fields supported by this version of Falco,
// the event types, and the underlying driverevent schema. It's used to
// detetect changes in engine version in our CI jobs.
#define FALCO_ENGINE_CHECKSUM "bc9d0d94ae70ef26b7cf814f62273a48b2bb4133dff0baff5f194f6f1711875a"
#define FALCO_ENGINE_CHECKSUM "8a7f383c1e7682c484096bb6a5cb68c29b818acbe65fa2854acbcc98277fd7e0"

View File

@@ -17,113 +17,110 @@ limitations under the License.
#include "falco_load_result.h"
static const std::string error_codes[] = {
"LOAD_ERR_FILE_READ",
"LOAD_ERR_YAML_PARSE",
"LOAD_ERR_YAML_VALIDATE",
"LOAD_ERR_COMPILE_CONDITION",
"LOAD_ERR_COMPILE_OUTPUT",
"LOAD_ERR_VALIDATE",
"LOAD_ERR_EXTENSION"
};
static const std::string error_codes[] = {"LOAD_ERR_FILE_READ",
"LOAD_ERR_YAML_PARSE",
"LOAD_ERR_YAML_VALIDATE",
"LOAD_ERR_COMPILE_CONDITION",
"LOAD_ERR_COMPILE_OUTPUT",
"LOAD_ERR_VALIDATE",
"LOAD_ERR_EXTENSION"};
const std::string& falco::load_result::error_code_str(error_code ec)
{
const std::string& falco::load_result::error_code_str(error_code ec) {
return error_codes[ec];
}
static const std::string error_strings[] = {
"File read error",
"YAML parse error",
"Error validating internal structure of YAML file",
"Error compiling condition",
"Error compiling output",
"Error validating rule/macro/list/exception objects",
"Error in extension item"
};
static const std::string error_strings[] = {"File read error",
"YAML parse error",
"Error validating internal structure of YAML file",
"Error compiling condition",
"Error compiling output",
"Error validating rule/macro/list/exception objects",
"Error in extension item"};
const std::string& falco::load_result::error_str(error_code ec)
{
const std::string& falco::load_result::error_str(error_code ec) {
return error_strings[ec];
}
static const std::string error_descs[] = {
"This occurs when falco can not read a given file. Check permissions and whether the file exists.",
"This occurs when the rules content is not valid YAML.",
"This occurs when the internal structure of the YAML file is incorrect. Examples include not consisting of a sequence of maps, a given rule/macro/list item not having required keys, values not having the right type (e.g. the items property of a list not being a sequence), etc.",
"This occurs when a condition string can not be compiled to a filter object.",
"This occurs when an output string can not be compiled to an output object.",
"This occurs when a rule/macro/list item is incorrect. Examples include a condition field referring to an undefined macro, falco engine/plugin version mismatches, items with append without any existing item, exception fields/comps having different lengths, etc.",
"This occurs when there is an error in an extension item"
};
"This occurs when falco can not read a given file. Check permissions and whether the file "
"exists.",
"This occurs when the rules content is not valid YAML.",
"This occurs when the internal structure of the YAML file is incorrect. Examples include "
"not consisting of a sequence of maps, a given rule/macro/list item not having required "
"keys, values not having the right type (e.g. the items property of a list not being a "
"sequence), etc.",
"This occurs when a condition string can not be compiled to a filter object.",
"This occurs when an output string can not be compiled to an output object.",
"This occurs when a rule/macro/list item is incorrect. Examples include a condition field "
"referring to an undefined macro, falco engine/plugin version mismatches, items with "
"append without any existing item, exception fields/comps having different lengths, etc.",
"This occurs when there is an error in an extension item"};
const std::string& falco::load_result::error_desc(error_code ec)
{
const std::string& falco::load_result::error_desc(error_code ec) {
return error_strings[ec];
}
static const std::string warning_codes[] = {
"LOAD_UNKNOWN_SOURCE",
"LOAD_UNSAFE_NA_CHECK",
"LOAD_NO_EVTTYPE",
"LOAD_UNKNOWN_FILTER",
"LOAD_UNUSED_MACRO",
"LOAD_UNUSED_LIST",
"LOAD_UNKNOWN_ITEM",
"LOAD_DEPRECATED_ITEM",
"LOAD_WARNING_EXTENSION",
"LOAD_APPEND_NO_VALUES",
"LOAD_EXCEPTION_NAME_NOT_UNIQUE",
"LOAD_INVALID_MACRO_NAME",
"LOAD_INVALID_LIST_NAME",
"LOAD_COMPILE_CONDITION"
};
static const std::string warning_codes[] = {"LOAD_UNKNOWN_SOURCE",
"LOAD_UNSAFE_NA_CHECK",
"LOAD_NO_EVTTYPE",
"LOAD_UNKNOWN_FILTER",
"LOAD_UNUSED_MACRO",
"LOAD_UNUSED_LIST",
"LOAD_UNKNOWN_ITEM",
"LOAD_DEPRECATED_ITEM",
"LOAD_WARNING_EXTENSION",
"LOAD_APPEND_NO_VALUES",
"LOAD_EXCEPTION_NAME_NOT_UNIQUE",
"LOAD_INVALID_MACRO_NAME",
"LOAD_INVALID_LIST_NAME",
"LOAD_COMPILE_CONDITION"};
const std::string& falco::load_result::warning_code_str(warning_code wc)
{
const std::string& falco::load_result::warning_code_str(warning_code wc) {
return warning_codes[wc];
}
static const std::string warning_strings[] = {
"Unknown event source",
"Unsafe <NA> comparison in condition",
"Condition has no event-type restriction",
"Unknown field or event-type in condition or output",
"Unused macro",
"Unused list",
"Unknown rules file item",
"Used deprecated item",
"Warning in extension item",
"Overriding/appending with no values",
"Multiple exceptions defined with the same name",
"Invalid macro name",
"Invalid list name",
"Warning in rule condition"
};
static const std::string warning_strings[] = {"Unknown event source",
"Unsafe <NA> comparison in condition",
"Condition has no event-type restriction",
"Unknown field or event-type in condition or output",
"Unused macro",
"Unused list",
"Unknown rules file item",
"Used deprecated item",
"Warning in extension item",
"Overriding/appending with no values",
"Multiple exceptions defined with the same name",
"Invalid macro name",
"Invalid list name",
"Warning in rule condition"};
const std::string& falco::load_result::warning_str(warning_code wc)
{
const std::string& falco::load_result::warning_str(warning_code wc) {
return warning_strings[wc];
}
static const std::string warning_descs[] = {
"A rule has a unknown event source. This can occur when reading rules content without having a corresponding plugin loaded, etc. The rule will be silently ignored.",
"Comparing a field value with <NA> is unsafe and can lead to unpredictable behavior of the rule condition. If you need to check for the existence of a field, consider using the 'exists' operator instead.",
"A rule condition matches too many evt.type values. This has a significant performance penalty. Make the condition more specific by adding an evt.type field or further restricting the number of evt.type values in the condition.",
"A rule condition or output refers to a field or evt.type that does not exist. This is normally an error, but if a rule has a skip-if-unknown-filter property, the error is downgraded to a warning.",
"A macro is defined in the rules content but is not used by any other macro or rule.",
"A list is defined in the rules content but is not used by any other list, macro, or rule.",
"An unknown top-level object is in the rules content. It will be ignored.",
"A deprecated item is employed by lists, macros, or rules.",
"An extension item has a warning",
"A rule exception is overriding/appending with no values",
"A rule is defining multiple exceptions with the same name",
"A macro is defined with an invalid name",
"A list is defined with an invalid name",
"A rule condition or output have been parsed with a warning"
};
"A rule has a unknown event source. This can occur when reading rules content without "
"having a corresponding plugin loaded, etc. The rule will be silently ignored.",
"Comparing a field value with <NA> is unsafe and can lead to unpredictable behavior of the "
"rule condition. If you need to check for the existence of a field, consider using the "
"'exists' operator instead.",
"A rule condition matches too many evt.type values. This has a significant performance "
"penalty. Make the condition more specific by adding an evt.type field or further "
"restricting the number of evt.type values in the condition.",
"A rule condition or output refers to a field or evt.type that does not exist. This is "
"normally an error, but if a rule has a skip-if-unknown-filter property, the error is "
"downgraded to a warning.",
"A macro is defined in the rules content but is not used by any other macro or rule.",
"A list is defined in the rules content but is not used by any other list, macro, or rule.",
"An unknown top-level object is in the rules content. It will be ignored.",
"A deprecated item is employed by lists, macros, or rules.",
"An extension item has a warning",
"A rule exception is overriding/appending with no values",
"A rule is defining multiple exceptions with the same name",
"A macro is defined with an invalid name",
"A list is defined with an invalid name",
"A rule condition or output have been parsed with a warning"};
const std::string& falco::load_result::warning_desc(warning_code wc)
{
const std::string& falco::load_result::warning_desc(warning_code wc) {
return warning_descs[wc];
}

View File

@@ -21,13 +21,11 @@ limitations under the License.
#include <string>
#include <nlohmann/json.hpp>
namespace falco
{
namespace falco {
// Represents the result of loading a rules file.
class load_result {
public:
enum error_code {
LOAD_ERR_FILE_READ = 0,
LOAD_ERR_YAML_PARSE,
@@ -87,6 +85,9 @@ public:
// has_warnings() can both be true if there were only warnings.
virtual bool has_warnings() = 0;
// Return json schema validation status.
virtual std::string schema_validation() = 0;
// This represents a set of rules contents as a mapping from
// rules content name (usually filename) to rules content. The
// rules content is actually a reference to the actual string
@@ -118,4 +119,4 @@ public:
virtual const nlohmann::json& as_json(const rules_contents_t& contents) = 0;
};
} // namespace falco
} // namespace falco

View File

@@ -24,16 +24,15 @@ limitations under the License.
#include <libsinsp/filter/ast.h>
/*!
\brief Represents a list in the Falco Engine.
The rule ID must be unique across all the lists loaded in the engine.
\brief Represents a list in the Falco Engine.
The rule ID must be unique across all the lists loaded in the engine.
*/
struct falco_list
{
falco_list(): used(false), id(0) { }
struct falco_list {
falco_list(): used(false), id(0) {}
falco_list(falco_list&&) = default;
falco_list& operator = (falco_list&&) = default;
falco_list& operator=(falco_list&&) = default;
falco_list(const falco_list&) = default;
falco_list& operator = (const falco_list&) = default;
falco_list& operator=(const falco_list&) = default;
~falco_list() = default;
bool used;
@@ -43,16 +42,15 @@ struct falco_list
};
/*!
\brief Represents a macro in the Falco Engine.
The rule ID must be unique across all the macros loaded in the engine.
\brief Represents a macro in the Falco Engine.
The rule ID must be unique across all the macros loaded in the engine.
*/
struct falco_macro
{
falco_macro(): used(false), id(0) { }
struct falco_macro {
falco_macro(): used(false), id(0) {}
falco_macro(falco_macro&&) = default;
falco_macro& operator = (falco_macro&&) = default;
falco_macro& operator=(falco_macro&&) = default;
falco_macro(const falco_macro&) = default;
falco_macro& operator = (const falco_macro&) = default;
falco_macro& operator=(const falco_macro&) = default;
~falco_macro() = default;
bool used;
@@ -62,16 +60,15 @@ struct falco_macro
};
/*!
\brief Represents a rule in the Falco Engine.
The rule ID must be unique across all the rules loaded in the engine.
\brief Represents a rule in the Falco Engine.
The rule ID must be unique across all the rules loaded in the engine.
*/
struct falco_rule
{
struct falco_rule {
falco_rule(): id(0), priority(falco_common::PRIORITY_DEBUG) {}
falco_rule(falco_rule&&) = default;
falco_rule& operator = (falco_rule&&) = default;
falco_rule& operator=(falco_rule&&) = default;
falco_rule(const falco_rule&) = default;
falco_rule& operator = (const falco_rule&) = default;
falco_rule& operator=(const falco_rule&) = default;
~falco_rule() = default;
std::size_t id;
@@ -79,6 +76,7 @@ struct falco_rule
std::string name;
std::string description;
std::string output;
extra_output_field_t extra_output_fields;
std::set<std::string> tags;
std::set<std::string> exception_fields;
falco_common::priority_type priority;

View File

@@ -21,23 +21,21 @@ limitations under the License.
#include "filter_ruleset.h"
/*!
\brief Represents a given data source used by the engine.
The ruleset of a source should be created through the ruleset factory
of the same data source.
\brief Represents a given data source used by the engine.
The ruleset of a source should be created through the ruleset factory
of the same data source.
*/
struct falco_source
{
struct falco_source {
falco_source() = default;
falco_source(falco_source&&) = default;
falco_source& operator = (falco_source&&) = default;
falco_source& operator=(falco_source&&) = default;
falco_source(const falco_source& s):
name(s.name),
ruleset(s.ruleset),
ruleset_factory(s.ruleset_factory),
filter_factory(s.filter_factory),
formatter_factory(s.formatter_factory) { };
falco_source& operator = (const falco_source& s)
{
name(s.name),
ruleset(s.ruleset),
ruleset_factory(s.ruleset_factory),
filter_factory(s.filter_factory),
formatter_factory(s.formatter_factory) {};
falco_source& operator=(const falco_source& s) {
name = s.name;
ruleset = s.ruleset;
ruleset_factory = s.ruleset_factory;
@@ -56,24 +54,19 @@ struct falco_source
// matches an event.
mutable std::vector<falco_rule> m_rules;
inline bool is_valid_lhs_field(const std::string& field) const
{
inline bool is_valid_lhs_field(const std::string& field) const {
// if there's at least one parenthesis we may be parsing a field
// wrapped inside one or more transformers. In those cases, the most
// rigorous analysis we can do is compiling a simple filter using
// the field as left-hand side of a comparison, and see if any error
// occurs.
if (field.find('(') != std::string::npos)
{
try
{
if(field.find('(') != std::string::npos) {
try {
auto filter = field;
filter.append(" exists");
sinsp_filter_compiler(filter_factory, filter).compile();
return true;
}
catch (...)
{
} catch(...) {
return false;
}
}

View File

@@ -30,19 +30,22 @@ limitations under the License.
#include <iomanip>
#include <thread>
#define RGX_PROMETHEUS_TIME_DURATION "^((?P<y>[0-9]+)y)?((?P<w>[0-9]+)w)?((?P<d>[0-9]+)d)?((?P<h>[0-9]+)h)?((?P<m>[0-9]+)m)?((?P<s>[0-9]+)s)?((?P<ms>[0-9]+)ms)?$"
#define RGX_PROMETHEUS_TIME_DURATION \
"^((?P<y>[0-9]+)y)?((?P<w>[0-9]+)w)?((?P<d>[0-9]+)d)?((?P<h>[0-9]+)h)?((?P<m>[0-9]+)m)?((?P<" \
"s>[0-9]+)s)?((?P<ms>[0-9]+)ms)?$"
// using pre-compiled regex
static re2::RE2 s_rgx_prometheus_time_duration(RGX_PROMETHEUS_TIME_DURATION);
// Prometheus time durations: https://prometheus.io/docs/prometheus/latest/querying/basics/#time-durations
#define PROMETHEUS_UNIT_Y "y" ///> assuming a year has always 365d
#define PROMETHEUS_UNIT_W "w" ///> assuming a week has always 7d
#define PROMETHEUS_UNIT_D "d" ///> assuming a day has always 24h
#define PROMETHEUS_UNIT_H "h" ///> hour
#define PROMETHEUS_UNIT_M "m" ///> minute
#define PROMETHEUS_UNIT_S "s" ///> second
#define PROMETHEUS_UNIT_MS "ms" ///> millisecond
// Prometheus time durations:
// https://prometheus.io/docs/prometheus/latest/querying/basics/#time-durations
#define PROMETHEUS_UNIT_Y "y" ///> assuming a year has always 365d
#define PROMETHEUS_UNIT_W "w" ///> assuming a week has always 7d
#define PROMETHEUS_UNIT_D "d" ///> assuming a day has always 24h
#define PROMETHEUS_UNIT_H "h" ///> hour
#define PROMETHEUS_UNIT_M "m" ///> minute
#define PROMETHEUS_UNIT_S "s" ///> second
#define PROMETHEUS_UNIT_MS "ms" ///> millisecond
// standard time unit conversions to milliseconds
#define ONE_MS_TO_MS 1UL
@@ -53,20 +56,17 @@ static re2::RE2 s_rgx_prometheus_time_duration(RGX_PROMETHEUS_TIME_DURATION);
#define ONE_WEEK_TO_MS ONE_DAY_TO_MS * 7UL
#define ONE_YEAR_TO_MS ONE_DAY_TO_MS * 365UL
namespace falco
{
namespace falco {
namespace utils
{
namespace utils {
uint64_t parse_prometheus_interval(std::string interval_str)
{
uint64_t parse_prometheus_interval(std::string interval_str) {
uint64_t interval = 0;
/* Sanitize user input, remove possible whitespaces. */
interval_str.erase(remove_if(interval_str.begin(), interval_str.end(), isspace), interval_str.end());
interval_str.erase(remove_if(interval_str.begin(), interval_str.end(), isspace),
interval_str.end());
if(!interval_str.empty())
{
if(!interval_str.empty()) {
re2::StringPiece input(interval_str);
std::string args[14];
re2::RE2::Arg arg0(&args[0]);
@@ -83,34 +83,52 @@ uint64_t parse_prometheus_interval(std::string interval_str)
re2::RE2::Arg arg11(&args[11]);
re2::RE2::Arg arg12(&args[12]);
re2::RE2::Arg arg13(&args[13]);
const re2::RE2::Arg* const matches[14] = {&arg0, &arg1, &arg2, &arg3, &arg4, &arg5, &arg6, &arg7, &arg8, &arg9, &arg10, &arg11, &arg12, &arg13};
const re2::RE2::Arg* const matches[14] = {&arg0,
&arg1,
&arg2,
&arg3,
&arg4,
&arg5,
&arg6,
&arg7,
&arg8,
&arg9,
&arg10,
&arg11,
&arg12,
&arg13};
const std::map<std::string, int>& named_groups = s_rgx_prometheus_time_duration.NamedCapturingGroups();
const std::map<std::string, int>& named_groups =
s_rgx_prometheus_time_duration.NamedCapturingGroups();
int num_groups = s_rgx_prometheus_time_duration.NumberOfCapturingGroups();
re2::RE2::FullMatchN(input, s_rgx_prometheus_time_duration, matches, num_groups);
static const char* all_prometheus_units[7] = {
PROMETHEUS_UNIT_Y, PROMETHEUS_UNIT_W, PROMETHEUS_UNIT_D, PROMETHEUS_UNIT_H,
PROMETHEUS_UNIT_M, PROMETHEUS_UNIT_S, PROMETHEUS_UNIT_MS };
static const char* all_prometheus_units[7] = {PROMETHEUS_UNIT_Y,
PROMETHEUS_UNIT_W,
PROMETHEUS_UNIT_D,
PROMETHEUS_UNIT_H,
PROMETHEUS_UNIT_M,
PROMETHEUS_UNIT_S,
PROMETHEUS_UNIT_MS};
static const uint64_t all_prometheus_time_conversions[7] = {
ONE_YEAR_TO_MS, ONE_WEEK_TO_MS, ONE_DAY_TO_MS, ONE_HOUR_TO_MS,
ONE_MINUTE_TO_MS, ONE_SECOND_TO_MS, ONE_MS_TO_MS };
static const uint64_t all_prometheus_time_conversions[7] = {ONE_YEAR_TO_MS,
ONE_WEEK_TO_MS,
ONE_DAY_TO_MS,
ONE_HOUR_TO_MS,
ONE_MINUTE_TO_MS,
ONE_SECOND_TO_MS,
ONE_MS_TO_MS};
for(size_t i = 0; i < sizeof(all_prometheus_units) / sizeof(const char*); i++)
{
for(size_t i = 0; i < sizeof(all_prometheus_units) / sizeof(const char*); i++) {
std::string cur_interval_str;
uint64_t cur_interval = 0;
const auto &group_it = named_groups.find(all_prometheus_units[i]);
if(group_it != named_groups.end())
{
const auto& group_it = named_groups.find(all_prometheus_units[i]);
if(group_it != named_groups.end()) {
cur_interval_str = args[group_it->second - 1];
if(!cur_interval_str.empty())
{
if(!cur_interval_str.empty()) {
cur_interval = std::stoull(cur_interval_str, nullptr, 0);
}
if(cur_interval > 0)
{
if(cur_interval > 0) {
interval += cur_interval * all_prometheus_time_conversions[i];
}
}
@@ -120,11 +138,9 @@ uint64_t parse_prometheus_interval(std::string interval_str)
}
#if defined(__linux__) and !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__)
std::string calculate_file_sha256sum(const std::string& filename)
{
std::string calculate_file_sha256sum(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open())
{
if(!file.is_open()) {
return "";
}
@@ -133,8 +149,7 @@ std::string calculate_file_sha256sum(const std::string& filename)
constexpr size_t buffer_size = 4096;
char buffer[buffer_size];
while (file.read(buffer, buffer_size))
{
while(file.read(buffer, buffer_size)) {
SHA256_Update(&sha256_context, buffer, buffer_size);
}
SHA256_Update(&sha256_context, buffer, file.gcount());
@@ -143,40 +158,32 @@ std::string calculate_file_sha256sum(const std::string& filename)
SHA256_Final(digest, &sha256_context);
std::stringstream ss;
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i)
{
for(int i = 0; i < SHA256_DIGEST_LENGTH; ++i) {
ss << std::hex << std::setw(2) << std::setfill('0') << static_cast<unsigned>(digest[i]);
}
return ss.str();
}
#endif
std::string sanitize_metric_name(const std::string& name)
{
std::string sanitize_rule_name(const std::string& name) {
std::string sanitized_name = name;
RE2::GlobalReplace(&sanitized_name, "[^a-zA-Z0-9_:]", "_");
RE2::GlobalReplace(&sanitized_name, "_+", "_");
if (!sanitized_name.empty() && sanitized_name.back() == '_')
{
if(!sanitized_name.empty() && sanitized_name.back() == '_') {
sanitized_name.pop_back();
}
return sanitized_name;
}
std::string wrap_text(const std::string& in, uint32_t indent, uint32_t line_len)
{
std::string wrap_text(const std::string& in, uint32_t indent, uint32_t line_len) {
std::istringstream is(in);
std::ostringstream os;
std::string word;
uint32_t len = 0;
while (is >> word)
{
if((len + word.length() + 1) <= (line_len-indent))
{
while(is >> word) {
if((len + word.length() + 1) <= (line_len - indent)) {
len += word.length() + 1;
}
else
{
} else {
os << std::endl;
os << std::left << std::setw(indent) << " ";
len = word.length() + 1;
@@ -186,18 +193,15 @@ std::string wrap_text(const std::string& in, uint32_t indent, uint32_t line_len)
return os.str();
}
uint32_t hardware_concurrency()
{
uint32_t hardware_concurrency() {
auto hc = std::thread::hardware_concurrency();
return hc ? hc : 1;
}
void readfile(const std::string& filename, std::string& data)
{
void readfile(const std::string& filename, std::string& data) {
std::ifstream file(filename, std::ios::in);
if(file.is_open())
{
if(file.is_open()) {
std::stringstream ss;
ss << file.rdbuf();
@@ -209,22 +213,18 @@ void readfile(const std::string& filename, std::string& data)
return;
}
bool matches_wildcard(const std::string &pattern, const std::string &s)
{
bool matches_wildcard(const std::string& pattern, const std::string& s) {
std::string::size_type star_pos = pattern.find("*");
if(star_pos == std::string::npos)
{
if(star_pos == std::string::npos) {
// regular match (no wildcards)
return pattern == s;
}
if(star_pos == 0)
{
if(star_pos == 0) {
// wildcard at the beginning "*something*..."
std::string::size_type next_pattern_start = pattern.find_first_not_of("*");
if(next_pattern_start == std::string::npos)
{
if(next_pattern_start == std::string::npos) {
// pattern was just a sequence of stars *, **, ***, ... . This always matches.
return true;
}
@@ -232,18 +232,16 @@ bool matches_wildcard(const std::string &pattern, const std::string &s)
std::string next_pattern = pattern.substr(next_pattern_start);
std::string to_find = next_pattern.substr(0, next_pattern.find("*"));
std::string::size_type lit_pos = s.find(to_find);
if(lit_pos == std::string::npos)
{
if(lit_pos == std::string::npos) {
return false;
}
return matches_wildcard(next_pattern.substr(to_find.size()), s.substr(lit_pos + to_find.size()));
} else
{
return matches_wildcard(next_pattern.substr(to_find.size()),
s.substr(lit_pos + to_find.size()));
} else {
// wildcard at the end or in the middle "something*else*..."
if(pattern.substr(0, star_pos) != s.substr(0, star_pos))
{
if(pattern.substr(0, star_pos) != s.substr(0, star_pos)) {
return false;
}
@@ -251,12 +249,10 @@ bool matches_wildcard(const std::string &pattern, const std::string &s)
}
}
namespace network
{
bool is_unix_scheme(const std::string& url)
{
namespace network {
bool is_unix_scheme(const std::string& url) {
return sinsp_utils::startswith(url, UNIX_SCHEME);
}
} // namespace network
} // namespace utils
} // namespace falco
} // namespace network
} // namespace utils
} // namespace falco

View File

@@ -23,15 +23,14 @@ limitations under the License.
#include <cstdint>
#include <string>
namespace falco::utils
{
namespace falco::utils {
uint64_t parse_prometheus_interval(std::string interval_str);
#if defined(__linux__) and !defined(MINIMAL_BUILD) and !defined(__EMSCRIPTEN__)
std::string calculate_file_sha256sum(const std::string& filename);
#endif
std::string sanitize_metric_name(const std::string& name);
std::string sanitize_rule_name(const std::string& name);
std::string wrap_text(const std::string& in, uint32_t indent, uint32_t linelen);
@@ -39,11 +38,10 @@ void readfile(const std::string& filename, std::string& data);
uint32_t hardware_concurrency();
bool matches_wildcard(const std::string &pattern, const std::string &s);
bool matches_wildcard(const std::string& pattern, const std::string& s);
namespace network
{
namespace network {
static const std::string UNIX_SCHEME("unix://");
bool is_unix_scheme(const std::string& url);
} // namespace network
} // namespace falco::utils
} // namespace network
} // namespace falco::utils

View File

@@ -21,18 +21,15 @@ limitations under the License.
using namespace libsinsp::filter;
static inline std::string get_field_name(const std::string& name, const std::string& arg)
{
static inline std::string get_field_name(const std::string& name, const std::string& arg) {
std::string fld = name;
if (!arg.empty())
{
if(!arg.empty()) {
fld += "[" + arg + "]";
}
return fld;
}
void filter_details::reset()
{
void filter_details::reset() {
fields.clear();
macros.clear();
operators.clear();
@@ -41,114 +38,92 @@ void filter_details::reset()
transformers.clear();
}
void filter_details_resolver::run(ast::expr* filter, filter_details& details)
{
void filter_details_resolver::run(ast::expr* filter, filter_details& details) {
visitor v(details);
filter->accept(&v);
}
void filter_details_resolver::visitor::visit(ast::and_expr* e)
{
for(size_t i = 0; i < e->children.size(); i++)
{
void filter_details_resolver::visitor::visit(ast::and_expr* e) {
for(size_t i = 0; i < e->children.size(); i++) {
e->children[i]->accept(this);
}
}
void filter_details_resolver::visitor::visit(ast::or_expr* e)
{
for(size_t i = 0; i < e->children.size(); i++)
{
void filter_details_resolver::visitor::visit(ast::or_expr* e) {
for(size_t i = 0; i < e->children.size(); i++) {
e->children[i]->accept(this);
}
}
void filter_details_resolver::visitor::visit(ast::not_expr* e)
{
void filter_details_resolver::visitor::visit(ast::not_expr* e) {
e->child->accept(this);
}
void filter_details_resolver::visitor::visit(ast::list_expr* e)
{
if(m_expect_list)
{
for(const auto& item : e->values)
{
if(m_details.known_lists.find(item) != m_details.known_lists.end())
{
void filter_details_resolver::visitor::visit(ast::list_expr* e) {
if(m_expect_list) {
for(const auto& item : e->values) {
if(m_details.known_lists.find(item) != m_details.known_lists.end()) {
m_details.lists.insert(item);
}
}
}
if (m_expect_evtname)
{
for(const auto& item : e->values)
{
if(m_details.known_lists.find(item) == m_details.known_lists.end())
{
if(m_expect_evtname) {
for(const auto& item : e->values) {
if(m_details.known_lists.find(item) == m_details.known_lists.end()) {
m_details.evtnames.insert(item);
}
}
}
}
void filter_details_resolver::visitor::visit(ast::binary_check_expr* e)
{
void filter_details_resolver::visitor::visit(ast::binary_check_expr* e) {
m_last_node_field_name.clear();
m_expect_evtname = false;
m_expect_list = false;
e->left->accept(this);
if (m_last_node_field_name.empty())
{
if(m_last_node_field_name.empty()) {
throw std::runtime_error("can't find field info in binary check expression");
}
m_details.operators.insert(e->op);
m_expect_list = true;
m_expect_evtname = m_last_node_field_name == "evt.type" || m_last_node_field_name == "evt.asynctype";
m_expect_evtname =
m_last_node_field_name == "evt.type" || m_last_node_field_name == "evt.asynctype";
e->right->accept(this);
m_expect_evtname = false;
m_expect_list = false;
}
void filter_details_resolver::visitor::visit(ast::unary_check_expr* e)
{
void filter_details_resolver::visitor::visit(ast::unary_check_expr* e) {
m_last_node_field_name.clear();
e->left->accept(this);
if (m_last_node_field_name.empty())
{
if(m_last_node_field_name.empty()) {
throw std::runtime_error("can't find field info in unary check expression");
}
m_details.fields.insert(m_last_node_field_name);
m_details.operators.insert(e->op);
}
void filter_details_resolver::visitor::visit(ast::identifier_expr* e)
{
void filter_details_resolver::visitor::visit(ast::identifier_expr* e) {
// todo(jasondellaluce): maybe throw an error if we encounter an unknown macro?
if(m_details.known_macros.find(e->identifier) != m_details.known_macros.end())
{
if(m_details.known_macros.find(e->identifier) != m_details.known_macros.end()) {
m_details.macros.insert(e->identifier);
}
}
void filter_details_resolver::visitor::visit(ast::value_expr* e)
{
if (m_expect_evtname)
{
void filter_details_resolver::visitor::visit(ast::value_expr* e) {
if(m_expect_evtname) {
m_details.evtnames.insert(e->value);
}
}
void filter_details_resolver::visitor::visit(ast::field_expr* e)
{
void filter_details_resolver::visitor::visit(ast::field_expr* e) {
m_last_node_field_name = get_field_name(e->field, e->arg);
m_details.fields.insert(m_last_node_field_name);
}
void filter_details_resolver::visitor::visit(ast::field_transformer_expr* e)
{
void filter_details_resolver::visitor::visit(ast::field_transformer_expr* e) {
m_details.transformers.insert(e->transformer);
e->value->accept(this);
}

View File

@@ -22,8 +22,7 @@ limitations under the License.
#include <unordered_set>
#include <unordered_map>
struct filter_details
{
struct filter_details {
// input macros and lists
std::unordered_set<std::string> known_macros;
std::unordered_set<std::string> known_lists;
@@ -40,29 +39,26 @@ struct filter_details
};
/*!
\brief Helper class for getting details about rules' filters.
\brief Helper class for getting details about rules' filters.
*/
class filter_details_resolver
{
class filter_details_resolver {
public:
/*!
\brief Visits a filter AST and stores details about macros, lists,
fields and operators used.
\param filter The filter AST to be processed.
\param details Helper structure used to state known macros and
lists on input, and to store all the retrieved details as output.
\brief Visits a filter AST and stores details about macros, lists,
fields and operators used.
\param filter The filter AST to be processed.
\param details Helper structure used to state known macros and
lists on input, and to store all the retrieved details as output.
*/
void run(libsinsp::filter::ast::expr* filter,
filter_details& details);
void run(libsinsp::filter::ast::expr* filter, filter_details& details);
private:
struct visitor : public libsinsp::filter::ast::expr_visitor
{
explicit visitor(filter_details& details) :
m_details(details),
m_expect_list(false),
m_expect_evtname(false),
m_last_node_field_name() {}
struct visitor : public libsinsp::filter::ast::expr_visitor {
explicit visitor(filter_details& details):
m_details(details),
m_expect_list(false),
m_expect_evtname(false),
m_last_node_field_name() {}
visitor(visitor&&) = default;
visitor(const visitor&) = delete;

View File

@@ -20,8 +20,7 @@ limitations under the License.
using namespace libsinsp::filter;
bool filter_macro_resolver::run(std::shared_ptr<libsinsp::filter::ast::expr>& filter)
{
bool filter_macro_resolver::run(std::shared_ptr<libsinsp::filter::ast::expr>& filter) {
m_unknown_macros.clear();
m_resolved_macros.clear();
m_errors.clear();
@@ -29,110 +28,90 @@ bool filter_macro_resolver::run(std::shared_ptr<libsinsp::filter::ast::expr>& fi
visitor v(m_errors, m_unknown_macros, m_resolved_macros, m_macros);
v.m_node_substitute = nullptr;
filter->accept(&v);
if (v.m_node_substitute)
{
if(v.m_node_substitute) {
filter = std::move(v.m_node_substitute);
}
return !m_resolved_macros.empty();
}
void filter_macro_resolver::set_macro(
const std::string& name,
const std::shared_ptr<libsinsp::filter::ast::expr>& macro)
{
void filter_macro_resolver::set_macro(const std::string& name,
const std::shared_ptr<libsinsp::filter::ast::expr>& macro) {
m_macros[name] = macro;
}
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_unknown_macros() const
{
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_unknown_macros()
const {
return m_unknown_macros;
}
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_errors() const
{
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_errors() const {
return m_errors;
}
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_resolved_macros() const
{
const std::vector<filter_macro_resolver::value_info>& filter_macro_resolver::get_resolved_macros()
const {
return m_resolved_macros;
}
void filter_macro_resolver::visitor::visit(ast::and_expr* e)
{
for (size_t i = 0; i < e->children.size(); i++)
{
void filter_macro_resolver::visitor::visit(ast::and_expr* e) {
for(size_t i = 0; i < e->children.size(); i++) {
e->children[i]->accept(this);
if (m_node_substitute)
{
if(m_node_substitute) {
e->children[i] = std::move(m_node_substitute);
}
}
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::or_expr* e)
{
for (size_t i = 0; i < e->children.size(); i++)
{
void filter_macro_resolver::visitor::visit(ast::or_expr* e) {
for(size_t i = 0; i < e->children.size(); i++) {
e->children[i]->accept(this);
if (m_node_substitute)
{
if(m_node_substitute) {
e->children[i] = std::move(m_node_substitute);
}
}
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::not_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::not_expr* e) {
e->child->accept(this);
if (m_node_substitute)
{
if(m_node_substitute) {
e->child = std::move(m_node_substitute);
}
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::list_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::list_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::binary_check_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::binary_check_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::unary_check_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::unary_check_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::value_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::value_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::field_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::field_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::field_transformer_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::field_transformer_expr* e) {
m_node_substitute = nullptr;
}
void filter_macro_resolver::visitor::visit(ast::identifier_expr* e)
{
void filter_macro_resolver::visitor::visit(ast::identifier_expr* e) {
const auto& macro = m_macros.find(e->identifier);
if (macro != m_macros.end() && macro->second) // skip null-ptr macros
if(macro != m_macros.end() && macro->second) // skip null-ptr macros
{
// note: checks for loop detection
const auto& prevref = std::find(m_macros_path.begin(), m_macros_path.end(), macro->first);
if (prevref != m_macros_path.end())
{
if(prevref != m_macros_path.end()) {
auto msg = "reference loop in macro '" + macro->first + "'";
m_errors.push_back({msg, e->get_pos()});
m_node_substitute = nullptr;
@@ -146,15 +125,12 @@ void filter_macro_resolver::visitor::visit(ast::identifier_expr* e)
new_node->accept(this);
// new_node might already have set a non-NULL m_node_substitute.
// if not, the right substituted is the newly-cloned node.
if (!m_node_substitute)
{
if(!m_node_substitute) {
m_node_substitute = std::move(new_node);
}
m_resolved_macros.push_back({e->identifier, e->get_pos()});
m_macros_path.pop_back();
}
else
{
} else {
m_node_substitute = nullptr;
m_unknown_macros.push_back({e->identifier, e->get_pos()});
}

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