diff --git a/.CFVERSION b/.CFVERSION index 954e228821..77a8973e74 100644 --- a/.CFVERSION +++ b/.CFVERSION @@ -1 +1 @@ -3.24.0 +3.24.5 diff --git a/.github/workflows/acceptance_tests.yml b/.github/workflows/acceptance_tests.yml index 9eac099968..62a8818aa2 100644 --- a/.github/workflows/acceptance_tests.yml +++ b/.github/workflows/acceptance_tests.yml @@ -5,7 +5,7 @@ on: jobs: acceptance_tests: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 with: diff --git a/.github/workflows/asan_unit_tests.yml b/.github/workflows/asan_unit_tests.yml index 9f7ba2076e..5de1588c8a 100644 --- a/.github/workflows/asan_unit_tests.yml +++ b/.github/workflows/asan_unit_tests.yml @@ -5,7 +5,7 @@ on: jobs: asan_unit_tests: - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 with: @@ -15,6 +15,6 @@ jobs: - name: Run autotools / configure run: ./autogen.sh --enable-debug - name: Compile and link (make) - run: make -j8 CFLAGS="-Werror -Wall -fsanitize=address" LDFLAGS="-fsanitize=address" + run: make -j8 CFLAGS="-Werror -Wall -Wextra -Wno-sign-compare -fsanitize=address" LDFLAGS="-fsanitize=address" - name: Run unit tests run: make -C tests/unit CFLAGS="-fsanitize=address" LDFLAGS="-fsanitize=address" check diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1987d4a14a..05ad8fbd5c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,7 +4,7 @@ on: # run this workflow on pull_request activity # this includes opening and pushing more commits pull_request: - branches: [ master, 3.21.x, 3.18.x ] + branches: [ master, 3.24.x, 3.21.x ] jobs: unit_tests: @@ -17,9 +17,6 @@ jobs: acceptance_tests: needs: unit_tests uses: ./.github/workflows/acceptance_tests.yml - windows_acceptance_tests: - needs: unit_tests - uses: ./.github/workflows/windows_acceptance_tests.yml macos_unit_tests: needs: unit_tests uses: ./.github/workflows/macos_unit_tests.yml diff --git a/.github/workflows/job-static-check.yml b/.github/workflows/job-static-check.yml index a86a5836f8..3b265a0a91 100644 --- a/.github/workflows/job-static-check.yml +++ b/.github/workflows/job-static-check.yml @@ -5,7 +5,7 @@ on: jobs: static_check: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout Core uses: actions/checkout@v3 @@ -38,13 +38,7 @@ jobs: - name: Prepare Environment run: | sudo apt-get update && \ - sudo apt-get install -y dpkg-dev debhelper g++ libncurses5 pkg-config \ - build-essential libpam0g-dev fakeroot gcc make autoconf buildah \ - liblmdb-dev libacl1-dev libcurl4-openssl-dev libyaml-dev libxml2-dev \ - libssl-dev libpcre2-dev - - - name: Run Autogen - run: NO_CONFIGURE=1 PROJECT=community ./buildscripts/build-scripts/autogen + sudo apt-get install -y buildah - name: Run The Test working-directory: ./core diff --git a/.github/workflows/macos_unit_tests.yml b/.github/workflows/macos_unit_tests.yml index c29a1ce2e0..193eb86c27 100644 --- a/.github/workflows/macos_unit_tests.yml +++ b/.github/workflows/macos_unit_tests.yml @@ -11,18 +11,15 @@ jobs: with: submodules: recursive - name: Install dependencies - run: brew install lmdb automake openssl pcre2 autoconf libtool + run: brew install lmdb automake openssl pcre2 autoconf libtool libyaml - name: Check tools run: command -v libtool && command -v automake && command -v autoconf - name: Check tools versions run: libtool -V && automake --version && autoconf --version - name: Run autotools / configure run: > - LDFLAGS="-L`brew --prefix lmdb`/lib -L`brew --prefix openssl`/lib -L`brew --prefix pcre2`/lib" - CPPFLAGS="-I`brew --prefix lmdb`/include -I`brew --prefix openssl`/include -I`brew --prefix pcre2`/include" - PATH="/opt/homebrew/opt/libtool/libexec/gnubin:$PATH" ./autogen.sh --enable-debug - name: Compile and link - run: make -j8 CFLAGS="-Werror -Wall" + run: MACOSX_DEPLOYMENT_TARGET=15.4 make -j8 CFLAGS="-Werror -Wall -Wextra -Wno-sign-compare" - name: Run unit tests run: make -C tests/unit check diff --git a/.github/workflows/shellcheck.yml b/.github/workflows/shellcheck.yml index adc97226e7..8166e37fe0 100644 --- a/.github/workflows/shellcheck.yml +++ b/.github/workflows/shellcheck.yml @@ -6,7 +6,7 @@ on: jobs: unit_tests: name: Run shellcheck on shell scripts - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 with: diff --git a/.github/workflows/unit_tests.yml b/.github/workflows/unit_tests.yml index 932560b1ea..0f72353e21 100644 --- a/.github/workflows/unit_tests.yml +++ b/.github/workflows/unit_tests.yml @@ -6,7 +6,7 @@ on: jobs: unit_tests: name: Run Unit Tests - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v3 with: @@ -16,6 +16,6 @@ jobs: - name: Run autotools / configure run: ./autogen.sh --enable-debug - name: Compile and link (make) - run: make -j8 CFLAGS="-Werror -Wall" + run: make -j8 CFLAGS="-Werror -Wall -Wextra -Wno-sign-compare" - name: Run unit tests run: make -C tests/unit check diff --git a/.github/workflows/valgrind.yml b/.github/workflows/valgrind.yml index db600e6556..08cc41ae32 100644 --- a/.github/workflows/valgrind.yml +++ b/.github/workflows/valgrind.yml @@ -5,7 +5,7 @@ on: jobs: valgrind_tests: - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 defaults: run: working-directory: core diff --git a/.github/workflows/windows_acceptance_tests.yml b/.github/workflows/windows_acceptance_tests.yml deleted file mode 100644 index 06e9cefd25..0000000000 --- a/.github/workflows/windows_acceptance_tests.yml +++ /dev/null @@ -1,91 +0,0 @@ -name: Windows Acceptance Tests - -on: - workflow_call - -defaults: - run: - shell: msys2 {0} - -jobs: - windows_acceptance_tests: - runs-on: windows-latest - steps: - - uses: msys2/setup-msys2@v2 - with: - install: >- - rsync - dos2unix - diffutils - util-linux - python-pip - - - name: Checkout Core - uses: actions/checkout@v3 - - - name: install cf-remote - run: pip install cf-remote - - # Note that msiexec can't install packages when running under msys; - # But cf-remote currently can't run under powershell - # (because it requires `pwd` module which is Unix-only). - # Hence, we _download_ msi package using cf-remote under msys, - # and install it by msiexec running under powershell. - - - name: get CFEngine package - run: cf-remote --version master download x86_64 msi - - - name: move CFEngine package to current workdir - run: "mv $HOME/.cfengine/cf-remote/packages/*.msi cfengine.msi" - - - name: install CFEngine - run: | - Get-Location # pwd - New-Item -Path "c:\" -Name "artifacts" -ItemType Directory - Start-Process msiexec.exe -Wait -ArgumentList '/quiet /qn /i cfengine.msi /L*V c:\tmp.log' - Get-Content c:\tmp.log | Set-Content -Encoding utf8 c:\artifacts\CFEngine-Install.log - file c:\artifacts\CFEngine-Install.log - shell: pwsh - - - name: run cf-agent - run: "'/c/Program Files/Cfengine/bin/cf-agent.exe' --version" - - # tests run easier if the core repo and CFEngine install are on the same partition: C: - - name: copy core checkout to main partition - run: 'rsync -avz /d/a/core/core /c/ || true' - - - name: prune platform independent tests to make the job more efficient - run: 'Remove-Item -Recurse -Force 00_basics, 01_vars, 02_classes, 10_files, 14_reports, 15_control, 16_cf-serverd, 21_methods, 22_cf-runagent, 26_cf-net, 27_cf-secret, 28_inform_testing' - working-directory: C:/core/tests/acceptance - shell: pwsh - - - name: run the tests - run: './testall --bindir="/c/Program Files/Cfengine/bin" --extraclasses=EXTRA' - working-directory: C:/core/tests/acceptance - env: - # env vars for testall script to properly detect environment - USER: runneradmin - OSTYPE: msys - - - name: print test.log - run: 'cat ./tests/acceptance/test.log || true' - working-directory: C:/core - if: ${{ always() }} - - - name: save test.log in artifacts - run: 'cp ./tests/acceptance/test.log /c/artifacts/test.log || true' - working-directory: C:/core - if: ${{ always() }} - - # make a tarball because otherwise there will be too many files and github won't save the artifact - - name: save workdir to artifacts - run: 'tar cfz /c/artifacts/workdir.tar.gz ./tests/acceptance/workdir || true' - working-directory: C:/core - if: ${{ always() }} - - - name: save artifacts - if: success() || failure() - uses: actions/upload-artifact@v3 - with: - name: artifacts - path: c:\artifacts diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000000..b0a0946bd0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3667 @@ +## 3.24.4 + +- Enabled `select_region` to converge across multiple passes (CFE-3866) +- Fixed buffer overflow in build XPath for `edit_xml` (ENT-13550) +- Fixed buffer overflow in `cf-secret` when using multiple keys of different sizes + (ENT-13591) +- Fixed buffer overflow in the files promise +- Fixed heap buffer overflow in files `edit_line` (ENT-13590) +- Fixed memory leak in `isreadable()` policy function +- Fixed potential buffer overflow when computing chroot path + (ENT-13551) +- Fixed potential buffer overflow when converting strings to GIDs/UIDs + (ENT-13551) +- Fixed segfault when cf-secret print-headers is called without an encrypted file + (CFE-4647) +- Fixed bug causing files promise to fail copying files on vfat file system + (ENT-13809) + +## 3.24.3 + +- Made permissions atomic during file copy: + The temporary file is now set to promised permissions before replacing it + with the original in copy_from files promises (ENT-13163) +- Removed useless output from cfengine3 init script (ENT-13234) +- Switched to using current process ID to investigate proc filesystem + to workaround in-container non-root owned symlinks (CFE-3429) +- Added sysvinit cf-php-fpm service script for Mission Portal + (ENT-13234) +- Fixed bug where remote file copy always preserves source perms + Remote file copy with the `copy_from` attribute now only preserves + source file permissions if the `preserve` attribute in `body copy_from` + is true. Otherwise it will use the permissions of the destination file + if it already exists and default permissions if it does not (ENT-11988) +- Fixed cf-support usage of coredumpctl matching (ENT-13272) +- Fixed crash in readyaml() policy function when parsing an empty file (CFE-4595) +- Fixed move_obstructions support when using content, and edit_template + (CFE-4591) +- Fixed handling of promise locking with edit line + Fixed bug where rendered files can result in erroneously empty files + as a result of promise locking (ENT-9980) + +Security fixes: + +- CVE-2026-24712 - Injection in CFEngine Policy Language: + https://cfengine.com/blog/2026/cve-2026-24710-and-cve-2026-24711-and-cve-2026-24712/ + +## 3.24.2 + +- Adjusted cf-support for exotic UNIX platforms (ENT-9786) +- Adjusted cf-support to not fail if core dumps are available and gdb is + missing (ENT-9786) +- In case of LMDB migration failures, the respective database file is now + moved to the side, and a fresh database is created. +- cf-agent now creates backup before LMDB migration +- Re-enabled DB migration support for LMDB +- SELinux: Allow cf-serverd to set its own limits (ENT-12446) +- Added http_port and getattr selinux permissions as needed for selinux + policy on rhel-8 and rhel-9 (ENT-12954) +- Added "acknowledged" field to lastseen DB (ENT-11838) +- Fixed issue where rhel >8 packages would not have correct openssl + dependency version (ENT-12587) +- Fixed bug in parsing process_select for Windows (ENT-12751) +- Fixed bug causing LMDB database corruption +- Fixed incorrect exit code handling in cf-runagent (ENT-12712) +- Fixed possible segmentation fault when backing up LMDB databases + +## 3.24.1 + +- Fixed multiple issues in cfengine-enterprise SELinux policy which could + cause AVC denials / warnings for various CFEngine components. + (ENT-12466, ENT-12446) +- Added logging CFEngine component related SELinux denials in cf-support + (ENT-12137) +- Agent now also ignores interfaces listed in ignore_interfaces.rx when + looking for IPv6 interface info. Variables such as + `default:sys.hardware_mac[]` will no longer be defined for + ignored interfaces. (ENT-11840) +- Atomic copy_from in files promise + Changes to `files` promise in `copy_from` attribute: + - The new file (i.e., `.cfnew`) is now created with correct + permission during remote copy. Previously it would be created with + default permissions. + - The destination file (i.e., ``) is no longer deleted on + backup during file copy. Previously it would be renamed to + `.cfsaved`, causing the original file to dissappear. Now an + actual copy of the original file with the same permissions is created + instead. + As a result, there will no longer be a brief moment where the original + file is inaccessible. (ENT-11988) +- commands promises with exit codes not matching any + `_returncodes` attributes from classes body now log and + error message not just an info message (CFE-4429, ENT-12103) + +## 3.24.0 + +- Added a sanity check to policy parser that checks for and warns + in case of promise declarations with no actions. The motivation + for this check is to aid policy writers in detecting semantic + errors early. (ENT-11137) +- Added sys.os_name_human for Alpine, postmarketOS, OpenBSD and NetBSD +- Added warning log message when OS is not recognized (CFE-4342) +- Adjusted locale settings in masterfiles stage common script to + handle more cases (ENT-11885) +- Adjusted package module inventory to include quotes around + fields when needed (CFE-4341) +- Added `sys.os_name_human` and `sys.os_version_major` variables + for Amazon. Additionally changed value of `sys.flavor` from + `AmazonLinux` to `amazon_linux_2`, so that it is similar to other + supported Linux distros. This change was necessary, due to the + fact that the `sys.os_version_major` variable is derived from + it. However, the `AmazonLinux` class previously derived from + `sys.flavor` is still defined for backwards compatibility. + (ENT-10817) +- CFEngine now uses PCRE2 for regular expressions (ENT-10629) +- CFEngine processes no longer suffer from the "Invalid argument" + issues when working with LMDB (ENT-11543) +- Changed cf-apache systemd unit to reload configuration gracefully + (ENT-11526) +- Changed cf-execd's sleep behavior so it attempts to wake up at + the beginning of every minute (ENT-11765) +- File copying now uses more efficient implementation on Linux + platforms (CFE-4380) +- Fixed bug in double expansion of foreign list variables with namespaces + (ENT-11923) +- Fixed bug related to failing backwards directory traversial when + using forward slashes in path argument of the findfiles_up() + policy function on Windows. +- Fixed bug where `default:sys.fqhost` contained many spaces when domain is + set in body common control (CFE-4053) +- Fixed cf-support call to cf-promises to collect all classes and vars + (CFE-4300) +- Fixed package promises with only promisers and no other attributes + (CFE-4315, CFE-4398, CFE-4408) +- Modified package promise default. If platform_default is present + use that package module. (CFE-4315) +- Ownership of symlinks is now handled properly (ENT-11235) +- SELinux no longer breaks exporting large reports as PDF (ENT-11154) +- The `arglist` attribute in the `commands` promises now preserves + whitespaces in the arguments. Whitespaces are currently not preserved on + Windows, or if the `useshell` attribute is set to anything other than + `"noshell"`. (CFE-2724, CFE-4294) +- Trailing newline on insert_tree promisers no longer removes + ending tag for select_xpath (CFE-3806) +- cf-agent has two new options --no-augments and + --no-host-specific-data to skip loading augments + (def.json or def_preferred.json) and host-specific + data (host_specific.json), respectively (ENT-10792) +- cf-agent now has a new option --skip-bootstrap-service-start to + skip starting CFEngine services during the bootstrap process + (ENT-11932) +- cf-runalerts.service no longer exists, alerts are now + periodically run by cf-reactor (ENT-11538) +- depth_search acting on a non-directory promiser now handles such + file as if the promise didn't use depth_search. A warning is issued in this case. + (ENT-8996) +- masterfiles-stage.sh now supports a new --check-only option + (ENT-9386) +- Added new policy variable `sys.cfengine_roles`. This + variable is a string list, containing "Reporting hub" if cf-hub + exists (hub package installed), "Policy server" if the host is + bootstrapped to itself (`policy_server` class defined), and just + "Client" if none of the other options are true. +- Added 2 new classes correlating to the values in `sys.cfengine_roles`: + `cfengine_reporting_hub` and `cfengine_client`. + +## 3.23.0 + +- Added selinux policy to allow cf-hub to initiate scheduled reports + (ENT-10696, ENT-9825) +- Added version_compare() policy function (CFE-3991) +- Bodies can now inherit attributes containing global variables + (CFE-4254) +- Cached policy function results now take into account number of arguments + and function name (CFE-4244) +- Fixed infinite loop on error bug while reading interface exception file +- Fixed inventoried policy release id when masterfiles-stage.sh deploys with cfbs + (ENT-10832) +- Improved locale override in masterfiles stage scripts (ENT-10753) +- Improved syntax description for validjson() (ENT-9759) +- Made cf-support use coredumpctl for core analysis only when configured in kerenl.core_pattern + (ENT-9985) +- Modified classesmatching() function to search parent bundles with inherit => true + (ENT-5850) +- Moved expected location of ignore_interfaces.rx from $(sys.inputdir) to + $(sys.workdir). If the file is found in $(sys.inputdir) but not in + $(sys.workdir), we will still process it for backwards compatability, + but issue a warning prompting the user to move it to the appropriate + location. (ENT-9402) +- Only CFEngine processes are now killed as expired lock owners + (CFE-3982) +- SELinux no longer blocks CFEngine deamons in reading security parameters from /proc/sys/kernel + (ENT-9684) +- cf-hub is now allowed to use the TLS kernel module on + SELinux-enabled systems (ENT-9727) +- cf_lock.lmdb is no longer restored from backup on + every boot (CFE-3982) +- packagesmatching() and packageupdatesmatching() now look for the software + inventory databases in the state directory and use them if found. This + change enables the usage of these functions in standalone policy files + without the demand for specifying the default package inventory attribute + in body common control. However, you still need the default package + inventory attribute specified in the policy framework for the software + inventory databases to exist in the first place and to be maintained. + (ENT-9083) +- CFEngine locks are now purged dynamically based on the local locks DB + usage/size ranging from no purging (<=25% usage) (ENT-8201, CFE-2136, ENT-5898) +- `cf-check repair` now rotates DB files with high usage (>95%) (CFE-3374) +- Full LMDB files are now handled gracefully by moving them aside and using new + empty LMDB files (ENT-8201) +- `cf-check repair` now supports the `--test-write` option to check if DBs can + be written to as part of identifying DBs that need repairing (CFE-3375) +- `cf-check diagnose` now shows DB usage and a hint if rotation is required +- /usr/bin/getent is now attempted to be used if /bin/getent doesn't exist (CFE-4256) + +## 3.22.0 + +- Added --help option to cf-support and aligned output with other + components (ENT-9740) +- Added classes and vars to cf-support (CFE-4160) +- Added condition to runalerts service to require stamp directory + (ENT-9711) +- Added mctp_socket class to selinux policy (ENT-10206) +- Added native core dump handling in cf-support for Solaris (ENT-9786) +- Added needed SELinux class lockdown for latest RHEL 9 hosts (ENT-9685) +- Adjusted cf-support for exotic/legacy POSIX systems (ENT-9340) +- Adjusted cf-support for hpux mktemp command (ENT-9786) +- Directories are now created with correct perms (CFE-4114) +- Variables & classes modules automatically tagged (ENT-7725) +- Changed bootstrap policy to preserve log level for debug, verbose, + and info (CFE-4121) +- Created new policy function isreadable (ENT-9380) +- Enabled expireafter attribute for custom promise types (CFE-4083) +- Enabled install-time SELinux policy compiling (ENT-9685) +- Expired agents now terminate custom promise modules (CFE-4083) +- Fixed debug module expand logging for scalars (CFE-4122) +- Fixed syntax description of validjson() (ENT-9759) +- Prevented cf-support from searching more than 1 level for core files + (ENT-9981) +- Started checking status of all cf- prefixed systemd services in + cf-support (ENT-9804) +- validjson() no longer accepts trailing bogus data (CFE-4080) + +## 3.21.0 + +- Added cf-support utility for generating support information + (ENT-9037) +- Adjusted cf-check and package module code for empty updates list + (ENT-9050) +- `$(this.promiser)` can now be used in `files` promise + attributes `if`, `ifvarclass` and `unless` + (CFE-2262, ENT-7008) +- Fixed storage promise for nfs on MacOS (CFE-4093) +- Fixed definition of `_low_ldt` class from cf-monitord (CFE-4022) +- Insertion of contents of a file with blank lines into + another file with blank lines no longer results in + mixed content (ENT-8788) +- Added suggestion to use a negative lookahead when non-convergent edits + are attempted + (CFE-192) +- Unresolved function calls that return scalar values + are now considered OK for constraints expecting + strings during syntax check (CFE-4094) +- cf-monitord now honors monitorfacility in body monitor control + (ENT-4492) +- cf-serverd now periodically reloads its policy if it + contains unresolved variables (e.g. $(sys.policy_hub) + in `allowconnect`). (ENT-8456) +- cf-serverd now starts in the network-online.target on + systemd-based systems (ENT-8456) +- edit_line bundles can now use the new + $(edit.empty_before_use) variable mirroring the value of + edit_defaults=>empty_before_use of the related files promise + (ENT-5866) +- Package modules with unresolved variables in their + names are now skipped in package queries (ENT-9377) +- Removed unsupported name_connect capability for udp_socket class + (ENT-8824) +- `meta` attribute can now be used in custom promises (CFE-3440) +- Custom promise modules can now support the `action_policy` + feature allowing promises of their custom types to be used + in dry-run and simulation modes and in combination with + `action_policy => "warn"`. (CFE-3433) +- Use of custom promise modules that don't fully specify + protocol now results in warning (CFE-3433) +- Warnings are logged if levels of log messages from + custom promise modules don't match results of their + related promises (CFE-3433) +- Adjusted SELinux policy for RHEL 9 (ENT-8824) +- Fixed SELinux policy to allow hub to send emails (ENT-9557, ENT-9473) +- SELinux no longer breaks SQL queries with large result + sets on RHEL 8 hubs (ENT-9496) +- Added SELinux LDAP port access for Mission Portal (ENT-9694) +- Allowed ciphers are now properly split into TLS 1.3 + cipher suites and ciphers used for TLS 1.2 and older + (ENT-9018) +- Fixed git_cfbs_deploy_refspec in masterfiles_stage leaving temp dir + (ENT-9039) + +## 3.20.0 + +- `rxdirs` now defaults to "false". This means that the read permission + bit no longer implies execute bit for directories, by default. + Permission bits will be exactly as specified. To restore the old behavior + you can still enable `rxdirs` explicitly. (CFE-951) +- `N` or `Ns` signal specs can now be used to sleep + between signals sent by `processes` promises + (CFE-2207, ENT-5899) +- Directories named .no-distrib are no longer copied from policy server + (in bootstrap/failsafe) (ENT-8079) +- Files promises using content attribute or template method now create + files by default unless `create => "false"` is specified. (CFE-3955, + CFE-3916) +- template_method mustache and inline_mustache now create file in promiser, + if template rendering was successfull and file does not exist. (ENT-4792) +- Added support for use of custom bodies in custom promise types + (CFE-3574) +- Custom promise modules now never get promise data with unresolved variables + (CFE-3434) +- Custom promises now use standard promise locking and support ifelapsed + (CFE-3434) +- Enable comment-attribute for custom promise types (CFE-3432) +- cf-secret encrypt now encrypts for localhost if no key or host is + specified (CFE-3874) +- CFEngine now builds with OpenSSL 3 (ENT-8355) +- CFEngine now requires OpenSSL 1.0.0 or newer (ENT-8355) +- Moved Skipping loading of duplicate policy file messages from VERBOSE to DEBUG + (CFE-3934) +- CFEngine processes now try to use getent if the builtin user/group + info lookup fails (CFE-3937) +- No longer possible to undefine reserved hard classes (ENT-7718) +- Unspecified `rxdirs` now produces a warning (CFE-951) +- Fixed wrong use of log level in users promises log messages (CFE-3906) +- Fixed default for ignore_missing_bundles and ignore_missing_inputs + The issue here was that these attributes should default to false, + but when they are assigned with an unresolved variable, they + would default to true. (ENT-8430) +- Added protocol 3 (cookie) to syntax description (ENT-8560) +- Moved errors from data_sysctlvalues from inform to verbose (CFE-3818) +- Fixed inconsistencies with methods promises and missing bundles + Previously, methods promises acted differently depending on if + you specify the bundle with usebundle or in the promiser string. + This change removes the inconsistent checking which was only + happening on promises with usebundle. It also ensures that + the agent will abort if trying to use an undefined bundle, + regardless of whether it was using promiser string or usebundle. + This change, combined with the fix for ignore_missing_bundles + and ignore_missing_inputs, allow you to use inputs and bundles + conditionally (like we do for the enterprise federation policy) + and still have the agent abort in the correct situations + (when a bundle is actually missing and you haven't enabled + ignore_missing_bundles). The downside is that there are some + potential situations where undefined bundles would be detected + earlier previously (both correctly and incorrectly). (ENT-8430) + +## 3.19.0 + +- -N/--negate now prevents persistent classes from being defined + (ENT-5886) +- `null` JSON value is now handled as empty data in augments/host-specific data + (ENT-7434) +- Added a new common control attribute `system_log_level` + For specifying the minimum log level required for log messages to + go to the system log. (ENT-7594) +- Added support for cfbs managed policy set to masterfiles staging script (ENT-7709) +- Trailing commas can now be used in policy argument lists (CFE-3734) +- Changed cf-key option --print-digest to take an optional argument. + cf-key now defaults to the public key file in workdir, if no argument + is specified or an empty string is given as the argument. (CFE-3682) +- Cached functions are now always called inside promises with `iflapsed => "0"` + (CFE-3754) +- Enabled `handle` attribute for custom promise types (CFE-3439) +- Enabled `depends_on` attribute for custom promise types (CFE-3438) +- Enabled `with` attribute for custom promise types (CFE-3441) +- Don't fail on new file creation when backups are enabled + (CFE-3640) +- Extended `hostsseen()` policy function to return host keys (CFE-2546) +- Moved httpd.pid to root of httpd workdir (ENT-7966) +- Only real changes in files now produce info messages (CFE-3708) +- Reports with unexpanded variable references are now + attempted to be held off until the reference expands + (CFE-3776) +- Set apache umask to 0177 (ENT-7948) +- The --skip-bootstrap-policy-run option now skips the update policy + (ENT-7500, ENT-7511) +- Added measurement names in cf-check dump (ENT-7452) +- Value of `$(with)` is now expanded even if it contains unresolved variable references + (CFE-3776) +- cf-serverd now binds to both IPV6 and IPV4 if bindtointerface is unspecified + (ENT-7362) +- cf-serverd now reports if fails to bind to all possible addresses/interfaces + (ENT-7362) +- Fixed dbm_quick.c DBPrivRead() argument type (CFE-3737) +- Fixed dbm_tokyocab.c DBPrivRead() argument type (CFE-3737) +- Fixed crashes (Segfaults) in VariableIsSecret() (ENT-7678) +- Fixed crashes (Segfaults) in VariablesMatching() (ENT-7678) + +## 3.18.0 + +- "No action for file" warning is no longer triggered when only + `content => "something"` is used (CFE-3507) +- "source=promise_iteration" variables are no longer created in + foreign bundles (ENT-7029) +- `cf-remote install` now supports the `--trust-keys` option for + pre-establishing trust before bootstrap (CFE-3485) +- `cf-remote spawn` now supports adding new VMs to an existing group + (CFE-3502) +- `rename => newname()` now supports relative paths (CFE-3537) +- `variables` and `classes` in CMDB and augments data now support + `comment` fields (CFE-3638) +- Included custom promise type libraries in src tarball + (CFE-3575, CFE-3576) +- --ignore-preferred-augments now sets a hard class; ignore_preferred_augments + This class makes it easy for cf-agent / cf-execd policy to + propagate the option to other binaries (CFE-3656) +- Added `classes` body support for custom promises (CFE-3437) +- Added a new --simulate=manifest-full mode + New simulation mode that manifests all changed files as well as + all other files evaluated by the agent run which were not skipped + (by file selection rules) (CFE-3506) +- Added a new runagent_socket_allow_users body executor control attribute + A new attribute that tells cf-execd to grant access to the + runagent.socket to the specified users (ENT-6735) +- Added checks to return value from getpwuid & getgrgid (CFE-3521) +- Added int() policy function (CFE-3616) +- Added new command line option: --ignore-preferred-augments + This option causes the agent to ignore def_preferred.json + always reading def.json (old behavior) (CFE-3656) +- Added policy function type() +- Added policy function findfiles_up (CFE-3577) +- Added policy variable sys.os_name_human (CFE-3569) +- Added policy variable sys.os_version_major (CFE-3569) +- Added shell library for custom promise types with cp example + (CFE-3516) +- Added string() policy function (CFE-3476) +- Augments data now supports meta information for classes + and a new `variables` object for variables with meta information + (CFE-3633) +- Fixed case where malformed input could trigger buffer overflow + in policy function format (CFE-3525) +- Ability to report some number of lines from the END of a file by + specifying number_of_lines as a negative number using printfile + (CFE-3558) +- CFEngine binaries now load host specific data + ($(sys.workdir)/data/host_specific.json) before Augments relative + to policy entry (def.json) (ENT-6789) +- CFEngine processes are now properly identified in syslog on + non-GNU/Linux systems (ENT-7100) +- CMDB data now supports meta information for classes + and a new `variables` object for variables with meta information + (CFE-3633) +- Changed custom promise type interpreter attribute to be optional + (CFE-3562) +- Changed files promise repaired log level to verbose (CFE-3631) +- Changed log message about whitespace in class expressions to be error + (CFE-3560) +- Changed sys var attribute names: + "OS type" was changed to "Kernel", "OS kernel" was changed to "Kernel Release" + (ENT-6551) +- Clarified error log message about untrusted state directory not being private + (CFE-3599) +- Classes from augments are now defined as soft classes + within the `namespace` context instead of being hard + classes. Policies using classes from augments in policy files + using namespaces need to be updated to refer to the augments + classes with the `default:` prefix (CFE-3632) +- Custom promise modules using JSON protocol now support data attributes + (CFE-3654) +- Custom promise modules using JSON protocol now support slist attributes + (CFE-3444) +- Custom promise types can now be declared in separate files (CFE-3510) +- Custom promise types can now report back result classes (CFE-3515) +- Custom promises now support the `log_level` attribute (CFE-3436) +- Each custom promise module is now only spawned once + and handles all promises of its matching type(s) (CFE-3572) +- Early failing custom promises now properly set result classes + (CFE-3645) +- Exit code from remote agent run is now sent to cf-runagent (CFE-3594) +- Fixed crash when attempting to put methods promises in bundles + which are not agent bundles (CFE-3672) +- Fixed memory leak in package module code (ENT-5752) +- Fixed memory leak in simulate mode (CFE-3498) +- Fixed some more sign-compare warnings (CFE-3415) +- Improved error handling / logging of data received from promise module +- Improved log messages for commands promise outcomes and return codes + (CFE-3604) +- Made errors about failed validation of custom promises less noisy +- Namespace and bundle can now be specified in augments and CMDB data + (CFE-3633) +- New observations of root owned SETUID programs moved from WARN to NOTICE + (ENT-6519) +- Policy function format() no longer truncates strings lager than 4KiB + (CFE-2686) +- Policy function storejson() no longer truncates strings lager + than 4096 bytes (CFE-2507) +- Promise type is now sent to custom promise modules (CFE-3563) +- Reduced the noise caused by packages promises being skipped in + evaluation passes 2 and 3 (ENT-6553) +- Set Filedescriptor Limit to a more practial Size (CFE-3625) +- Stopped emitting warning and recording result when observing new + SETGID files (ENT-6750) +- Stopped updating files promise result with WARN (notkept) when + setuid files are encountered (ENT-6519) +- Unspecified `files` constraints no longer cause `_kept` classes + to be defined (CFE-3578) +- Updated contrib/masterfiles-stage scripts and instructions to be + accurate (ENT-6165) +- Fixed using a custom promise module with two different + interpreters results in an error (CFE-3572) - Value of the + `files_single_copy` body control attribute is now logged in + verbose logging mode (CFE-3622) +- Variables and classes defined in cmdb cannot be re-defined in + augments (ENT-7079) +- Verbose log now contains comments associated with `vars` and + `classes` promises (CFE-2442, CFE-2443) +- cf-agent now checks that promise module logs expected errors +- cf-agent now sends correct information to promise module in header +- cf-execd now executes cf-agent for "localhost" requests via the + runagent.socket (ENT-7090) +- cf-execd now handles requests to run cf-runagent on given hosts + (ENT-6182) +- cf-execd now runs cf-agent from a child process instead of a + thread on POSIX systems (ENT-6182) +- cf-runagent now exits with a code reflecting remote agent run + status(es) (CFE-3594) +- cf-serverd now supports systemd-based socket activation +- def_preferred.json is now used instead of def.json if it exists + Old clients will ignore it, allowing you to have 2 + versions of the augments file, 1 for compatibility + with old clients, and 1 for utilizing the new feautres. + (CFE-3656) +- files_single_copy body agent control attribute can now be an + empty list (CFE-3622) +- files_single_copy no longer treats paths of copied files as + regular expressions (CFE-3621) +- log_level is properly sent to promise modules in both validate + and evaluate requests (CFE-3564) +- unless can now be used with custom promise types (CFE-3431) +- CFEngine processes now reuse log facility from previous run for + early logging before policy is loaded (ENT-6955) + +## 3.17.0 + +- cf-agent can now simulate the changes done to files in a chroot, printing + diff or manifest information about what it would do in a normal evaluation. + Use the new command line option: `--simulate=diff` or `--simulate=manifest`. + Please note that only files and packages promises are simulated currently. +- Custom promise types can now be added using promise modules (CFE-3273) +- cf-monitord now uses `/proc/net/*` files to get network information if + possible (CFE-2945) +- Added new policy function execresult_as_data() (CFE-3315) +- Added optional argument to execresult for choosing between stdout and + stderr (CFE-3108) +- Outcome classes are now always defined for promiser in files promises + (CFE-3369) +- and(), or(), not() now return boolean and cannot be used directly in + slist vars. They can now be used in other places where a boolean is + expected. (Most notably and / or promise attributes). The return values + can be converted to strings using concat(), if necessary (CFE-3470) +- Backgrounded commands are now correctly executed in the child process + (CFE-3379) +- CFEngine policy bodies can now be completely empty +- Directory listings in files changes monitoring are now only updated + when there is a change (CFE-3382) +- Promises with `action => bg()` no longer break reporting data (ENT-6042) +- Spaces inside square brackets (slist/data index) are now allowed in + class expressions (CFE-3320) +- Variables specifying data/list names in @() references are now expanded + (CFE-2434) +- Added warnings when trying to use {{.}} to expand containers in mustache + templates (CFE-3457, CFE-3489) +- Limited unqualified host and domain name to 511 characters (CFE-3409) +- AVCs are no longer produced for CFEngine processes accessing /proc/net + (CFE-3240) +- Fixed how we check for `--cols` argument to `ps` (ENT-6098) +- Fixed a memory leak in users promises +- Fixed a small memory leak in cf-promises (CFE-3461) +- Fixed expansion of variables in data/list references (CFE-3299) + +## 3.16.0 + +- Added `cf-secret` binary for host-specific encryption (CFE-2613) +- `cf-check diagnose --test-write` can now be used to test writing + into LMDB files (ENT-4484) +- `if` constraint now works in combination with class contexts + (CFE-2615) +- Added $(sys.cf_version_release) variable (ENT-5348) +- Added new macros to parser: else, maximum_version, between_versions, + before_version, at_version and after_version. Version macros now + accept single digits (CFE-3198) +- Added cf-postgres requirement to cf-apache and cf-hub systemd units + (ENT-5125) +- Added files promise content attribute (CFE-3276) +- Added string_trim() policy function (CFE-3074) +- Added warning if CSV parser parses nothing from non-empty file + (CFE-3256) +- All changes made by `files` promises are now reported. Also, + directory and file creations are now properly reported as `info` + messages. And failures in edit_xml result in promises marked as + failed not interrupted. Purged dirs and files are reported as + repaired (ENT-5291, CFE-3260) +- Bootstrap to loopback interface is now allowed, with a warning + (CFE-3304) +- Client initiated reporting was fixed on RHEL 8.1 (ENT-5415) +- Fixed rare crashing bug when parsing zombie entries in ps output. The + problem was only ever observed on AIX, but could theoretically happen + on any platform depending on exact libc behavior. (ENT-5329) +- Fixed an issue causing duplicate entries in sys.interfaces, and + sys.hardware. (CFE-3046) +- Fixed ifelse() to return fallback in case of unresolved variables + (ENT-4653) +- Fixed locking of promises using log_repaired / log_string with + timestamps (CFE-3376) +- Fixed memory leak in handling of inline JSON in policy evaluation +- Fixed memory leak in readlist functions (CFE-3263) +- Fixed race condition when multiple agents are acquiring critical + section locks simultaneously (CFE-3361) +- Fixed selection of standard_services when used from non-default + namespace (ENT-5406) +- Fixed service status cfengine3 on systemd managed hosts (ENT-5528) +- Fixed some memory leaks and crashes in policy evaluation (CFE-3263) +- Improved error message for invalid body attribute names (CFE-3273) +- Improved management of secondary groups to avoid intermediary state + failures (ENT-3710) +- LMDB files are now created with correct permissions (ENT-5986) +- Log messages about broken Mustache templates are now errors (CFE-3263) +- Made classfiltercsv() fail properly on invalid class expression index +- Measurements promises with no match no longer produce errors + (ENT-5171) +- Moved error reading file in countlinesmatching() from verbose to error + (CFE-3234) +- Added new data validation policy functions validdata() and validjson() + (CFE-2898) +- New version checking convenience policy functions (CFE-3197) + Added the following policy functions to check against local CFEngine version: + - cf_version_maximum() + - cf_version_minimum() + - cf_version_after() + - cf_version_before() + - cf_version_at() + - cf_version_between() +- Removed (USE AT YOUR OWN RISK) from cf-key help menu for -x (ENT-5090) +- Rewrote helloworld.cf to use files promises content attribute + (CFE-3276) +- The outcome classes are now defined for the top-level directory when + `include_basedir` is `false` (ENT-5291) +- Variable references with nested parentheses no longer cause errors + (CFE-3242) +- cf-check: Added a more user friendly message when trying to print + unknown binary data (ENT-5234) +- cf-check: Added data validation for cf_lastseen.lmdb (CFE-2988) +- cf-check: Added nice printing for nova_agent_executions.lmdb + (ENT-5234) +- cf-check: Added validation for timestamps in cf_lock.lmdb (CFE-2988) +- cf-check: Added validation for timestamps in lastseen.lmdb (CFE-2988) +- cf-check: Fixed issue causing repair to target the wrong database file + (ENT-5309) +- cf-check: Symlinked LMDB databases are now preserved in repair + Performs diagnosis and repair on symlink target instead of symlink. + Repaired files / copies are placed alongside symlink target. + In some cases, the symlink target is deleted to repair a corrupt + database, and the symlink is left as a broken symlink. This is + handled gracefully by the agent, it will be recreated. Broken + symlinks are now detected as an acceptable condition in diagnose, + it won't try to repair them or delete them. (ENT-5162) +- storage promises managing nfs mounts should now correctly mount + after editing fstab entries + +## 3.15.0 + +- New policy function basename() added (CFE-3196) +- Added read_module_protocol() policy function + This function reads module protocol from a file, and can be used + for caching the results of commands modules. (CFE-2973) +- The @ character is now allowed in the key of classic arrays defined + by the module protocol (CFE-3099) +- nth() policy function now supports negative indices (CFE-3194) +- Fixed .xy floating point numbers parsing in eval() (CFE-2762) +- Added inform constraint to commands promises, to allow suppression of + INFO log messages (CFE-2973) +- Changed unless constraint to be more consistent with if + For any situation where if would NOT skip a promise, unless + will cause the promise to be skipped. When there are + unresolved variables / function calls, if will skip, unless + will NOT skip. (CFE-3160) +- Default minimum allowed TLS version is now 1.1 (ENT-4616) +- Network protocol version 2 is now called "tls" + "tls" or "2" can be used in places where you specify network + protocol. Log messages were altered, to show "tls" instead of + "latest". (ENT-4406) +- Introduced protocol version 3 - "cookie" + This protocol is identical to version 2 ("tls"), + except it allows the enterprise reporting hub to send + the COOKIE command to enterprise hosts. This command is used for + detecting hosts using duplicate identities. Protocol version "latest" + now points to version 3. For community installations, it should not + make a difference, policy servers will not send this command. The only + visible difference is the new version number (in logs and policy). + (ENT-4406) +- Package modules now hit network when package cache is first initialized + (CFE-3094) +- Fixed promise skipping bug in unless (CFE-2689) +- Fixed error message for unexpanded variables in function calls in unless + (CFE-2689) +- Prevented buffer overflow when policy variable names are longer than + 1024 bytes +- Zero bytes in class guards no longer cause crashes (CFE-3028) +- Fixed bug in ps parsing on OpenBSD / NetBSD causing bootstrap to fail +- Fixed crash in policy/JSON parsing of numbers with too many decimal + points (CFE-3138) +- copy_from without preserve now respects destination mode (ENT-4016) +- Removed stime_range and ttime_range constraints from promise hash + (ENT-4921) +- Fixed promise result when using process_stop in processes type promises + (ENT-4988) +- cf-execd now sends SIGKILL to the agent process in case of + agent_expireafter, after attempting SIGINT and SIGTERM (CFE-2664) +- cf-serverd now tries to accept connection multiple times (CFE-3066) +- Fixed multiple measurements tracking growth of same file (ENT-4814) +- Set create permissions of monitord files in state directory to 0600 + 0600 matches the permissions enforced by policy. + Affected files: + - `state/cf_incoming.*` + - `state/cf_outgoing.*` + - `state/cf_users` + - `state/env_data` + + (ENT-4863) + +- Clarified descriptions of io_writtendata and io_readdata (ENT-5127) +- Clarified log message about process_count and restart_class being used + concurrently (CFE-208) +- Agent runs that hit abortclasses now record results (ENT-2471) +- An ID of rhel in os-release file will now define both rhel and redhat + classes (CFE-3140) +- Version specific distro classes are now collected by default in + Enterprise (ENT-4752) +- redhat_8 and redhat_8_0 are now defined on RHEL 8 (CFE-3140) +- Added derived-from-file tag to hard classes based on /etc/redhat-release + (CFE-3140) +- Added sys.bootstrap_id policy variable containing the ID from + /var/cfengine/bootstrap_id.dat, if present (CFE-2977) +- sys.interfaces now contains interfaces even when they only have + IPv6 addresses (ENT-4858) +- IPv6-only interfaces added to `sys.hardware_(addresses,mac)` (CFE-3164) +- IPv6 addresses are now added to policy variable sys.ip_addresses + (CFE-682) +- IPv6 addresses now respect ignored_interfaces.rx (CFE-3156) +- Hostname now allowed in bindtoaddress (CFE-3190) +- Fixed issue when removing comments from files in various policy functions + This also fixes many erroneous occurences of the error message + mentioning: + + [...] because it legally matches nothing + + (A warning can still appear if a comment regex actually matches nothing). + Also made this comment removing logic faster. + Affected functions include: + - readstringlist() + - readintlist() + - readreallist() + - peers() + - peerleader() + - peerleaders() + - data_readstringarray() + - data_readstringarrayidx() + - data_expand() + - readstringarray() + - readstringarrayidx() + - readintarray() + - readrealarray() + - parsestringarray() + - parsestringarrayidx() + - parseintarray() + - parserealarray() + + (CFE-3188, ENT-5019) + +- Fixed memory leak in JSON / env file parsing (CFE-3210) +- Fixed memory leak in handling of nfs / fstab (CFE-3210) +- Fixed memory leak in string_replace() and regex_replace() (CFE-3210) +- Fixed memory leak when using with constraint (CFE-3210) +- Fixed minor memory leak in policy evaluation (CFE-3210) +- Fixed small memory leak in SQL database promises (CFE-3210) +- Received SIGBUS now triggers a repair of local DBs (CFE-3127) +- Corrupted LMDB files are now automatically repaired (CFE-3127) +- Keys in the lock database, cf_lock.lmdb, are now human-readable + (CFE-2596) +- Local databases now use synchronous access on AIX and Solaris (ENT-4002) +- Report corrupted local database with a critical log message (CFE-2469) +- Local DB errors are now logged with the particular DB file path (CFE-2469) +- cf-check: repair now preserves readable data in corrupted LMDB files + (CFE-3127) +- cf-check: --dump option was added to the backup command +- cf-check: Added --no-fork to diagnose command (CFE-3145) +- cf-check: Added -M manpage option and other common options (CFE-3082) +- cf-check: No DB files in state dir now causes errors +- cf-check: dump command now dumps DB contents to JSON5 (CFE-3126) +- cf-check: help command can now take a topic as argument + +## 3.14.0 + +- A bootstrap_id.dat file is now generated on every bootstrap + (CFE-2977) +- Added options to cf-net to set minimum TLS version and ciphers + (ENT-4617) +- Added --no-truncate option to cf-key + This option, when used with --show-hosts changes the formatting + of the output. Instead of padding and truncating each of the + fields, they are printed, in full, with no padding, and separated + by a single tab character. The output is not as pretty, but should + be more useful for parsing by other scripts / tooling. (CFE-3036) +- Added a new option --skip-db-check to agent and execd + This option allows you to enable/disable database (LMDB) consistency + checks. Initially it is disabled by default, but this will likely + change. (CFE-2893) +- Added a new utility to contrib: cf-remote + cf-remote is a python + fabric tool to log in to remote hosts + you have ssh access to. It can be used to download, transfer, + and install CFEngine packages as well as bootstrapping etc. + At this point, cf-remote is not packaged with CFEngine, but can be + installed separately from: + https://github.com/cfengine/cf-remote + (CFE-2889) +- Added derived-from-file tags to hard classes based on /etc/debian_version and /etc/issue +- Added a function to filter CSV-files by classes (CFE-2768) +- Forward slash is now an allowed character in module protocol commands + (CFE-2478) +- Augments files can now handle class expressions by appending `::` + A condition in an augments file is treated as a class expression + if it ends in ::. Otherwise it is treated as a regular + expression. (CFE-2954) +- Internal ps command can now handle longer usernames (CFE-2951) +- Made copylink_pattern honor `/../` in copy source (CFE-2960) +- CSV parser now supports CRLF inside double quotes (ENT-4504) +- Added an error when a function defining a variables still fails at + pass 3 (CFE-2983) +- Documented cf-execd and cf-serverd response to SIGHUP in manpage + (CFE-2853) +- Stopped trimming leading zeroes in ubuntu minor version class + The old version detection logic (using /etc/debian_version) was + converting the minor version part to an integer, defining + ubuntu_18_4 instead of ubuntu_18_04. The new platform detection + (based on /etc/os-release) defines ubuntu_18_04. Since both old + and new methods are running to maximize compatibility, both + ubuntu_18_04 and ubuntu_18_4 were defined. + This commit ensures that the old detection logic treats the + minor version (the 04 part) as a string, not an integer. The + change is specific to Ubuntu, and should affect Ubuntu 18.04, + 16.04, 14.04, etc. (CFE-2882) +- SUID log permissions are now properly enforced (CFE-2919) +- Agent log file names are now always lowercase +- Extended module with file protocol for data (CFE-3050) +- Fixed a segfault in `cf-promises -p json-full` (CFE-3019) +- Added cf-key help output to indicate ability to delete by key digest + (CFE-2997) +- Fixed disabling TLS 1.0 (CFE-3068) +- Fixed growing memory footprint of daemons (CFE-3032) +- Fixed the log message about setting collect_window (ENT-4238) +- Fixed the log message when parsing TIME in `ps` output fails +- Fixed parsing of YAML values starting with numbers (CFE-2033) +- Fixed sys.flavor on AIX (ENT-3970) +- Fixed 6 cases where promises could get the wrong outcome + All cases were related to error handling and detected using + static code analysis (LGTM). They were limited to cf-monitord + and cf-agent (guest_environments and files promise types). Due + to a programming mistake, promise results would sometimes be + overwritten with `skipped` outcome. Keeping the previous + value or making the promises `not kept` is expected behavior. + Added a query to our CI (LGTM) to make sure we catch this error + on new contributions. +- Fixed an issue while parsing ps output on AIX (ENT-4295) +- Fixed a memory leak in filesexist function (ENT-4313) +- Fixed a memory leak in mustache rendering (ENT-4313) +- Fixed a memory leak in: differences(), intersection(), unique() + (ENT-4586) +- Fixed a segfault in policy parser (ENT-4022) +- Connection cache is now global (CFE-2678) +- Increased verbosity of AcquireLock permission error (ENT-4395) +- Message about invalid class characters from module protocol moved to VERBOSE + (CFE-2887, CFE-3008) +- Prevented buffer overflows in cf-monitord data parsing +- Private keys generated by cf-key are no longer encrypted + Private key files encrypted with a broken cipher and default + hard coded passphrase provide no real security, and is only an + inconvenience. Maybe it was intended to add a password prompt + later, but it's been 10 years now, and the cipher and passphrase + remain untouched. The function which reads keys still supports + both encrypted and unencrypted keys, it will decrypt if necessary. +- Reduced SSL/TLS shutdowns on bad networks (CFE-3023) +- Removed programming error in handling of process_count body + Previously, having a failing function call inside in_range_define + or out_of_range_define would cause a programming error when + trying to define that as a class. Fixed it by detecting the + case, printing a normal error, and skipping defining the class. (CFE-2067) +- Set policy->release_id to "failsafe"/"bootstrap" when running failsafe.cf + (CFE-3031) +- Switched permissions of various temporary files in state to 0600 + These files were created with 0644 permissions, and then + repaired in policy. However, since they are deleted / recreated + periodically, it causes INFO noise. Safer and better user + experience to create them with restricted permissions to + begin with. + Affected files: + - $(sys.statedir)/cf_procs + - $(sys.statedir)/cf_rootprocs + - $(sys.statedir)/cf_otherprocs + + (ENT-4601) + +- string_split segments are now truncated to 1024 bytes instead of + crashing (CFE-3047) +- Unresolved function calls in process_select body are now skipped + Function calls which always fail, like getuid("nosuchuser"), are + never resolved. Previously this would cause a programming error, + since the body is expected to have a list of strings, not + unresolved function calls. + The function calls are silently skipped (with a verbose message) + as this matches the behavior of calling the functions in a vars + promise, and using that as a body parameter. + (CFE-1968) +- cf-check directories can now be controlled from ENV vars (CFE-2994) +- cf-check: Added backup command + This command copies lmdb files to a timestamped backup directory. + (ENT-4064) +- cf-check: diagnose and backup now use state directory by default + (ENT-4064) + +## 3.13.0 + +- Added support for TLS 1.3 and its ciphersuites +- Added `feature` hard classes for supported TLS versions + Different versions of TLS are supported depending on what version + of OpenSSL CFEngine was compiled and linked with. Newly added + feature hard classes bring that information to the + policy. Classes like these are now defined (for supported + versions of TLS): + ``` + feature_tls source=agent,hardclass + feature_tls_1 source=agent,hardclass + feature_tls_1_0 source=agent,hardclass + feature_tls_1_1 source=agent,hardclass + feature_tls_1_2 source=agent,hardclass + feature_tls_1_3 source=agent,hardclass + ``` +- Added a new variable $(sys.default_policy_path) + A new sys variable that provides the path of the default policy + file evaluated when no file is specified with the `-f` option. +- Added an option to skip the initial policy run on bootstrap + In some cases it may not be desired to run the policy as the last + step of the bootstrap. This can be done with the new + `--skip-bootstrap-policy-run` option for cf-agent. (CFE-2826) +- Trigger promises.cf as the last step of bootstrap (CFE-2826) +- Added support for overriding the package module's path (CFE-2103) +- Added support for setting package module interpreter (CFE-2880) +- Added --log-level option to all components + This allows you to specify any log level (info, verbose, debug etc.). + It is also less strict, allowing different spelling. As an example, + --log-level i, --log-level INFO, --log-level inform are all the same. +- Added a new binary: cf-check + Corrupt local databases (LMDB) continues to be a problem. + cf-check will be used to diagnose and remediate problems + with corrupt databases. It is a standalone binary, which + doesn't evaluate policy or use the local databases, thus + it can be used in situations where the other binaries + like cf-agent would hang. + cf-check replaces our lmdb database dumper, lmdump. + cf-check lmdump or symlinking / renaming it to lmdump + will make cf-check have the exact same behavior as lmdump. + cf-check will include much more functionality in the future + and some of the code will be added to other binaries, + for example to do health checks of databases on startup. + Ticket: (ENT-4064) +- Added function string_replace. (CFE-2850) +- Allowed dots in variable identifiers with no such bundle + As described and discussed in CFE-1915, defining remote variables + (injecting variables into remote bundles) is dangerous and must + be blocked. However, using a dot-separated common prefix for + variables raises no security concerns and can be considered + valid. (CFE-1915) +- Allowed requiring TLS 1.3 as the minimum version +- Apply augments after vars, classes and inputs in def.json + (CFE-2741, CFE-2844) +- Bundle name is now part of the log message when aborting a bundle + (CFE-2793) +- Class names set by module protocol are automatically canonified + (CFE-2877, CFE-2887) +- Classes failsafe_fallback and bootstrap_mode are now reported by default +- Corrected log level for `data_readstringarray*` (CFE-2922) +- Do not iterate over JSON objects' properties in mustache (CFE-2125) +- Do not render templates when passed invalid data (CFE-2194) +- Eliminated error messages caused by attempting to kill expired processes + (CFE-2824) +- Fixed cf-runalerts systemd unit conditions so the service will run + (ENT-3929) +- Fixed the off-by-one error in cf-runagent background process spawning + (CFE-2873) +- Fixed OOB read / heap buffer overflow in evaluator (ENT-4136) +- Fixed a memory leak which occured when reloading RSA keys from disk + (CFE-2857) +- Fixed a memory leak which occured while loading augments files + (CFE-2913) +- Fixed an issue with splay time in cf-execd (CFE-2931) +- Fixed error handling and memory leak in cf-key (CFE-2918) +- Fixed memory leak in JSON to policy conversion (ENT-4136) +- Fixed memory leak in lmdb cleanup (CFE-2918) +- Fixed memory leaks in cf-agent during bootstrap (CFE-2918) +- Fixed memory leaks in variablesmatching() and findfiles() (CFE-2918) +- Fixed missing class with mustache templates in warn_only mode + (CFE-2600) +- Fixed small memory leak in cf-serverd (CFE-2918) +- Fixed small memory leak in cf-upgrade (ENT-4136) +- Fixed small memory leaks of environment variable strings (CFE-2918) +- LMDB database dumper, lmdump, no longer creates empty databases + (ENT-4064) +- Made variablesmatching functions treat args regexes more correctly + variablesmatching() and variablesmatching_as_data() no longer + use string comparison to find matches. The documentation is clear; + arguments should be regexes (so you have to escape special + characters). + + ``` + bundle agent main + { + vars: + "myvar" + string => "example", + meta => {"os[linux]"}; + "matches" slist => variablesmatching(".*", "os\[linux\]"); + + reports: + "Match: $(matches)"; + } + ``` + + The above example is correct. If you don't escape the brackets + like above, it will no longer work. (You probably shouldn't use + brackets in tags anyway). + +- Prevent the init script from managing processes inside containers + (ENT-3800) +- Read mustache-rendered files in text mode when comparing digest + (ENT-2526) +- Reload persistent classes on config reload in cf-execd and cf-serverd + (CFE-2857) +- Fixed issue with @if macro failing when it is on the first line. + (CFE-2817) +- Fixed issue with cf-agent intermittently hanging on windows + sometimes (ENT-3756) +- Change GIT_BRANCH to GIT_REFSPEC and remove Design Center vars + (ENT-4023) +- os-release file is now used for hard classes and sys.flavor on all linuxes + This will improve platform detection on newer operating systems where + /etc/os-release (or /usr/lib/os-release) is present. + A hard class will be set for the value of the ID key (canonified with + underscores), if it exists. If both ID and VERSION_ID exist, multiple + hard classes will be set for all parts of the version number. The + special variable sys.flavor will also be set by determining major + version from VERSION_ID. + Example os-release file: + + ``` + ID=coreos + VERSION_ID=1185.3.0 + ``` + + For the example above, sys.flavor will be coreos_1185 and 4 hard + classes will be set; coreos_1185_3_0, coreos_1185_3, coreos_1185, + and coreos. + For backwards compatibility, older distribution specific logic is still + executed and may overwrite sys.flavor and define hard classes as before. + +- Refactor use of atexit to use custom cleanup function instead. On Windows + atexit() unloads DLLs before and/or during atexit functions being called + which causes bad behavior. (ENT-3756) + +## 3.12.0b1 + +New Features: + +- Added a --key-type option to specify RSA key size to cf-key +- New hash_to_int policy function (CFE-2733) +- Issue a warning on ignored locking attributes (CFE-2748) +- Added IPv6 hard classes with the `ipv6_` prefix (CFE-2310) +- Introduce "missing_ok" attribute in body copy_from + This allows to ignore missing sources in file copy operations (CFE-2365) +- Enable Xen hypervisor detection on all x86 platforms (CFE-2203) +- Added sys.policy_entry variables (CFE-2572) +- Added inline_mustache template method (CFE-1846) +- New component cf-net (cf-net is a CLI for the CFEngine network protocol, + useful for debugging, testing etc) and accompanying policy variable + sys.cf_net containing path to cf-net binary + +Changes: + +- Load augments at the end of context discovery + This means that classes defined as part of the context discovery + (e.g. `am_policy_hub` and `policy_server`) can be used in the + augments (CFE-2482) +- Open measurements promise type from enterprise cf-monitord +- Transform filesexist() into a collecting function (CFE-2744) +- Load process table when actually needed for a processes promise (ENT-2536) +- Ignore commented out entries in fstab when edit_fstab is true (CFE-2198) +- Do not move obstructions in warn policy mode (CFE-2740) +- Made the max bytes parameter to file reading functions optional (CFE-2656) +- Do not tag large volatile variables for inventory + sys.interfaces_data, sys.inet and sys.inet6 are commonly larger than the + maximum data size allowed to be collected by cf-hub. Data larger than 1k + is truncated. Instead of reporting truncated data this change stops + tagging the variable so that it will not be collected to the Enterprise + hub and will not be available in Mission Portal. (ENT-3483) +- cf-execd now re-parses augments on policy reload (CFE-2406) +- Improved misleading verbose message + For constraints if/ifvarclass/unless, we now print the whole rval of the constraint. + Previously the message was just "skipping variable because ifvarclass is not defined" while the variable itself was defined. + Old message example: + ``` + verbose: Skipping promise `mailto` because `if`/`ifvarclass` is not defined + ``` + Changed to: + ``` + verbose: Skipping promise `mailto` because `ifvarclass => not(isvariable("mailto"))` is not defined + ``` + (CFE-2697) +- Promise comments for file changes moved to verbose (ENT-3414) +- Suppress output from systemctl based restart of services in + bootstrap/failsafe (CFE-1459) +- Parser can now handle larger inbut buffers (CFE-1886) +- Improved logging of ACL errors (ENT-3455) +- cf-execd systemd service now only kills cf-execd itself (ENT-3395) +- Load multiple augments from "augments" string array in def.json + (CFE-2084) +- Improved support for Alpine Linux +- Set the exit value when running cf-key + When running cf-key to generate new keys, set the exit value of the + program to be 0 on success and 1 on failure. This makes it easier to + catch errors during setup of a new machine. + Change the default behavior of the program to not write anything to stdout, + opting to use the Log() function which can write to stdout and will also + allow output to be sent to syslog. + Add a --inform option to set the global log level to LOG_LEVEL_INFO. + Change the permissions of the randseed file to 600 and catch the exception + if the chmod call fails. +- Properly reverse-resolve DNS names longer than 63 chars (ENT-3379) +- Properly redirect init script to systemd on debian systems (ENT-3326) + +Bug fixes: + +- Disallow modifications of variables from a remote bundle (CFE-1915) +- Speedup evalution by not copying variables table when expanding a promise + (CFE-2524) +- Resolve subkey conflicts when converting to JSON + Whenever there is a conflict of array variable definitions prefer + the container subkeys over simple values when converting to JSON + (CFE-2536) +- Do not ignore meta promises in server bundles (CFE-2066) +- Added a debug log for computed class in splayclass +- Don't error when calling isexecutable on broken link (CFE-741) +- Fixed segfault when no show-evaluated-vars/classes is specified +- Fixed memory leak in cf-execd, triggered when sending email failed (CFE-2712) +- Fixed IPv6 parsing to be un-reversed (CFE-2580) +- Fixed bug preventing permission changes on Unix sockets (CFE-1782) +- Fixed storage mount promise when existing mountpoint has a similar path + (CFE-1960) +- Fixed segfault when cf-promises -p is called against a file with syntax + errors (CFE-2696) +- Fixed rare cf-execd hang (CFE-2719) +- Fixed mergedata segfault when called on a non-container (CFE-2704) +- Do not segfault if policy_server.dat only contains whitespaces and/or line breaks +- Fixed segfault on JSON policy files with no bundles and bodies (CFE-2754) + +## 3.11.0 + +New Features: + +- Allowed function calls in promiser using universal "with" attribute + (CFE-1092) +- Added example of with attribute (CFE-1092) +- Detect Amazon Linux and set "AmazonLinux" hard class and + sys.flavour variable +- New sysctlvalue() and data_sysctlvalues() functions from /proc/sys + (CFE-2513) +- readdata() also auto-detects .yml files as YAML +- Added support for ENV and CSV file parsing (CFE-1881) +- Added vars and classes for CoreOS (ENT-3043) +- cf-agent: implement --show-evaluated-vars and --show-evaluated-classes +- Support for custom ports and host names as policy hub (CFE-953) +- cf-promises: allows --show-vars and --show-classes to take an optional filter +- Added a new tool: cf-net. cf-net is a CLI for the CFEngine + network protocol, useful for debugging, testing etc (CFE-2493) +- New policy variable: sys.cf_net contains path to cf-net binary +- Read /etc/os-release into sys.os_release (CFE-1881) + +Changes: + +- readintlist() now prints an error if the + file contains real numbers, not integers, and aborts; previously it was + printing an info-level error message, was half-reading an integer out of + the real, and was continuing successfully. +- "make tar-package" should create a tarball with the contents of + "make install" (ENT-3041) +- Allowed opening symlinks owned by root or by the current user + (CFE-2516) +- Change warning message about depth_search on a non directory to + DEBUG level +- Ensure synchronous start and stop with systmectl (ENT-2841) +- Put logs in /var/log and PID files in /var/run when using FHS layout + (CFE-2449) +- readstringlist(), readintlist(), readreallist(): Print + verbose instead of error message if file can not be read +- cf-serverd: Do not close connection when file does not exist + (CFE-2532) +- policy_server.dat now appends a newline and supports host & port +- Allowed string_head and string_tail to take negative arguments +- getvalues(inexistent_var) returns an empty list. + Restores 3.7.x and earlier behaviour. (CFE-2479) +- Partially restore old getvalues(array) behaviour + Bugfix: getvalues() now behaves correctly for old CFEngine + arrays of depth 1 + Behaviour change: it always returns a list now. Even when v is a simple + string (i.e. not an iterable) it will return an slist with one element: + the value of the string variable. + Known issues: getvalues() still misbehaves with double-indexed arrays + (see CFE-2504, CFE-2536) +- The source version of CFEngine now installs binaries into + bin folder instead of sbin folder (CFE-2448) +- Don't error during dry run for proposed execution (CFE-2561) +- Print verbose instead of error message when readfile() fails (CFE-2512) +- cf-serverd: Auto configure max open files ulimit according to + maxconnections (CFE-2575) +- Made the max bytes parameter to file reading functions optional. + Affects readfile(), readenvfile(), readcsv() + +Bug fixes: + +- Fixed insert_lines related memory corruption (CFE-2520) +- Prevent LMDB assertion on AIX by ensuring nested DB calls are + not occuring during signal handler cleanup (CFE-1996) +- Fixed a bug which could cause cf-execd to believe there was + an error when sending the email report, when there really wasn't +- zendesk#3204: Fix "lastseenexpireafter" 32-bit signed int overflow +- Fixed cf-execd not exiting immediately with SIGTERM on AIX (ENT-3147) +- Fixed automatic service stops based on runlevel (redhat/centos) + (CFE-2611) +- Fixed cf-serverd crash when reporting corrupted data (ENT-3023) +- Fixed rare output truncation on Solaris 10/11 (CFE-2527) +- Fixed crash on Solaris when ps ucb variant is not available (CFE-2506) +- Fixed logic to detect when running under a Xen Hypervisor (CFE-1563) +- Fixed "lastseenexpireafter" 32-bit signed int overflow (zendesk#3204) +- Fixed IPv6 parsing to be un-reversed (CFE-2580) + +## 3.10.0 + +New features/additions: + +- All new features/additions for 3.8 and 3.9 are also included in 3.10. +- Added: Classes body tailored for use with diff +- New feature: Classes promise: allow classes without an expression to default to defined. +- Support for custom ports and host names as policy hub (CFE-953) +- Added: Definition of from_cfexecd for cf-execd initiated runs + (CFE-2386) +- Added < <= > >= operators to eval(). +- Added testing jUnit and TAP bundles and include them in stdlib.cf +- New function isipinsubnet() (ENT-7949) +- LogDebug(): implement module-based debug logging. + Now most DEBUG messages are _not_ printed even when "-d" is in use, but + the specific debug module has to be enabled on the command line. For + example to enable all log modules, run: + cf-agent -d --log-modules=all +- Added: edit_line contains_literal_string to stdlib +- Added variablesmatching_as_data() function paralleling variablesmatching() + (Redmine #7885) +- Allowed specifying agent maxconnections via def.json (CFE-2461) +- Added getuserinfo() function +- Added body agent control select_end_match_eof option. (CFE-2390) +- Added class to enable post transfer verification during policy updates +- Added ability to append to bundlesequnece with def.json (CFE-2460) +- policy_server.dat now appends a newline and supports host & port + +Changes: + +- Rewrite iteration engine to avoid combinatorial explosion with nested variable expansions. + This speeds up enormously the execution of policies that included long + slists or JSON containers, that in the past didn't even terminate. + Change: `"cf_null"` string literal was changed to not be something + special, and it's now a string that can be used anywhere, like + in slists or part of bundlesequence etc. + NOTE: Old policy should be grep'ed for `"cf_null"` and in case such + occurences were handled specially, they should be reworked. + Change: `"--empty-list--"` is now never printed by format(), + an empty list is now printed as `"{ }"`. + Change: Order of pre-evaluation was slightly changed, A new "vars" pass + at the beginning of pre-evaluation was added. It used to be + classes-vars, but it was changed to vars-classes-vars. As a + result some classes or variables might be evaluated at a + different time than before. As always try to write policy code that works no matter what the + order of execution is. + One way is to always _guard_ the execution of functions to avoid + bogus function results. For example the following will avoid + running execresult() bevore the file has been created: + execresult("cmd /path/to/filename") if => fileexists("/path/to/filename"); + C internals: NULL Rlist is now perfectly valid, in fact it is the only + way to denote an empty Rlist. + C internals: Since a slist variable can be NULL, API of + EvalContextVariableGet() changed: The way to detect if a + variable is found, is not to check return value for NULL, + but to check returned _type_ for CF_DATA_TYPE_NONE. + Fixed what I could find as wrong API uses. (CFE-2162) +- Allowed arbitrary service policies (CFE-2402) +- Behaviour change: cf-execd: Do not append -Dfrom_cfexecd to exec_command . + (CFE-2386) +- Failsafe/Bootstrap no longer copy files starting with .git (like .gitignore) or .mailmap + (CFE-2439) +- Changed: Enable strict transport security +- Changed: Disable http TRACE method +- Changed: Verify transfered files during policy update +- Allowed getvariablemetatags() and getclassmetatags() to get a specific tag key +- Changed: Use more restrictive unix socket perms (ENT-2705) +- Added sys.user_data container for user starting agent. +- Pass package promise options to underlying apt-get call (#802) + (CFE-2468) +- Changed: Enable agent component management policy on systemd hosts + (CFE-2429) +- Changed: Switch processes restart_class logging to verbose +- Changed: Log level for keeping verbatim JSON to DEBUG (CFE-2141) +- Changed: Require network before CFEngine services (CFE-2435) +- Behaviour change: getvalues(inexistent_var) returns an empty list. + Restores 3.7.x and earlier behaviour. (CFE-2479) +- Behaviour change: when used with CFEngine 3.10.0 or greater, + bundles set_config_values() and set_line_based() are appending a + trailing space when inserting a configuration option with empty value. + (CFE-2466) +- Behaviour change: getvalues() always returns a list now. Even when v is a simple + string (i.e. not an iterable) it will return an slist with one element: + the value of the string variable. +- Behaviour change: readintlist() now prints an error if the + file contains real numbers, not integers, and aborts; previously it was + printing an info-level error message, was half-reading an integer out of + the real, and was continuing successfully. +- Ensure synchronous start and stop with systemctl (ENT-2841) +- Change select_region INI_section to match end of section or end of file + (CFE-2519) + +Bug fixes: + +- Fixed files promise not setting ACL properly on directories. (CFE-616) +- Upgraded CFEngine dependencies to the following versions: + - lixml2 2.9.4 + - OpenSSL 1.0.2j + - LibYAML 0.1.7 + - Curl 7.50.3 +- Fixed cumulative() to accept up to 1000 years, like it's documented. +- Fixed parsing of host name/IP and port number in cf-runagent + (CFE-546) +- Fixed intermittent error message of type: + "error: Process table lacks space for last columns: " (CFE-2371) +- storage: Properly initialize the list of current mounts (CFE-1803) +- Fixed `contain` attribute `no_output` having no effect when + the `commands` promise is using `module => "true"`. (CFE-2412) +- Fixed bug which caused empty emails to be sent from cf-execd + if there was no previous output log and the new log was fully filtered + by email filters. (ENT-2739) +- Allowed ifelse(FALSE, $(x), "something else") to work. (CFE-2260) +- Fixed connection cache, reuse connections when possible. (CFE-2447) +- Fixed rare bug that would sometimes prevent redis-server from launching. +- Fixed bug in files promise when multiple owners are promised + but first one doesn't exist, and improve logging . (CFE-2432) +- Define kept outcome with action warn if edit_line is as expected + (CFE-2424) +- Example using getvariablemetatags() and getclassmetatags() to get a specific tag key +- Remove 2k limit on strings length when writing JSON policies + (CFE-2383) +- Fixed ttime_range constraint to go higher than 2G as number of seconds. +- Changed: cronjob bundle tolerates different spacing +- Allowed editing fields in lines longer than 4k (CFE-2438) +- Don't send empty emails for logs where everything is filtered. + (ENT-2739) +- Allowed maplist(), maparray(), and mapdata() to evaluate function calls during iteration + (ARCHIVE-1619) +- insert_lines is no longer implicitly matching EOF as + end of the region if `select_end` pattern is not matched . (CFE-2263) +- Changed: Remove executable bit from systemd units (CFE-2436) +- cf-serverd should reload def.json when reloading policy (CFE-2406) +- Fixed cf-monitord detection of usernames of the process table on AIX. +- Speed up local and remote file copying and fix spurious errors. + (ENT-2769) +- Fixed occasional segfault when running getindices() on a + variable that has indices of multiple depths (e.g. both "a[x]" and + "a[x][y]"). (CFE-2397) +- When no file is provided when calling cf-promises + with cf or json output, use promises.cf by default. This restores the + previous behavior. (CFE-2375) +- Fixed: Services starting or stopping unnecessarily (CFE-2421) +- Changed: Split systemd units (CFE-2278) +- EOF is matched as an end of the region in edit_line + promises only if `select_end_match_eof` parameter is true. (CFE-2263) +- Fixed double logging of output_prefix, and log process name for cf-agent syslog messages. + (CFE-2225) +- Be less verbose if a network interface doesn't have a MAC address. + (CFE-1995) +- Fixed: CFEngine choking on standard services (CFE-2806) +- Fixed insert_lines related memory corruption (CFE-2520) +- Fixed cf-serverd crash when reporting corrupted data. (ENT-3023) +- Fixed ability to manage INI sections with metachars for + manage_variable_values_ini and set_variable_values_ini (CFE-2519) +- Fixed apt_get package module incorrectly using interactive mode. +- Fixed crash on Solaris when ps ucb variant is not available. (CFE-2506) +- cf-serverd: Do not close connection when file does not exist. + (CFE-2532) +- getvalues() now behaves correctly for old CFEngine arrays of depth 1. + Known issues: getvalues() still misbehaves with double-indexed arrays + (see (CFE-2504, CFE-2536) + +## 3.9.0 + +New features/additions: + +- Added optional interface parameter to iprange() to match only one interface. +- Allowed `=` in symbolic modes (Redmine #7826) +- Added: FreeBSD ports package module +- New package module for FreeBSD pkg package manager. +- Added support for adding/removing fifos in policy +- Added Linux parsing of /proc/net/ data. + - sys.inet + - sys.inet6 + - sys.interface_data + - Data is returned as a data container. + - See documentation for more details. (Jira CFE-1991) +- sys.ip2iface: new reverse mapping variable from IP to interface name +- Namespaced classes can now be specified on the command line. +- Namespaces can now be passed to cf-runagent -D and --remote-bundles + (Redmine #7856) +- Added `cf-full` and `json-full` to cf-promises `-p` option. + They generate output based on the entire policy. The existing `cf` + already behaved this way, and it has now been changed to generate + output only for a single file, which the existing `json` option + already does. +- New language functions: processexists() and findprocesses() + (Redmine #7633) +- Implemented new regex_replace() function. (Redmine #7346) +- Added log rotation policy for state/classes.jsonl log. (Redmine #7951) +- Added collect_vars utility bundle to stdlib +- Intoduce report_class_log attribute to body agent control. + (Redmine #7951) +- Added standard_services service_method allowing for explicit usage +- cf-promises --show-vars can now show JSON variables. +- Added json_pipe mode to mapdata(), which allows piping a + JSON container to an external program for manipulation and receiving + JSON back. The jq tool is a good example where this mode can be + useful. A corresponding $(def.jq) variable has also been added with + a default path to this tool. See documentation for mapdata() for + more information and examples. (Jira CFE-2071) +- Behaviour change: "true" is always defined and "false" is never defined in a context expression. +- Added: nimclient package module for AIX + This module provides basic functionality for using nimclient as a means + to ensure packages are either present or absent. It does not support + listing package updates available or provide any special caching. +- Added callstack_callers() and callstack_promisers() functions. +- Log variable definitions in debug output. (Redmine #7137) +- Added: Memory information to host info report (Jira CFE-1177) +- In Mustache templates, one can now use {{#-top-}} and + {{/-top-}} tags to iterate over the top level element in a + container. (Redmine #6545) +- Added network_connections() function that parses /proc/net +- Provide new -w argument to override the workdir for testing +- New feature: Emails sent by cf-execd can be filtered to get + rid of emails for unwanted log messages. The attributes + mailfilter_include and mailfilter_exclude in body executor + control control what to include. See documentation for cf-execd for + more information. (Jira CFE-2283) +- Added: file_make_mustache bundle to render mustache templates +- Added `-n` flag to cf-key to avoid host name lookups. +- cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor multiple -D, -N and -s arguments + (Redmine #7191) +- Added "canonify" mode to mapdata(). +- Added: printfile bodies to stdlib +- Added: New results classes body [] (Redmine #7418, #7481) +- Implemented cf-runagent --remote-bundles and cf-serverd "bundle" access promise. + (Redmine #7581) +- Added commands promise arglist attribute, augmenting args attribute. +- It's now possible to reference variables in inline JSON, + for example: mergedata(`[ thing, { "mykey": otherthing[123] } ]`). + thing and otherthing[123] will be resolved as variables, since + they are unquoted. See the documentation for more details. + (Redmine #7871) +- Allowed inline JSON to be used in the following function + calls: + - data_expand() + - difference() + - every() + - filter() + - format() + - getindices() + - getvalues() + - grep() + - intersection() + - join() + - length() + - makerule() + - mapdata() + - maplist() + - mean() + - mergedata() + - none() + - nth() + - parsejson() + - product() + - regarray() + - reglist() + - reverse() + - shuffle() + - some() + - sort() + - storejson() + - string_mustache() + - sublist() + - sum() + - unique() + - url_get() + - variance() + + For example: mergedata(`[ "thing", { "mykey": "myvalue" } ]`) + See the documentation for more details. (Jira CFE-2253) + +- Added: edit_line contains_literal_string to stdlib +- Added body agent control select_end_match_eof option. (Jira CFE-2390) + +Changes: + +- Changed: classesmatching(): order of classes changed +- Changed: getindices(), getvalues(), variablesmatching(), maparray(): + order of variables returned has changed +- Changed: set_quoted_values uses bundle scoped classes +- Changed: set_config_values uses bundle scoped classes +- Changed: set_variable_values uses bundle scoped classes +- Changed: set_config_values_matching uses bundle scoped classes +- Changed: manage_variable_values_ini uses bundle scoped classes +- Changed: set_line_based should use bundle scoped classes + (Jira CFE-1959) +- getvalues() will now return a list also for data containers, + and will descend recursively into the containers. (Redmine #7116) +- Changed: Improve git drop user support +- Use new package promise as default package promise + implementation. (Jira CFE-2332) +- Don't follow symbolic links when copying extended attributes. +- When a `bodydefault:_` body is + defined, it will be used by all promises of type `` + unless another body is explicitly used. +- cf-serverd no longer appends "-I -Dcfruncommand" to + cfruncommand, this has to be done manually in masterfiles + body server control. (Redmine #7732) +- eval() function arguments mode and options are now + optional. +- sort() function argument mode is now optional. +- Changed: returnszero() no longer outputs the output of a command. + The output can be seen by enabling info mode (-I). +- cfruncommand is not executed under shell. (Redmine #7409) +- Removed: Apache CGI module +- Changed: Make maxbytes arg of readjson() and readyaml() optional +- Classes matching agent control's abortclasses are + now printed before exit, even if they are defined in common bundles. + Previously the regex (in abortclasses) that matched the class was + printed if the class was defined in a common bundle, but the class + itself was printed if it was defined in an agent bundle. With this + change, the defined class that caused the abort is always printed. +- Removed: Support for email settings from augments_file (Redmine #7682) +- Changed: set_variable_values_ini uses bundle scoped classes +- findfiles() now skips relative paths. (Redmine #7981) +- Clients connections using non TLS protocol are rejected + by default. . (Jira CFE-2339) +- Changed: Policy files specified in the "inputs" section of + def.json will no longer be auto-loaded. One has to refer to the + which are using the "inputs" field inside def.json. (Redmine #7961) +- Changed: Separate binary details from policy update (Redmine #7662) +- Added guard for binary upgrade during bootstrap (Redmine #7861) +- Changed: Modernize pkg module and package_method +- Removed: Userdir apache module +- filestat(path, "linktarget") now follows non-absolute links and returns full path of target. + This introduces a change in behaviour. Here is an example: + ``` + $ ls -l /bin/sh + lrwxrwxrwx 1 root root 4 Jun 4 2015 /bin/sh -> dash + ``` + Previously the filestat function would return "dash", and would also log + an error that the file can not be read. Now it will return "/bin/dash" + (or the final destination if it happens that /bin/dash is also a + symlink). + You can still get the previous behaviour by using + filestat(path, "linktarget_shallow"). (Redmine #7404) +- Define `(bootstrap|failsafe)_mode` during update.cf when triggerd from failsafe.cf + (Redmine #7861) +- Behavior change: The promise string of a processes + promise now matches just the command line of each process instead of + the line that is output by ps. This was done to reduce fragmentation + between platforms, since ps is a very nonstandardized tool. + (Jira CFE-2161) +- Allowed namespace names made more strict, to disallow + namespaces that cannot be reached. (Redmine #7903) +- Behavior change: When using readintlist(), readreallist() + or readstringlist(), parsing an empty file will no longer result in a + failed function call, but instead an empty list. Failure to open the + file will still result in a failed function call. +- insert_lines is no longer implicitly matching EOF as + end of the region if `select_end` pattern is not matched . + (Jira CFE-2263) +- EOF is matched as an end of the region in edit_line + promises only if `select_end_match_eof` parameter is true. + (Jira CFE-2263) + +Bug fixes: + +- Upgraded CFEngine dependencies to the following versions: + - Curl 7.48.0 + - libxml2 2.9.4 + - LMDB 0.9.18 + - OpenLDAP 2.4.44 + - OpenSSL 1.0.2h + - PCRE 8.38 + + (Jira ENT-2720) + +- Upgraded dependencies to latest minor versions. + For Community / Enterprise: + For Enterprise: +- Fixed bug which sometimes misparses user names in ps output. +- Fixed: Problem with git not dropping privileges soon enough +- Allowed def.json up to 5MB instead of 4K. +- It is possible to edit the same value in multiple regions + of one file. (Redmine #7460) +- CFEngine on Windows no longer truncates log messages if the + program in question is killed halfway through. +- Fixed a bug which caused def.json not being able to define + classes based on other hard classes. (Jira CFE-2333) +- Changed: Tighten Enterprise hub permissions (Jira ENT-2708) +- Fixed a regression which would sometimes cause "Permission + denied" errors on files inside directories with very restricted + permissions. (Redmine #7808) +- Fixed use-after-free in ArrayMap and HashMap (Redmine #7952) +- Package repositories are no more hit every time package promise + is evaluated on SUSE. +- Fixed a bug which sometimes caused package promises to be + skipped with "XX Another cf-agent seems to have done this since I + started" messages in the log, most notably in long running cf-agent + runs (longer than one minute). (Redmine #7933) +- TTY detection should be more reliable. (Redmine #7606) +- cf-promises -p cf now produces valid CFEngine code (Redmine #7956) +- Fixed ps options for FreeBSD to check processes only in current host and not in jails +- cf-runagent now properly supports multiple -D or -s arguments + (Redmine #7191) +- Fixed: Work around impaired class definition from augments + (Jira CFE-2333) +- Fixed "No such file or directory" LMDB error on heavily loaded hosts. + (Jira CFE-2300) +- Check for empty server response in RemoteDirList after decryption + (Redmine #7908) +- Small performance optimization when cf-execd scans emails before sending. +- Fixed handling of closed connections during transactions + (Redmine #7926) +- The core ps parsing engine used for processes promises + has been rewritten from scratch, and should be more robust than + before. (Jira CFE-2161) +- Fixed the lexer which could not handle empty newline(s) + before a @endif. +- groupexists() no longer fails to detect a group name + starting with a digit. (Jira CFE-2351) +- Fixed HP-UX specific bug that caused a lot of log output to disappear. +- Fixed unresolved variable (Redmine #7931) +- Changed: Suppress standard services noise on SUSE (Redmine #6968) +- Reduced verbosity of yum package module (Redmine #7485) +- cf-runagent: Allow connections to localhost instead of failing silently. +- Show errors regarding failure to copy extended attributes + when doing a local file copy. Errors could happen when copying + across two different mount points where the support for extended + attributes is different between the mount points. +- Fixed classes being set because of hash collision in the implementation. + (Redmine #7912) +- Fixed build failure on FreeBSD 7.1 (Redmine #7415) +- Improved logging when managing setuid/setgid +- Reduced verbosity of apt_get package module (Redmine #7485) +- packagesmatching() and packageupdatesmatching() should work + when new package promise is used. (Jira CFE-2246) +- Fixed bug which could render host unable to recover from a + syntax error, even if failsafe.cf was utilized. This could happen if + the file containing the syntax error was specified in the def.json + special file. (Redmine #7961) +- Prevent crash in cf-execd email code when policy server is not set. +- In case of networking error, assume checksum is wrong +- Fixed two cases where action_policy warn still produces errors + (Redmine #7274) +- Fixed bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) +- @if minimum_version now correctly ignores lines starting with `@` + (Redmine #7862) +- No longer hang when changing permissions/ownership on fifos + (Redmine #7030) +- `readfile()` and `read*list()` should print an error if they fail to read file. + (Redmine #7702) +- The isvariable() function call now correctly accepts all + array variables when specified inline. Previously it would not accept + certain special characters, even though they could be specified + indirectly by using a variable to hold it. (Redmine #7088) +- Fixed file descriptor leak when there are network errors. +- Improved robustness of process table parsing on Solaris. + (Jira CFE-2161) +- Installing packages containing version numbers using yum + now works correctly. (Redmine #7825) +- Parse def.json vars, classes and inputs from the C + code. This fixes a bug where certain entries in this file would be + parsed too late to have any effect on the evaluation. + (Redmine #7453, #7615) +- Change package modules permissions on hub package so that + hub can execute package promises. (Redmine #7602) +- Fixed: CFEngine choking on standard services (Jira CFE-2086) +- Fixed: cf-upgrade on SUSE +- Fixed: Stop CFEngine choking on systemctl output (Jira CFE-2806) +- storage: Properly initialize the list of current mounts + (Jira CFE-1803) +- Fixed bug which caused empty emails to be sent from cf-execd + if there was no previous output log and the new log was fully filtered + by email filters. (Jira ENT-2739) +- Don't send empty emails for logs where everything is filtered. + (Jira ENT-2739) +- Fixed intermittent error message of type: + "error: Process table lacks space for last columns: " + (Jira CFE-2371) +- Be less verbose if a network interface doesn't have a MAC address. + (Jira CFE-1995) + +## 3.8.2 + +Fixes: + +- Updated library dependencies to latest version. + Libraries upgraded: + - curl 7.47.0 + - LMDB 0.9.18 + - MySQL 5.1.72 + - OpenLDAP 2.4.44 + - OpenSSL 1.0.2g + - PostgreSQL 9.3.11 + - Redis 3.0.7 + - rsync 3.1.2 + + PHP was kept at 5.6.17 because of problems with the 5.6.19 version. + +- Reduced verbosity of apt_get package module (Redmine #7485) +- Reduced verbosity of yum package module (Redmine #7485) +- The isvariable() function call now correctly accepts all + array variables when specified inline. Previously it would not accept + certain special characters, even though they could be specified + indirectly by using a variable to hold it. (Redmine #7088) +- Don't follow symbolic links when copying extended attributes. +- Fixed a bug which sometimes caused package promises to be + skipped with "XX Another cf-agent seems to have done this since I + started" messages in the log, most notably in long running cf-agent + runs (longer than one minute). (Redmine #7933) +- Fixed bug which could render host unable to recover from a + syntax error, even if failsafe.cf was utilized. This could happen if + the file containing the syntax error was specified in the def.json + special file. (Redmine #7961) +- Changed: Policy files specified in the "inputs" section of + def.json will no longer be auto-loaded. One has to refer to the + $(def.augments_inputs) variable in the policy (the standard + masterfiles policies include this by default). This only affects + installations which are not based on the standard masterfiles, and + which are using the "inputs" field inside def.json. (Redmine #7961) +- Fixed file descriptor leak when there are network errors. +- Fixed cf-serverd error messages with classic protocol clients + (Redmine #7818) +- Installing packages containing version numbers using yum + now works correctly. (Redmine #7825) +- Fixed ps options for FreeBSD to check processes only in current host and not in jails +- Fixed build failure on FreeBSD 7.1 (Redmine #7415) +- Show errors regarding failure to copy extended attributes + when doing a local file copy. Errors could happen when copying + across two different mount points where the support for extended + attributes is different between the mount points. +- Fixed classes being set because of hash collision in the implementation. + (Redmine #7912) +- Allowed def.json up to 5MB instead of 4K. +- Fixed a regression which would sometimes cause "Permission + denied" errors on files inside directories with very restricted + permissions. (Redmine #7808) +- Changed: Suppress standard services noise on SUSE (Redmine #6968) + +Changes: + +- Changed: classesmatching(): order of classes changed + +## 3.8.1 + +Changes: + +- Upgraded CFEngine dependencies to the following versions: + - OpenSSL 1.0.2e + - PCRE 8.38 + - libxml2 2.9.3 + - OpenLDAP 2.4.43 + - libcurl 7.46.0 +- Upgraded LMDB to version 0.9.17. (Redmine #7879) + +Bug fixes: + +- @if minimum_version now correctly ignores lines starting with `@` + (Redmine #7862) +- Added guard for binary upgrade during bootstrap (Redmine #7861) +- Namespaced classes can now be specified on the command line. +- Fixed bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) +- Fixed two cases where action_policy warn still produces errors + (Redmine #7274) +- Parse def.json vars, classes and inputs from the C + code. This fixes a bug where certain entries in this file would be + parsed too late to have any effect on the evaluation. + (Redmine #7453, #7615) +- Fixed HP-UX specific bug that caused a lot of log output to disappear. +- Check for empty server response in RemoteDirList after decryption + (Redmine #7908) +- getvalues() will now return a list also for data containers, + and will descend recursively into the containers. (Redmine #7116) +- Define `(bootstrap|failsafe)_mode` during update.cf when triggerd from failsafe.cf + (Redmine #7861) + +## 3.8.0 + +New features/additions: + +- New feature: Bodies can now inherit attribute values from + other bodies by specifying "inherit_from" with the name of the body to + inherit from, plus any arguments it accepts. For example: + ``` + body classes myclasses + { + inherit_from => classes_generic("myname"); + } + ``` + (Redmine #4309) +- Added url_get() function. (Redmine #6480) +- Added @if feature() syntax + @if feature work like @if minimum_version but allows distinguishing + between features chosen at compile time. +- Extend module protocol to create persistent classes. + To use it, have the module print a line with "^persistence=" + before printing any class names. "persistence=0" goes back to non- + persistent classes. (Redmine #7302) +- Added: New results classes body (Redmine #7418) +- Added: Debug reports in cfe_internal_cleanup_agent_reports +- Added: Path to svcprop in stdlib +- Added: masterfiles-stage script to contrib +- Whitespace is now allowed in class expressions for + readability, between class names and operators. (Redmine #7152) + +Changes: + +- Changed: Clarify bootstrap/failsafe reports +- Changed: Improve in-line docs for internal log maintenance +- Changed: Improve efficiency and debug reports (Redmine #7527) +- Removed: 3.5 support from masterfiles policy framework +- Long promiser strings with multiple lines are now + abbreviated in logs. (Redmine #3964) +- Changed: Reunify Version based policy split +- Changed: Separate binary details from policy update (Redmine #7662) +- Remove /var/cfengine/cf3..runlog. (Redmine #6957) +- Changed: sys.libdir and sys.local_libdir to non version specific path + - sys.libdir now resolves to $(sys.inputdir)/lib + - sys.local_libdir now resolves to lib (Redmine #7559) +- Moved the following files to /var/cfengine/log/: + - /var/cfengine/promise_summary.log + - /var/cfengine/cfagent..log +- Changed: Separate binary details from policy update (Redmine #7662) +- Removed: Support for email settings from augments_file (Redmine #7682) + +Bug fixes: + +- It is possible to edit the same value in multiple regions + of one file. (Redmine #7460) +- Change package modules permissions on hub package so that + hub can execute package promises. (Rednime #7602) (Redmine #7602) +- Fixed exporting CSV reports through HTTPS. (Redmine #7267) +- cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor + multiple -D, -N and -s arguments (Redmine #7191) +- `readfile()` and `read*list()` should print an error if they fail to read file. + (Redmine #7702) +- No longer hang when changing permissions/ownership on fifos + (Redmine #7030) +- Fixed broken HA policy for 3rd disaster-recovery node. +- Fixed: Policy errors for 3.5 and 3.6 +- Mustache templates: Fix {{@}} key when value is not a + primitive. The old behavior, when iterating across a map or array of + maps, was to abort if the key was requested with {{@}}. The new + behavior is to always replace {{@}} with either the key name or the + iteration position in the array. An error is printed if {{@}} is used + outside of a Mustache iteration section. +- Fixed build with musl libc. (Redmine #7455) +- Fixed a bug which could cause daemons to not to be killed + correctly when upgrading or manually running "service cfengine3 stop". + (Redmine #7193) +- Fixed daemons not restarting correctly on upgrade on AIX. +- Package promise: Fix inability to install certain packages + with numbers. (Redmine #7421) +- Redmine #6027 Directories should no more be changed randomly + into files. (Redmine #6027) +- Improved cf-serverd's lock contention because of getpwnam() + call. (Redmine #7643) (Redmine #7643) +- action_policy "warn" now correctly produces warnings instead + of various other verbosity levels. (Redmine #7274) +- If there is an error saving a mustache template file + it is now logged with log-level error (was inform). +- The JSON parser now supports unquoted strings as keys. +- Reduced malloc() thread contention on heavily loaded + cf-serverd, by not exiting early in the logging function, if no message + is to be printed. (Redmine #7624) (Redmine #7624) +- Fixed a bug which caused daemons not to be restarted on + upgrade. (Redmine #7528) +- Included latest security updates for dependencies. +- Fixed bug which would cause bff and depot packages not to + run package scripts on removal. (Redmine #7193) +- Fixed upgrade causing error message under systemd because of open ports. +- Fixed several bugs which prevented CFEngine from loading + libraries from the correct location. This affected several platforms. + (Redmine #6708) +- Legacy package promise: Result classes are now defined if + the package being promised is already up to date. (Redmine #7399) +- failsafe.cf will be created when needed. (Redmine #7634) + (Redmine #7634) +- If file_select.file_types is set to symlink and there + are regular files in the scanned directory, CFEngine no longer + produces an unnecessary error message. (Redmine #6996) +- Fixed `AIX_PREINSTALL_ALREADY_DONE.txt: cannot create` error + message on AIX. +- Fixed package promise not removing dependent packages. (Redmine #7424) +- Fixed: Solaris packages no longer contain duplicate library + files, but instead symlinks to them. (Redmine #7591) +- Fixed select_class not setting class when used in common bundle with slist. + (Redmine #7482) +- Fixed "@endif" keyword sometimes being improperly processed + by policy parser. (Redmine #7413) +- Fixed noise from internal policy to upgrade windows agents + (Redmine #7456) +- cfruncommand now works if it contains spaces, with the TLS protocol. + (Redmine #7405) +- Fixed warning "Failed to parse csv file entry" with certain very long + commands promises. (Redmine #7400) +- CFEngine no longer erronously passes -M to useradd on HP-UX. (Redmine #6734) +- cf-monitord no longer complains about missing thermal zone files. + (Redmine #7238) +- systemd is now detected correctly if it is a symlink (Redmine #7297) +- TTY detection should be more reliable. (Redmine #7606) + (Redmine #7606) + +## 3.7.3 + +Fixes: + +- Reduced verbosity of yum package module (Redmine #7485) +- Reduced verbosity of apt_get package module (Redmine #7485) +- Upgraded dependencies to latest patch versions. + Upgraded libraries: + - curl 7.47.0 + - libxml2 2.9.3 + - LMDB 0.9.18 + - MySQL 5.1.72 + - OpenLDAP 2.4.44 + - OpenSSL 1.0.2g + - PCRE 8.38 + - PostgreSQL 9.3.11 + - Redis 2.8.24 + - rsync 3.1.2 + + PHP was kept at 5.6.17 because of problems with the 5.6.19 version. + +- Parse def.json vars, classes, and inputs in C (Redmine #7453) +- Namespaced classes can now be specified on the command line. +- getvalues() will now return a list also for data containers, + and will descend recursively into the containers. (Redmine #7116) +- @if minimum_version now correctly ignores lines starting with `@` + (Redmine #7862) +- Fixed definition of classes from augments file +- Don't follow symbolic links when copying extended attributes. +- Fixed ps options for FreeBSD to check processes only in current host and not in jails +- Fixed cf-serverd error messages with classic protocol clients + (Redmine #7818) +- Changed: Suppress standard services noise on SUSE (Redmine #6968) +- The isvariable() function call now correctly accepts all + array variables when specified inline. Previously it would not accept + certain special characters, even though they could be specified + indirectly by using a variable to hold it. (Redmine #7088) +- Show errors regarding failure to copy extended attributes + when doing a local file copy. Errors could happen when copying + across two different mount points where the support for extended + attributes is different between the mount points. +- Fixed bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) +- Fixed file descriptor leak when there are network errors. +- Fixed a regression which would sometimes cause "Permission + denied" errors on files inside directories with very restricted + permissions. (Redmine #7808) +- Check for empty server response in RemoteDirList after decryption + (Redmine #7908) +- Allowed def.json up to 5MB instead of 4K. +- Added guard for binary upgrade during bootstrap (Redmine #7861) +- Fixed HP-UX specific bug that caused a lot of log output to disappear. +- Fixed a bug which sometimes caused package promises to be + skipped with "XX Another cf-agent seems to have done this since I + started" messages in the log, most notably in long running cf-agent + runs (longer than one minute). (Redmine #7933) +- Define `(bootstrap|failsafe)_mode` during update.cf when triggerd from failsafe.cf + (Redmine #7861) +- Fixed two cases where action_policy warn still produces errors + (Redmine #7274) +- Fixed classes being set because of hash collision in the implementation. + (Redmine #7912) +- Fixed build failure on FreeBSD 7.1 (Redmine #7415) +- Installing packages containing version numbers using yum + now works correctly. (Redmine #7825) + +Changes: + +- Changed: classesmatching(): order of classes changed + +## 3.7.3 + +Fixes: + +- Reduced verbosity of yum package module (Redmine #7485) +- Reduced verbosity of apt_get package module (Redmine #7485) +- Upgraded dependencies to latest patch versions. + Upgraded libraries: + - curl 7.47.0 + - libxml2 2.9.3 + - LMDB 0.9.18 + - MySQL 5.1.72 + - OpenLDAP 2.4.44 + - OpenSSL 1.0.2g + - PCRE 8.38 + - PostgreSQL 9.3.11 + - Redis 2.8.24 + - rsync 3.1.2 + + PHP was kept at 5.6.17 because of problems with the 5.6.19 version. + +- Parse def.json vars, classes, and inputs in C (Redmine #7453) +- Namespaced classes can now be specified on the command line. +- getvalues() will now return a list also for data containers, + and will descend recursively into the containers. (Redmine #7116) +- @if minimum_version now correctly ignores lines starting with `@` + (Redmine #7862) +- Fixed definition of classes from augments file +- Don't follow symbolic links when copying extended attributes. +- Fixed ps options for FreeBSD to check processes only in current host and not in jails +- Fixed cf-serverd error messages with classic protocol clients + (Redmine #7818) +- Changed: Suppress standard services noise on SUSE (Redmine #6968) +- The isvariable() function call now correctly accepts all + array variables when specified inline. Previously it would not accept + certain special characters, even though they could be specified + indirectly by using a variable to hold it. (Redmine #7088) +- Show errors regarding failure to copy extended attributes + when doing a local file copy. Errors could happen when copying + across two different mount points where the support for extended + attributes is different between the mount points. +- Fixed bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) +- Fixed file descriptor leak when there are network errors. +- Fixed a regression which would sometimes cause "Permission + denied" errors on files inside directories with very restricted + permissions. (Redmine #7808) +- Check for empty server response in RemoteDirList after decryption + (Redmine #7908) +- Allowed def.json up to 5MB instead of 4K. +- Added guard for binary upgrade during bootstrap (Redmine #7861) +- Fixed HP-UX specific bug that caused a lot of log output to disappear. +- Fixed a bug which sometimes caused package promises to be + skipped with "XX Another cf-agent seems to have done this since I + started" messages in the log, most notably in long running cf-agent + runs (longer than one minute). (Redmine #7933) +- Define `(bootstrap|failsafe)_mode` during update.cf when triggerd from failsafe.cf + (Redmine #7861) +- Fixed two cases where action_policy warn still produces errors + (Redmine #7274) +- Fixed classes being set because of hash collision in the implementation. + (Redmine #7912) +- Fixed build failure on FreeBSD 7.1 (Redmine #7415) +- Installing packages containing version numbers using yum + now works correctly. (Redmine #7825) + +Changes: + +- Changed: classesmatching(): order of classes changed + +## 3.7.2 + +Bug fixes: + +- `readfile()` and `read*list()` should print an error if they fail to read file. + (Redmine #7702) +- Fixed `AIX_PREINSTALL_ALREADY_DONE.txt: cannot create` error + message on AIX. +- If there is an error saving a mustache template file + it is now logged with log-level error (was inform). +- Changed: Clarify bootstrap/failsafe reports +- Fixed several bugs which prevented CFEngine from loading + libraries from the correct location. This affected several platforms. + (Redmine #6708) +- If file_select.file_types is set to symlink and there + are regular files in the scanned directory, CFEngine no longer + produces an unnecessary error message. (Redmine #6996) +- Fixed: Solaris packages no longer contain duplicate library + files, but instead symlinks to them. (Redmine #7591) +- cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor + multiple -D, -N and -s arguments (Redmine #7191) +- Fixed "@endif" keyword sometimes being improperly processed + by policy parser. (Redmine #7413) +- It is possible to edit the same value in multiple regions + of one file. (Redmine #7460) +- Fixed select_class not setting class when used in common bundle with slist. + (Redmine #7482) +- Fixed broken HA policy for 3rd disaster-recovery node. +- Directories should no more be changed randomly + into files. (Redmine #6027) +- Included latest security updates for 3.7. +- Reduced malloc() thread contention on heavily loaded + cf-serverd, by not exiting early in the logging function, if no message + is to be printed. (Redmine #7624) +- Improved cf-serverd's lock contention because of getpwnam() + call. (Redmine #7643) +- action_policy "warn" now correctly produces warnings instead + of various other verbosity levels. (Redmine #7274) +- Changed: Improve efficiency and debug reports (Redmine #7527) +- Change package modules permissions on hub package so that + hub can execute package promises. (Redmine #7602) +- No longer hang when changing permissions/ownership on fifos + (Redmine #7030) +- Fixed exporting CSV reports through HTTPS. (Redmine #7267) +- failsafe.cf will be created when needed. (Redmine #7634) +- Mustache templates: Fix {{@}} key when value is not a + primitive. The old behavior, when iterating across a map or array of + maps, was to abort if the key was requested with {{@}}. The new + behavior is to always replace {{@}} with either the key name or the + iteration position in the array. An error is printed if {{@}} is used + outside of a Mustache iteration section. +- Legacy package promise: Result classes are now defined if + the package being promised is already up to date. (Redmine #7399) +- TTY detection should be more reliable. (Redmine #7606) + +Masterfiles: + +- Added: Path to svcprop in stdlib +- Added: New results classes body [] (Redmine #7418, #7481) +- Removed: Support for email settings from augments_file (Redmine #7682) + +## 3.7.1 + +Bug fixes: + +- Fixed daemons not restarting correctly on upgrade on AIX. (Redmine #7550) +- Fixed upgrade causing error message under systemd because of open ports. +- Fixed build with musl libc. (Redmine #7455) +- Long promiser strings with multiple lines are now + abbreviated in logs. (Redmine #3964) +- Fixed a bug which could cause daemons to not to be killed + correctly when upgrading or manually running "service cfengine3 stop". + (Redmine #7193) +- Package promise: Fix inability to install certain packages + with numbers. +- Fixed package promise not removing dependent packages. (Redmine #7424) +- Fixed warning "Failed to parse csv file entry" with certain very long + commands promises. (Redmine #7400) +- Fixed misaligned help output in cf-hub. (Redmine #7273) +- Augmenting inputs from the augments_file (Redmine #7420) +- Added support for failover to 3rd HA node located outside cluster. +- Upgraded all dependencies for patch release. +- Fixed a bug which caused daemons not to be restarted on + upgrade. (Redmine #7528) + +## 3.7.0 + +New features: + +- New package promise implementation. + The syntax is much simpler, to try it out, check out the syntax: + + ``` + packages: + "mypackage" + policy => "absent/present", + + # Optional, default taken from common control + package_module => apt_get, + + # Optional, will only match exact version. May be + # "latest". + version => "32.0", + + # Optional. + architecture => "x86_64"; + ``` + +- Full systemd support for all relevant platforms +- New classes to determine whether certain features are enabled: + - feature_yaml + - feature_xml + + For the official CFEngine packages, these are always enabled, but + packages from other sources may be built without the support. + +- New readdata() support for generic data input (CSV, YAML, JSON, or auto) +- YAML support: new readyaml() function and in readdata() +- CSV support: new readcsv() function and in readdata() +- New string_mustache() function +- New data_regextract() function +- eval() can now be called with "class" as the "mode" argument, which + will cause it to return true ("any") if the calculated result is + non-zero, and false ("!any") if it is zero. +- New list_ifelse() function +- New mapdata() function as well as JSON support in maparray(). +- filestat() function now supports "xattr" argument for extended + attributes. +- "ifvarclass" now has "if" as an alias, and "unless" as an inverse + alias. +- Ability to expand JSON variables directory in Mustache templates: + Prefix the name with `%` for multiline expansion, `$` for compact + expansion. +- Ability to expand the iteration _key_ in Mustache templates with @ +- Canonical JSON output: JSON output has reliably sorted keys so the + same data structure will produce the same JSON every time. +- New "@if minimum_version(x.x)" syntax in order to hide future language + improvements from versions that don't understand them. +- Compile time option (--with-statedir) to + override the default state/ directory path. +- Fixed error messages/ handling in process signalling which no longer + allowed any signals to fail silently +- Also enable shortcut keyword for cf-serverd classic protocol, eg to + simplify the bootstrap process for clients that have different + sys.masterdir settings (Redmine #3697) +- methods promises now accepts the bundle name in the promiser string, + as long as it doesn't have any parameters. +- In a services promise, if the `service_method` bundle is not specified, + it defaults to the promiser string (canonified) with `"service_"` as a + prefix. The bundle must be in the same namespace as the promise. +- Inline JSON in policy files: surrounding with parsejson() is now + optional _when creating a new data container_. +- New data_expand() function to interpolate variables in a data container. +- Added configurable network bandwidth limit for all outgoing + connections ("bwlimit" attribute in "body common control") . To + enforce it in both directions, make sure the attribute is set on both + sides of the connection. +- Secure bootstrap has been facilitated by use of + "cf-agent --boostrap HUB_ADDRESS --trust-server=no" +- Implemented new TLS-relevant options (Redmine #6883): + - body common control: tls_min_version + - body server control: allowtlsversion + - body common control: tls_ciphers + - body server control: allowciphers (preexisting) + +Changes: + +- Improved output format, less verbose, and messages are grouped. +- cf-execd: agent_expireafter default was changed to 120 minutes + (Redmine #7113) +- All embedded databases are now rooted in the state/ directory. +- TLS used as default for all outgoing connections. +- process promise now reports kept status instead of repaired if a + signal is not sent, even if the restart_class is set. The old + behavior was to set the repaired status whenever the process was not + running. (Redmine#7216). +- Bootstrapping requires keys to be generated in advance using cf-key. +- Disabled class set on reverse lookup of interfaces IP addresses. + (Redmine #3993, Redmine #6870) +- Define a hard class with just the OS major version on FreeBSD. +- Abort cf-agent if OpenSSL's random number generator can't + be seeded securely. +- Masterfiles source tarball now installs using the usual commands + "./configure; make install". +- Updated Emacs syntax highlighting template to support the latest + syntax enhancements in 3.7. + +Deprecations: + +- Arbitrary arguments to cfruncommand (using "cf-runagent -o") are + not acceptable any more. (Redmine #6978) +- 3.4 is no longer supported in masterfiles. + +Bug fixes: + +- Fixed server common bundles evaluation order (Redmine#7211). +- Limit LMDB disk usage by preserving sparse areas in LMDB files + (Redmine#7242). +- Fixed LMDB corruption on HP-UX 11.23. (Redmine #6994) +- Fixed insert_lines failing to converge if preserve_block was used. + (Redmine #7094) +- Fixed init script failing to stop/restart daemons on openvz/lxc + hosts. (Redmine #3394) +- rm_rf_depth now deletes base directory as advertised. (Redmine #7009) +- Refactored cf-agent's connection cache to properly differentiate + hosts using all needed attributes like host and port. + (Redmine #4646) +- Refactored lastseen database handling to avoid inconsistencies. + (Redmine #6660) +- cf-key --trust-key now supports new syntax to also update the + lastseen database, so that clients using old protocol will trust + the server correctly. +- Fixed a bug which sometimes caused an agent or daemon to kill or stop + itself. (Redmine #7075, #7244) +- Fixed a bug which made it difficult to kill CFEngine daemons, + particularly cf-execd. (Redmine #6659, #7193) +- Fixed a bug causing systemd not to be detected correctly on Debian. + (Redmine #7297) +- "cf-promises -T" will now correctly report the checked out commit, + even if you haven't checked out a Git branch. (Redmine #7332) +- Reduced verbosity of harmless errors related to socket timeouts and + missing thermal zone files. (Redmine #6486 and #7238) + +Masterfiles: + +Added: + +- Support for user specified overring of framework defaults without + modifying policy supplied by the framework itself (see + example_def.json) +- Support for def.json class augmentation in update policy +- Run vacuum operation on postgresql every night as a part of + maintenance. +- Added measure_promise_time action body to lib (3.5, 3.6, 3.7, 3.8) +- New negative class guard cfengine_internal_disable_agent_email so + that agent email can be easily disabled by augmenting def.json + +Changed: + +- Relocated def.cf to controls/VER/ +- Relocated update_def to controls/VER +- Relocated all controls to controls/VER +- Only load cf_hub and reports.cf on CFEngine Enterprise installs +- Relocated acls related to report collection from bundle server + access_rules to controls/VER/reports.cf into bundle server + report_access_rules +- Re-organized cfe_internal splitting core from enterprise specific + policies and loading the appropriate inputs only when necessary +- Moved update directory into cfe_internal as it is not generally + intended to be modified +- services/autorun.cf moved to lib/VER/ as it is not generally intended + to be modified +- To improve predictibility autorun bundles are activated in + lexicographical order +- Relocated services/file_change.cf to cfe_internal/enterprise. This + policy is most useful for a good OOTB experience with CFEngine + Enterprise Mission Portal. +- Relocated service_catalogue from promsies.cf to services/main.cf. It is + intended to be a user entry. This name change correlates with the main + bundle being activated by default if there is no bundlesequence + specified. +- Reduced benchmarks sample history to 1 day. +- Update policy no longer generates a keypair if one is not found. + (Redmine: #7167) +- Relocated cfe_internal_postgresql_maintenance bundle to lib/VER/ +- Set postgresql_monitoring_maintenance only for versions 3.6.0 and + 3.6.1 +- Move hub specific bundles from lib/VER/cfe_internal.cf into + lib/VER/cfe_internal_hub.cf and load them only if policy_server policy + if set. +- Re-organized lib/VER/stdlib.cf from lists into classic array for use + with getvalues + +Removed: + +- Diff reporting on /etc/shadow (Enterprise) +- Update policy from promise.cf inputs. There is no reason to include + the update policy into promsies.cf, update.cf is the entry for the + update policy +- `_not_repaired` outcome from `classes_generic` and `scoped_classes` generic + (Redmine: # 7022) + +Fixes: + +- standard_services now restarts the service if it was not already + running when using service_policy => restart with chkconfig (Redmine + #7258) + +## 3.6.5 + +Features: + +- Introduced "systemd" hard class. (Redmine #6995) +- Added paths to dtrace, zfs and zpool on FreeBSD in masterfiles. + +Bug fixes: + +- Fixed build error on certain RHEL5 and SLES10 setups. (Redmine #6841) +- Fixed a bug which caused dangling symlinks not to be removed. + (Redmine #6582) +- Fixed data_readstringarrayidx function not preserving the order of the + array it's producing. (Redmine #6920) +- Fixed a bug which sometimes caused CFEngine to kill the wrong daemon + if both the host and a container inside the host were running + CFEngine. (Redmine #6906) +- Made sure the rm_rf_depth bundle also deletes the base directory. + (Redmine #7009) +- Fixed monitord reporting wrongly on open ports. (Redmine #6926) +- Skip adding the class when its name is longer than 1024 characters. + Fixed core dump when the name is too large. (Redmine #7013) +- Fixed detection of stopped process on Solaris. (Redmine #6946) +- Fixed infinite loop (Redmine #6992) plus a couple more minor + bugs in edit_xml promises. + +## 3.6.4 + +Features: + +- Introduced users promises support on HP-UX platform. +- Introduced process promises support on HP-UX platform. + +Bug fixes: + +- Fixed bug on FreeBSD which sometimes led to the wrong process being + killed (Redmine #2330) +- Fixed package version comparison sometimes failing with rpm package + manager (Redmine #6807) +- Fixed a bug in users promises which would sometimes set the wrong + password hash if the user would also be unlocked at the same time. +- Fixed a bug on AIX which would occasionally kill the wrong process. +- Improved error message for functions that require an absolute path. + (Redmine #6877) +- Fixed some spelling errors in examples. +- Fixed error in out-of-tree builds when building cf-upgrade. +- Fixed a bug which would make cf-agent exit with an error if it was + built with a custom log directory, and that directory did not exist. +- Fixed ordering of evaluating promises when depends_on is used. + (Redmine #6484, Redmine #5462) +- Skip non-empty directories silently when recursively deleting. + (Redmine #6331) +- Fixed memory exhaustion with list larger than 4994 items. + (Redmine # 6672) +- Fixed cf-execd segfault on IP address detection (Redmine #6905). +- Fixed hard class detection of RHEL6 ComputeNode (Redmine #3148). + +## 3.6.3 + +New features: + +- Support for HP-UX 11.23 and later +- Experimental support for Red Hat Enterprise Linux 7 + +Bug fixes: + +- Fixed getindices on multi-dimensional arrays (Redmine #6779) +- Fixed mustache template method to run in dryrun mode (Redmine #6739) +- Set mailto and mailfrom settings for execd in def.cf (Redmine #6702) +- Fixed conflation of multi-index entries in arrays (Redmine #6674) +- Fixed promise locking when transferring using update.cf (Redmine #6623) +- Update JSON parser to return an error on truncation (Redmine #6608) +- Fixed sys.hardware_addresses not expanded (Redmine #6603) +- Fixed opening database txn /var/cfengine/cf_lastseen.lmdb: + MDB_READERS_FULL when running cf-keys --show-hosts (Redmine #6602) +- Fixed segfault (Null pointer dereference) when select_end in + delete_lines never matches (Redmine #6589) +- Fixed max_file_size => "0" not disabling or allowing any size + (Redmine #6588) +- Fixed ifvarclass, with iteration over list, failing when deleting + files with time condition (Redmine #6577) +- Fixed classes defined with "or" constraint are never set if any value + doesn't evaluate to a scalar (Redmine #6569) +- Update "mailfrom" default in default policy (Redmine #6567) +- Fixed logrotate ambiguity of filename (Redmine #6563) +- Fixed parsing JSON files (Redmine #6549) +- Reduced write count activity to /var partition (Redmine #6523) +- Fixed files delete attribute incorrectly triggering promise_kept + (Redmine #6509) +- Update services bundle output related to chkconfig when run in + inform mode. (Redmine #6492) +- Fixed Solaris serverd tests (Redmine #6406) +- Fixed broken bechaviour of merging arrays with readstringarray + (Redmine #6369) +- Fixed ifelapsed bug with bundle nesting (Redmine #6334) +- Fixed handling cf_null in bundlesequence (Redmine #6119) +- Fixed maparray reading whole input array when using subarray + (Redmine #6033) +- Fixed directories being randomly changed to files (Redmine #6027) +- Update defaults promise type to work with classes (Redmine #5748) +- systemd integration in services promises (Redmine #5415) +- Fixed touch attribute ignoring action = warn_only (Redmine #3172) +- Fixed 4KB string limit in functions readfile, string_downcase, + string_head, string_reverse, string_length, string_tail, + string_upcase (Redmine #2912) + +## 3.6.2 + +Bug fixes: + +- Don't regenerate software_packages.csv every time (Redmine #6441) +- Improved verbose message for package_list_command +- Fixed missing log output on AIX (Redmine #6434) +- Assorted fixes to dirname() esp on Windows (Redmine #4716) +- Fixed package manager detection +- Fixed build issues on FreeBSD +- Allowed copying of dead symbolic links (Redmine #6175) +- Preserve order in readstringarrayidx (Redmine #6466) +- Fixed passing of unexpanded variable references to arrays + (Redmine #5893) +- Use entries for new `{admin,deny}_{ips,hostnames}` constraints in + the relevant legacy lists (Redmine #6542) +- Cope with ps's numeric fields overflowing to the right +- Interpret failing function calls in ifvarclass as class not set + (Redmine #6327) +- Remove unexpanded lists when extending lists (Redmine #6541) +- Infer start-time of a process from elapsed when needed + (Redmine #4094) +- Fixed input range definition for laterthan() function (Redmine #6530) +- Don't add trailing delimiter when join()'ing lists ending with a + null-value (Redmine #6552) +- 9999999999 (ten 9s) or higher has been historically used as an upper + bound in CFEngine code and policy but because of overflow on 32-bit + platforms it caused problems with big numbers. Fixed in two ways: + first change all existing policy uses to 999999999 (nine 9s instead + of eleven 9s), second fix the C code to not wrap-around in case of + overflow, but use the LONG_MAX value (Redmine #6531). +- cf-serverd and other daemons no longer reload their configuration + every minute if CFEngine is built with an inputs directory outside + of the work directory (not the default). (Redmine #6551) + +## 3.6.1 + +New features: + +- Introduced Solaris and AIX support into the 3.6 series, with many associated build and + bug fixes. + +Changes: + +- Short-circuit evaluation of classes promises if class is already set (Redmine #5241) +- Fixed to assume all non-specified return codes are failed in commands promises (Redmine #5986) +- cf-serverd logs reconfiguration message to NOTICE (was INFO) so that it's always logged in syslog + +Bug fixes: + +- File monitoring has been completely rewritten (changes attribute in files promise), which + eliminates many bugs, particularly regarding files that are deleted. Upgrading will keep + all monitoring data, but downgrading again will reinitialize the DB, so all files will be + reported as if they were new. (Redmine #2917) +- $(this.promiser) expands in files promises for `transformer`, `edit_template`, + `copy_from.source`, `file_select.exec_program`, `classes` and `action` bodies + (Redmine #1554, #1496, #3530, #1563) +- `body changes` notifies about disappeared files in file monitoring (Redmine #2917) +- Fixed CFEngine template producing a zero sized file (Redmine #6088) +- Added `0-9 A-Z _` to allowed context of module protocol (Redmine #6063) +- Extend ps command column width and prepend zone name on Solaris +- Fixed strftime() function on Solaris when called with certain specifiers. +- Fixed users promise bug regarding password hashes in a NIS/NSS setup. +- Fixed $(sys.uptime), $(sys.systime) and $(sys.sysday) in AIX. (Redmine #5148, #5206) +- Fixed processes_select complaining about "Unacceptable model uncertainty examining processes" (Redmine #6337) +- ps command for linux has been changed to cope with big rss values (Redmine #6337) +- Address ps -axo shift on FreeBSD 10 and later (Redmine #5667) +- methods and services promises respect action_policy => "warn" (Redmine #5924) +- LMDB should no longer deadlock if an agent is killed on the hub while holding the DB lock. + Note that the change only affects binary packages shipped by CFEngine, since the upstream + LMDB project has not yet integrated the change. (Redmine #6013) + +## 3.6.0 + +Changes: + +- Changes to logging output + - Added process name and pid in syslog message (GitHub #789) + - cf-serverd logging levels are now more standardised: + - INFO logs only failures + - VERBOSE logs successful requests as well + - DEBUG logs actual protocol traffic. + - cf-serverd now logs the relevant client IP address on + each message. + - Logging contexts to local database (cf_classes.tcdb) has been deprecated. + - `usebundle` promisees are logged for all the bundle promises + - output from `reports` promises has nothing prefixed except `R: ` + - a log line with stack path is generated when the promise type evaluated changes +- LMDB (symas.com/mdb) is the default database for local data storage : use version 0.9.9 or later + cf-agent --self-diagnostics (-x) is only implemented for TCDB, not for LMDB +- port argument in readtcp() and selectservers() may be a + service name (e.g. "http", "pop3"). +- Enable source file in agent copy_from promises to be a relative path. + - file "changes" reporting now reports with log level "notice", instead of "error". +- process_results default to AND'ing of set attributes if not specified (Redmine #3224) +- interface is now canonified in sys.hardware_mac[interface] to align with + sys.ipv4[interface] (Redmine #3418) +- cf-promises no longer errors on missing bodies when run without --full-check (-c) +- Linux flavor "SUSE" now correctly spelled with all uppercase in variables and class names + (Redmine #3734). The "suse" lowercase version is also provided for convenience (Redmine #5417). +- `$(this.promise_filename)` and `$(..._dirname)` variables are now absolute paths. (Redmine #3839) +- Including the same file multiple times in `body control inputs` is not an error +- portnumber in body copy_from now supports service names like + "cfengine", "pop3" etc, check /etc/services for more. +- The failsafe.cf policy, run on bootstrap and in some other + unusual cases, has been extracted from C code into libpromises/failsafe.cf +- masterfiles + - cf_promises_validated is now in JSON format + - timestamp key is timestamp (sec since unix epoch) of last time validated + - the masterfiles now come from https://github.com/cfengine/masterfiles and are + not in the core repository +- cf-serverd calls cf-agent with -Dcfruncommand when executing cf-runagent requests +- Marked as removed: promise_notkept_log_include, promise_notkept_log_exclude, promise_repaired_log_include, + promise_repaired_log_exclude, classes_include, classes_exclude, variables_include, + variables_exclude attributes from report_data_select body (syntax is valid but not functional). + They have been replaced by the following attributes: promise_handle_include, + promise_handle_exclude, metatags_include, metatags_exclude. + +New features: + +- New promise type "users" for managing local user accounts. +- TLS authentication and fully encrypted network protocol. + Additions specific to the new type of connections: + - New attribute "allowlegacyconnects" in body server control, + which enables serving policy via non-latest CFEngine protocol, + to the given list of hosts. If the option is absent, it + defaults to allow all hosts. To refuse non-TLS connections, + specify an empty list. + - New attribute "protocol_version" in body copy_from, and body + common control, which defines the preferred protocol for + outgoing connections.. Allowed values at the moment: "0" or + "undefined", "classic" or "1", "latest" or "2". By leaving the + copy_from option as undefined the common control option is + used, and if both are undefined then classic protocol is used + by default. + - The new networking protocol uses TLS for authentication, + after which all dialog is encrypted within the established + TLS session. cf-serverd is still able to speak the legacy + protocol with old agents. + - The `skipverify` option in `body server control` is + deprecated and only left for compatibility; it does + nothing + - cf-serverd does not hang up the connection if some request + fails, so that the client can add more requests. + - For the connections using the new protocol, all of the + paths in bundle server access_rules now differentiate + between a directory and a file using the trailing + slash. If the path exists then this is auto-detected and + trailing slash appended automatically. You have to append + a trailing slash manually to an inexistent or symbolic + path (e.g. "/path/to/$(connection.ip)/") to force + recursive access. +- New in `access` promises for `bundle server access_rules` + - Attributes "admit_ips", "admit_hostnames", "admit_keys", + "deny_ips", "deny_hostnames", "deny_keys" + - "admit_keys" and "deny_keys" add the new functionality + of controlling access according to host identity, + regardless of the connecting IP. + - For these new attributes, regular expressions + are not allowed, only CIDR notation for `"admit/deny_ips"`, exact + `"SHA=..."` strings for `"admit/deny_keys"`, and exact hostnames + (e.g. "cfengine.com") or subdomains (starting with dot, + e.g. ".cfengine.com") for `"admit/deny"_hostnames`. Same rules + apply to `deny_*` attributes. + - These new constraints and the paths in access_rules, can contain + special variables "$(connection.ip)", "$(connection.hostname)", + "$(connection.key)", which are expanded dynamically for every + received connection. + - For connections using the new protocol, "admit" and "deny" + constraints in bundle server access_rules are being phased + out, preferred attributes are now "admit_ips", "deny_ips", + "admit_hostnames", "deny_hostnames", "admit_keys", + "deny_keys". + - New "shortcut" attribute in bundle server access_rules used to + dynamically expand non-absolute request paths. +- masterfiles + - standard library split: lib/3.5 (compatibility) and lib/3.6 (mainline) + - many standard library bundles and bodies, especially packages- and file-related, + were revised and fixed + - supports both Community and Enterprise + - new `inventory/` structure to provide OS, dmidecode, LSB, etc. system inventory + (configured mainly in def.cf) + - cf_promises_release_id contains the policy release ID which is the GIT HEAD SHA + if available or hash of tree + - a bunch'o'bundles to make starting with CFEngine easier: + - file-related: file_mustache, file_mustache_jsonstring, file_tidy, dir_sync, file_copy, + file_link, file_hardlink, file_empty, file_make + - packages-related: package_absent, package_present, package_latest, + package_specific_present, package_specific_absent, package_specific_latest, package_specific + - XML-related: xml_insert_tree_nopath, xml_insert_tree, xml_set_value, xml_set_attribute + - VCS-related: git_init, git_add, git_checkout, git_checkout_new_branch, + git_clean, git_stash, git_stash_and_clean, git_commit, git + - process-related: process_kill + - other: cmerge, url_ping, logrotate, prunedir +- New command line options for agent binaries + - New options to cf-promises + - `--show-classes` and `--show-vars` + - `--eval-functions` controls whether cf-promises should evaluate functions + - Colorized output for agent binaries with command line option `--color` + (auto-enabled if you set CFENGINE_COLOR=1) +- New language features + - New variable type `data` for handling of structured data (ie JSON), + including supporting functions: + - `data_readstringarray` - read a delimited file into a data map + - `data_readstringarrayidx` - read a delimited file into a data array + - `datastate` - create a data variable with currently set classes and variables + - `datatype` - determine the type of the top element of a container + - `format` - %S can be used to serialize `data` containers into a string + - `mergedata` - merge two data containers, slists/ilists/rlists, or "classic" + arrays into a data container + - `parsejson` - create a data container from a JSON string + - `readjson` - create a data container from a file that contains JSON + - `storejson` - serialize a data container into a string + - Most functions operating on lists can also operate on data containers + - pass a data container to a bundle with the @(container) notation + - the module protocol accepts JSON for data containers with the `%` sigil + - Tagging of classes and variables allows annotating of language construct with + meta data; supporting functionality: + - The module protocol in `commands` promises has been extended to allow setting + of tags of created variables and classes, and the context of created variables + - `getclassmetatags` - returns list of meta tags for a class + - `getvariablemetatags` - returns list of meta tags for a variable + - `body file control` has an `inputs` attribute to include library files and other + dependencies + - bundlesequences can be built with bundlesmatching() based on bundle name and tags +- New attributes in existing promise types and bodies + - New option `preserve_all_lines` for insert_type in insert_lines promises + - Caching of expensive system functions to avoid multiple executions of + execresult() etc, can be controlled via cache_system_functions attribute in + body common control + - New option `mailsubject` in body executor control allows defining the subject + in emails sent by CFEngine + - Support for Mustache templates in `files` promises; use `template_method` and + `template_data` attributes. Without `template_data` specified, uses datastate(). + - New and improved functions + - `bundlesmatching` - returns list of defined bundles matching a regex and tags + - `canonifyuniquely` - converts a string into a unique, legal class name + - `classesmatching` - returns list of set classes matching a regex and tags + - `eval` - evaluates mathematical expressions; knows SI k, m, g quantifiers, e.g. "100k" + - `findfiles` - list files matching a search pattern; use `**` for recursive searches + - `makerule` - evaluates whether a target file needs to be rebuilt from sources + - `max`, `min` - returns maximum and minimum of the numbers in a container or list + (sorted by a `sort` method) + - `mean` - returns the mean of the numbers in a container or list + - `nth` - learned to look up by key in a data container holding a map + - `packagesmatching` - returns a filtered list of installed packages. + - `readfile` - learned to read system files of unknown size like those in /proc + - `sort` - can sort lexicographically, numerically (int or real), by IP, or by MAC + - `string_downcase`, `string_upcase` - returns the lower-/upper-case version of a + string + - `string_head`, `string_tail` - returns the beginning/end of a string + - `string_length` - returns the length of a string + - `string_reverse` - reverses a string + - `string_split` - improved implementation, deprecates `splitstring` + - `variablesmatching` - returns a list of variables matching a regex and tags + - `variance` - returns the variance of numbers in a list or container +- New hard classes + - Introduced alias `policy_server` for context `am_policy_hub` (the latter will + be deprecated) + - all the time-based classes have GMT equivalents +- New variables + - `sys.bindir` - the location of the CFEngine binaries + - `sys.failsafe_policy_path` - the location of the failsafe policy file + - `sys.inputdir` - the directory where CFEngine searches for policy files + - `sys.key_digest` - the digest of the host's cryptographic key + - `sys.libdir`, `sys.local_libdir` - the location of the CFEngine libraries + - `sys.logdir` - the directory where the CFEngine log files are saved + - `sys.masterdir` - the location of masterfiles on the policy server + - `sys.piddir` - the directory where the daemon pid files are saved + - `sys.sysday` - the number of days since the beginning of the UNIX epoch + - `sys.systime` - the number of seconds since the beginning of the UNIX epoch + - `sys.update_policy_path` - the name of the update policy file + - `sys.uptime` - the number of minutes the host has been online + - `this.promise_dirname` - the name of the file in which the current promise + is defined + - `this.promiser_uid` - the ID of the user running cf-agent + - `this.promiser_gid` - the group ID of the user running cf-agent + - `this.promiser_ppid` - the ID of the parent process running cf-agent + +Deprecations: + +- `splitstring` - deprecated by `string_split` +- `track_value` +- `skipverify` + +Bug fixes: for a complete list of fixed bugs, see Redmine at https://cfengine.com/dev + +- Various fixes in evaluation and variable resolution +- Improved performance of list iteration (Redmine #1875) +- Removed limitation of input length to internal buffer sizes + - directories ending with "/" are not ignored + - lsdir() always return a list now, never a scalar +- `abortclasses` fixed to work in common bundles and other cases +- Namespaced `edit_line` bundles now work (Redmine#3781) +- Lists are interpolated in correct order (Redmine#3122) +- cf-serverd reloads policies properly when they change +- Lots of leaks (memory and file descriptor) fixed + +## 3.5.3 + +Changes: + +- Improved security checks of symlink ownership. A symlink created by a user pointing + to resources owned by a different user will no longer be followed. +- Changed the way package versions are compared in package promises. (Redmine #3314) + In previous versions the comparison was inconsistent. This has been fixed, but may + also lead to behavior changes in certain cases. In CFEngine 3.5.3, the comparison + works as follows: + ``` + + ``` + For instance: + ``` + apache-2.2.31 ">=" "2.2.0" + ``` + will result in the package being installed. + +Bug fixes: + +- Fixed cf-monitord crash due to incorrect array initialization (Redmine #3180) +- Fixed cf-serverd stat()'ing the file tree every second (Redmine #3479) +- Correctly populate sys.hardware_addresses variable (Redmine #2936) +- Added support for Debian's GNU/kfreebsd to build system (Redmine #3500) +- Fixed possible stack corruption in guest_environments promises (Redmine #3552) +- Work-around hostname trunctation in HP-UX's uname (Redmine #3517) +- Fixed body copy purging of empty directories (Redmine #3429) +- Made discovery and loading of avahi libraries more robust +- Compile and packaging fixes for HP-UX, AIX and Solaris +- Fixed fatal error in lsdir() when directory doesn't exist (Redmine #3273) +- Fixed epoch calculation for stime inrange calculation (Redmine #2921) + +## 3.5.2 + +Bug fixes: + +- Fixed delayed abortclasses checking (Redmine #2316, #3114, #3003) +- Fixed maplist arguments bug (Redmine #3256) +- Fixed segfaults in cf-pomises (Redmine #3173, 3194) +- Fixed build on Solaris 10/SmartOS (Redmine #3097) +- Sanitize characters from /etc/issue in sys.flavor for Debian (Redmine #2988) +- Fixed segfault when dealing with files or data > 4K (Redmine #2912, 2698) +- Don't truncate keys to 126 characters in getindices (Redmine #2626) +- Files created via `log_*` actions now have mode 600 (Redmine #1578) +- Fixed wrong log message when a promise is ignored due to `ifvarclass` not matching +- Fixed lifetime of persistent classes (Redmine #3259) +- Fixed segfault when process_select body had no process_result attribute + Default to AND'ed expression of all specified attributes (Redmine #3224) +- Included system message in output when acl promises fail +- Fixed invocation of standard_services bundle and corresponding promise compliance (Redmine #2869) + +## 3.5.1 + +Changes: + +- File changes are logged with log level Notice, not Error +- The CFEngine Standard Library in masterfiles/libraries is now split into + promise-type specific policy files, and lives in a version-specific directory. + This should have no impact on current code, but allows more granular include of + needed stdlib elements (Redmine #3044) + +Bug fixes: + +- Fixed recursive copying of files (Redmine #2965) +- Respect classes in templates (Redmine ##2928) +- Fixed timestamps on Windows (Redmine #2933) +- Fixed non-root cf-agent flooding syslog (Redmine #2980) +- Fixed email flood from cf-execd due to timestamps in agent output (Redmine #3011) +- Preserve security context when editing or copying local files (Redmine #2728) +- Fixed path for sys.crontab on redhat systems (Redmine #2553) +- Prevent incorrect "insert_lines promise uses the same select_line_matching anchor" warning (Redmine #2778) +- Fixed regression of setting VIPADDRESS to 127.0.0.1 (Redmine #3010) +- Fixed "changes" promise not receiving status when file is missing (Redmine #2820) +- Fixed symlinks being destroyed when editing them (Redmine #2363) +- Fixed missing "promise kept" status for the last line in a file (Redmine #2943) + +## 3.5.0 + +New features: + +- classes promises now take an optional scope constraint. +- New built-in functions: every, none, some, nth, sublist, uniq, filter + - every + - none + - some + - nth + - sublist + - uniq + - filter + - classesmatching + - strftime + - filestat + - ifelse + - maparray + - format +- cf-promises flag --parse-tree is replaced by --policy-output-format=, requiring the + user to specify the output format (none, cf, json) +- cf-promises allows partial check of policy (without body common control) without integrity check; + --full-check enforces integrity check +- Agent binaries support JSON input format (.json file as generated by cf-promises) +- cf-key: new options --trust-key/-t and --print-digest/-p +- Class "failsafe_fallback" is defined in failsafe.cf when main policy contains errors and + failsafe is run because of this +- Added scope attribute for body classes (Redmine #2013) +- Better diagnostics of parsing errors +- Error messages from parser now show the context of error +- New cf-agent option: --self-diagnostics +- New output format, and --legacy-output +- Warnings for cf-promises. +- Enable zeroconf-discovery of policy hubs for automatic bootstrapping + if Avahi is present +- Support for sys.cpus on more platforms than Linux & HPUX + +Changes: + +- Parser no longer allows `,` after promiser or promisee. must be either `;` or lval +- Made parser output in GCC compatible format the only supported format + (remove --gcc-brief-format flag) + +- Silence license warnings in Enterprise Free25 installations +- action_policy => "warn" causes not_kept classes to be set on promise needing repair. +- Command line option version (-V) now prints a shorter parsable version without graphic +- Implicit execution of server and common bundles taking arguments is skipped in cf-serverd. +- WARNING: option --policy-server removed, require option to --bootstrap instead +- process promises don't log if processes are out of range unless you + run in verbose mode +- reports promises are now allowed in any context (Redmine #2005) +- cf-report has been removed +- cf-execd: --once implies --no-fork +- Version info removed from mail subject in the emails sent by cf-execd. + The subject will only contain "[fqname/ipaddress]" instead of "communnity/nova [fqname/ipaddress]" + Please change your email filters accordingly if necessary. +- "outputs" promise type is retired. Their semantics was not clear, and the functionality + is better suited for control body setting, not a promise. +- Tokyo Cabinet databases are now automatically checked for + correctness during opening. It should prevent a number of issues + with corrupted TC databases causing binaries to hang. +- Improved ACL handling on Windows, which led to some syntax changes. We now consistently + use the term "default" to describe ACLs that can be inherited by child objects. These + keywords have received new names: + - acl_directory_inherit -> acl_default + - specify_inherit_aces -> specify_default_aces + + The old keywords are deprecated, but still valid. In addition, a new keyword + "acl_inherit" controls inheritance behavior on Windows. This feature does not exist on + Unix platforms. (Redmine #1832) + +- Networking code is moved from libpromises to its own library, + libcfnet. Work has begun on making the API more sane and thread-safe. + Lots of legacy code was removed. +- Added getaddrinfo() replacement in libcompat (borrowed from PostgreSQL). +- Replace old deprecated and non thread-safe resolver calls with + getaddrinfo() and getnameinfo(). +- Hostname2IPString(), IPString2Hostname() are now thread-safe, and are + returning error when resolution fails. +- Running cf-execd --once now implies --no-fork, and also does not wait + for splaytime to pass. +- execresult(), returnszero() and commands promises no longer requires the first word + word to be an absolute path when using the shell. (Part of Redmine #2143) +- commands promises useshell attribute now accepts "noshell" and "useshell" values. Boolean + values are accepted but deprecated. (Part of Redmine #2143) +- returnszero() now correctly sets the class name in this scenario (Part of + Redmine #2143): + ``` + classes: + "commandfailed" not => returnszero("/bin/nosuchcommand", "noshell"); + ``` + +Bugfixes: + +- Bundles are allowed to be empty (Redmine #2411) +- Fixed `.` and `-` not being accepted by a commands module. (Redmine #2384) +- Corrected parsing of list variables by a command module. (Redmine #2239) +- Fixed issue with package management and warn. (Redmine #1831) +- Fixed JSON crash. (Redmine #2151) +- Improved error checking when using fgets(). (Redmine #2451) +- Fixed error message when deleting nonexistent files. (Redmine #2448) +- Honor warn-only when purging from local directory. (Redmine #2162) +- Made sure "restart" and "reload" are recognized keywords in packages. (Redmine #2468) +- Allocate memory dynamically to avoid out-of-buffer or out-of-hash + situations +- Fixed edit_xml update of existing attributes (Redmine #2034) +- Use failsafe policy from compile-time specified workdir (Redmine #1991) +- ifvarclass checked from classes promises in common bundles +- Do not wait for splaytime when executing only once +- Disabled xml editing functionality when libxml2 doesn't provide necessary APIs (Redmine #1937) +- Out-of-tree builds should work again, fixed a bunch of related bugs. +- Fixed race condition in file editing. (Redmine #2545) +- Fixed memory leak in cf-serverd and others (Redmine #1758) + +## 3.4.5 (Bugfix and stability release) + +Bugfixes: + +- Made qualified arrays expand correcty (Redmine #1998, Mantis #1128) +- Corrected possible errors in tcdb files when opening +- Avoid possible db corruption when mixing read/write and cursor operations +- Allowed umask value of 002 (Redmine #2496) + +## 3.4.4 (Bugfix and stability release) + +Bugfixes: + +- Prevent possible crash when archiving files (GitHub #316) +- Don't create symlinks to cf-know in update policy +- Don't enable xml support if libxml2 is too old (Redmine #1937) + +## 3.4.3 (Bugfix and stability release) + +Bugfixes: + +- Don't flood error messages when processes are out of defined range +- Prevent segmentation fault in cf-monitord -x (Redmine #2021) +- When copying files, use same file mode as source file, rather than 0600 (Redmine #1804) +- Included xpath in messages generated by edit_xml operations (Redmine #2057) + +## 3.4.2 (Bugfix and stability release) + +Bugfixes: + +- Fixes to policies in masterfiles (see masterfiles/Changelog for details) +- Fixes for OpenBSD (GitHub #278) +- Do not canonify values specified in abortbundleclasses/abortclasses (Redmine #1786) +- Fixed build issues on NetBSD, SLES 12.2 +- Improved error message when libxml2 support is not compiled (Redmine #1799) +- Fixed potential segmentation fault when trimming network socket data (GitHub #233) +- Fixed potential segmentation fault when address-lookups in lastseen db failed (GitHub #233) +- Execute background promise serially when max_children was reached, rather + than skipping them (GitHub #233) +- Fixed segmentation fault in cf-promises when invoked with --reports (Redmine #1931) +- Fixed compilation with Sun Studio 12 (Redmine #1901) +- Silence type-pun warning when building on HP-UX (GitHub #287) + +## 3.4.1 (Bugfix and stability release) + +New feature/behavior: + +- cf-execd terminates agent processes that are not responsive + for a configurable amount of time (see agent_expireafter in body + executor control), defaulting to 1 week + +Bugfixes: + +- Fixed regression of classmatch() failing with hard classes (Redmine #1834) +- Create promise-defined and persistent classes in correct + namespace (Redmine #1836) +- Several fixes to namespace support +- Fixed several crash bugs caused by buffer overflow and race + conditions in cf-serverd +- Regenerate time classes in cf-execd for each run (Redmine #1838) +- edit_xml: fix select_xpath implementation and update documentation + NOTE: code that uses select_xpath_region needs to be changed to + select_xpath +- edit_xml: make sure that text-modification functions don't overwrite + child nodes +- edit_xml: improve error logging + +## 3.4.0 + +New features: + +- Added rpmvercmp utility to compare versions of RPM packages for + accurate sorting of RPM packages for packages promises. +- Implemented network timeout on server side to avoid keeping stale + connections for hours. +- XML editing capabilities. See the documentation for edit_xml + body. Note the new dependency: libxml2. +- Implemented inheritance of local classes by bundles called using + "usebundle". By default classes are not inherited. See the + examples/unit_inherit.cf for an example. +- Moved from Nova/Enterprise: + - POSIX ACL support, + - "outputs" promise type, + - remote syslog support. +- packages_default_arch_command hook in packages promises, to + specify default architecture of the packages on the system. +- packages_version_less_command / packages_version_equal_command hooks + in packages promises, to specify external command for native package + manager versions comparison +- agent_expireafter in body executor control allows you to set a + timeout on all cf-agent runs, to enforce a threshold on the + number of concurrent agents +- Running in Solaris zone is now detected and classes "zone" and + `"zone_"` are created in this case. +- VirtualBox support added to guest_environment promises. +- guest_environment promises are supported under OS X. +- The "depends_on" attribute is now active, for the partal ordering + of promises. If a promise depends on another (referred by handle) + it will only be considered if the depends_on list is either kept + or repaired already. + + \*\* WARNING: When upgrading, make sure that any existing use + of depends_on does not make some promises being + unintentionally ignored. This can happen if you are + currently referring to non-existent or never-run handles + in depends_on attributes. + +- methods return values, initial implementation +- New format for cf-key -s, includes timestamp of last connection +- cf-promises --parse-tree option to parse policy file and dump it + in JSON format +- Namespaces support for bundles and bodies. See the + `examples/unit_namespace*.cf` for the usage. +- Default arguments for bundles. See the examples/unit_defaults.cf +- Metadata promise type. See the examples/unit_meta.cf + +New semantics: + +- Methods promises now return the status of promises + kept within them. If any promise was not kept, the method is not + kept, else if any promise is repaired, the method was repaired + else it was kept. +- Remote variable access in namespaces by $(namespace:bundle.variable) + +Changed functionality: + +- cf-execd -F switch no longer implies `run once`. New -O/--once + option is added to achieve this behaviour. This makes cf-execd + easier to run from systemd, launchd and other supervision + systems. + +Misc: + +- Support for the following outdated platforms and corresponding + classes has been removed. De facto those platforms were + unsupported for a long time, as CFEngine codebase uses C99 + language features unavailable on old platforms: + - SunOS 3.x (sun3) + - SunOS 4.x (sun4) + - Ultrix (ultrix) + - DEC OSF/1 AXP (osf) + - Digital UNIX (digital) + - Sony NEWS (newsos) + - 4.3BSD (bsd4_3) + - IRIX (irix, irix4, irix64) + - IBM Academic Operating System (aos) + - BSD/OS / BSDi / BSD/386 (bsdos) + - NeXTSTEP (nextstep) + - GNU Hurd (gnu) + - NEC UX/4800 (ux4800) + +- (Old news) Since 3.3.0 the layout of CFEngine Community packages + has changed slightly. + + `cf-*` binaries have been moved to /var/cfengine/bin, due to the + following reasons: + - `cf-*` binaries are linked to libraries installed to + /var/cfengine/lib, so placing binaries in /usr/local/sbin does not + increase reliability of the CFEngine, + - keeping whole CFEngine under single prefix (/var/cfengine) + makes packaging simpler, + - it matches the layout of CFEngine Enterprise packages. + + Please adjust your policies (the recommended ways to deal with + the move are either to adjust $PATH to include /var/cfengine or to + create symlinks in /usr/local/sbin in case you are relying on + binaries to be available in $PATH). + +- Workdir location is properly changed if --prefix or --enable-fhs + options are supplied to configure (Mantis #1195). +- Added check for broken libmysqlclient implementations (Mantis #1217). +- Standard library is updated from COPBL repository. +- cf-know is no longer built in Community releases. The only + functionality useful in Community, namely the reference manual + generation, is provided by new compile-time cf-gendoc tool. +- Filename (for storing filechanges) changed + from file_change.log -> file_changes.log (in /var/cfengine/state) + + New format for storing file changes introduced: + [timestamp,filename,,Message] + + N = New file found + C = Content Changed + S = Stats changed + R = File removed + +- Acceptance test suite passes on Mac OS X. +- Changed some port numbers to replace old services with imap(s) +- archlinux hard class on Arch Linux. +- Detect BSD Make and automatically switch to GNU Make during build. + +Bugfixes: + +- cfruncommand for cf-execd is an arbitrary shell command now (Mantis #1268). +- Fixed broken "daily" splayclasses (Mantis #1307). +- Allowed filenames up to 4096 bytes in network transfers (Redmine #1199). +- Fixed stale state preserved during cf-serverd reload (Redmine #1487). +- Free disk space calculation is fixed (Mantis #1120). +- Numerous portability bugfixes (especially OpenBSD, Solaris, AIX-related). +- Compatibility fixes for AIX, HP-UX, Solaris (Mantis #1185, Mantis #1177, Mantis #1109). +- Fixed broken socklen_t configure check under OpenBSD (Mantis #1168). +- Fixed hang in cf-promises under OpenBSD (Mantis #1113). +- Fixed endless loop in evaluating "$()" construct (Mantis #1023). +- Fixed check for old PCRE versions (Mantis #1262). +- Fixed insertion of multi-line blocks at the start of file (Mantis #809). +- Fixed numerous memory leaks. +- Fixes for metadata that were not resolvable +- Fixes for namespaces that would not support metadata and variable expansion +- Point-to-point network interfaces are detected and reported by CFEngine (Mantis #1246) +- Partial non-GNU userspace support in acceptance testsuite (Mantis #1255) + +Full list of issues fixed is available on +https://cfengine.com/bugtracker/changelog_page.php (old bug tracker) +and https://cfengine.com/dev/projects/core/versions/34 (new bug tracker) + +## 3.3.9 (Bugfix and stability release) + +Bugfixes: + +- Do not lose hard classes in cf-serverd during policy reload + (Mantis #1218). +- Implemented receive network timeout in cf-serverd. Prevents + overloading cf-serverd with stale connections. + +## 3.3.8 (Bugfix and stability release) + +Versions 3.3.6, 3.3.7 were internal and weren't released. + +Bugfixes: + +- Propery set sys.domain variable if hostname is fully-qualified. +- Fixed several small memory leaks. +- Made network timeout for network reads configurable. Previously + it was hardcoded to be 30 seconds, which was not enough for + cf-runagent invoking cf-agent on big policies (Mantis #1028). + +## 3.3.5 (Bugfix and stability release) + +Bugfixes: + +- Fixed cf-execd memory leak on hosts with cf-monitord running. +- Robustify against wrongly-sized entires in embedded databases. + +Standard library: + +- Bugfixes from upstream COPBL repository. +- standard_services bundle from upstream COPBL repository. + +## 3.3.4 (Bugfix and stability release) + +Evaluation of policies: + +- Fixed wrong classes set after installation of several packages + using packages promises (Mantis #829). +- Fixed segfault using edit_template on existing file (Mantis #1155). + +Misc: + +- Fixed memory leak during re-read of network interfaces' + information in cf-execd/cf-serverd. + +## 3.3.3 (Bugfix and stability release) + +Evaluation of policies: + +- Zero-length files are valid for readfile() and similar functions + (Mantis #1136). +- Unchoke agent in case it encounters symlinks in form ./foo + (Similar to Mantis #1117). + +Misc: + +- Fixed generation of reference manual on machines with umask more + relaxed than 022. +- Use statvfs(3) on OpenBSD to obtain filesystem information + (Mantis #1135). + +## 3.3.2 (Bugfix and stability release) + +Evaluation of policies: + +- Do not segfault if file copy was interrupted due to network + connectivity or server going away (Mantis #1089). +- Do not segfault if log_failed attribute is present in body, but + log_kept is not (Mantis #1107). +- Do not mangle relative paths in symlinks during file copy + Previously symlink a -> b was mangled to a -> ./b. + (Mantis #1117) +- Properly compare 1.0 and 1.0.1 in packages promises. Previously + only versions with equal amount of "segments" were comparable + (Mantis #890, #1066). + +Base policy: + +- Properly set permissions on files for /var/cfengine/lib on HP-UX + (Mantis #1114). +- Standard library (cfengine_stdlib.cf) is synced with COPBL + repository. + +Misc: + +- Do not create huge file in case corrupted TokyoCabinet database + is detected (Mantis #1106). +- Fixed file descriptor leak on error paths, may have caused crashes + of cf-execd and cf-serverd (Issue #1096). +- Fixed intermittent segfault in cf-execd (Mantis #1116). +- Impose an upper limit on amount of listening sockets reported by + cf-monitord. Huge amounts of listening sockets caused cf-agent to + segfault on next run (Mantis #1098). +- Added missing function prototypes caused errors during compilation + on HP-UX (Mantis #1109). +- Fixed compilation on Solaris 11 (Mantis #1091). + +## 3.3.1 (Bugfix and stability release) + +Evaluation of policies: + +- Do not cut off name of bundle in variables interpolation (Mantis #975). +- Do not segfault in function evaluation guarded by ifvaclass clause (Mantis #1084, #864). +- Do not segfault if "classes" promise does not declare any value to be evaluated (Mantis #1074). +- Do not segfault in database promises if there is no + database_operation provided (Mantis #1046). + +Built-in functions: + +- Fixed countclassesmatching() function which was misbehaving trying + to match classes starting with alphanumeric symbol (Mantis #1073). +- Fixed diskfree() to return kilobytes, as described in documentation (Mantis #980, #955). +- Fixed hostsseen() function to avoid treating all hosts as not + being seen since 1970 (Mantis #886). +- Do not output misleading error message if readtcp() is unable to connect (Mantis #1085). + +Command-line interface: + +- -d option previously reqired an argument, though help message disagreed (Mantis #1053). +- Disabled --parse-tree option, not ready for the release (Mantis #1063). +- Acept -h as a --help option. +- Ensure that cf-execd might be started right after being shut down. + +Misc: + +- Plug file descriptor leak after failed file copy (Mantis #990). +- Fixed unsafe admit rules in default promises.cf (Mantis #1040). +- Fixed splaytime to match documentation: it is specified in minutes, not seconds (Mantis #1099). + +Packaging: + +- Fixed owner/group of initscript and profile.d snippet in RPM builds (Mantis #1061, #1058). +- Fixed location of libvirt socket CFEngine uses to connect to libvirtd (Mantis #1072). +- Install CoreBase to /var/cfengine/masterfiles during installation (Mantis #1075). +- Do not leave old cf-twin around after upgrade (Mantis #1068) +- Do not leave rcS.d symlinks after purging .deb package (Mantis #1092). + +## 3.3.0 + +New promise types: + +- Guest environments promises, which allow to manipulate virtual + machines using libvirt. +- Database promises, which allow to maintain schema of MySQL and + PostgreSQL databases. Database promises are in "technical preview" + status: this promise type is subject to change in future. +- Services promises for Unix, allows abstraction of details + on managing any service + +New built-in functions: + +- dirname() to complement lastnode() +- lsdir() +- maplist() to apply functions over lists + +New features: + +- Allowed defining arrays from modules. +- Allowed both process_stop' and signals' constraints in + processes' promises at the same time. +- cf-promises --gcc-brief-format option to output warnings and + errors in gcc-compatible syntax which to ease use "go to next + error" feature of text editors. +- Iteration over lists is now allowed for qualified (non-local) lists. + +New built-in variables and classes (Linux): + +- Number of CPUs: $(sys.cpus), 1_cpu, 2_cpus etc + +New built-in variables and classes (Unices): + +- `$(sys.last_policy_update)` - timestamp when last policy change was seen by host +- `$(sys.hardware_addresses)` - list of MAC adresses +- `$(sys.ip_addresses)` - list of IP addresses +- `$(sys.interfaces)` - list of network interfaces +- `$(sys.hardware_mac[$iface])` - MAC address for network interface +- `mac_::` - discovered MAC addresses + +Changes: + +- Major cleanup of database handling code. Should radically decrease + amount of database issues experienced under heavy load. + + _WARNING_: Berkeley DB and SQLite backends are _removed_, use + Tokyo Cabinet or QDBM instead. Both Tokyo Cabinet and QDBM are + faster than Berkeley DB in typical CFEngine workloads. + + Tokyo Cabinet requires C99 environment, so it should be + available on every contemporary operating system. + + For the older systems QDBM, which relies only on C89, is a + better replacement, and deemed to be as portable, as Berkeley DB. + +- Change of lastseen database schema. Should radically decrease + I/O contention on lasteen database. +- Automatic reload of policies by cf-execd. +- Documentation is generated during build, PDF and HTML files are + retired from repository. +- Rarely used feature retired: peer connectivity intermittency calculation. +- Memory and CPU usage improvements. +- Testsuite now uses `make check` convention and does not need root + privileges anymore. +- cf_promises_validated now filled with timestamp, allows digest-copy + for policy instead of mtime copy which is safer when clocks are unsynchronised +- The bundled failsafe.cf policy now has trustkey=false to avoid IP spoofing + attacks in default policy +- See the full list of bugfixes at + https://cfengine.com/bugtracker/changelog_page.php + +## 3.2.4 (Bugfix and stability release) + +- Fixed failure in network transfer in case of misbehaving peer +- A few tiny memory leaks on error paths fixed + +## 3.2.3 (Bugfix and stability release) + +- A few tiny memory leaks fixed +- Improved performance of cf-serverd under heavy load with + TokyoCabinet database +- Full list of issues fixed is available on + https://cfengine.com/bugtracker/changelog_page.php + +## 3.2.2 (Bugfix and stability release) + +- Enabled compilation in "large files" mode under AIX +- Alleviated problem with broken file transfers over unstable + internet links. +- Full list of issues fixed is available on + https://cfengine.com/bugtracker/changelog_page.php + +## 3.2.1 (Bugfix and stability release) + +- Fixed compilation under HP-UX and Solaris +- Enabled compilation using HP ANSI C compiler +- Full list of issues fixed is available on +- https://cfengine.com/bugtracker/changelog_page.php + +## 3.2.0 + +New bootstrap method with single-command bootstrapping: + +- cf-agent --bootstrap --policy-server 123.456.789.123 +- Associated policy template files are added, partially maintained + by CFEngine +- Bug fixes for file-editing, package versioning, and embedded + database corruption (We recommend using TokyoCabinet instead of + BerkeleyDB if building from source). +- Improved upgrade path for Nova. +- Patches for improved run-agent concurrency +- Reorganization of documentation and community resources +- 100% on regression test suite on 3 operating systems + (Ubuntu, Debian, SuSE on x86-64 hardware) +- Support for multiple release environments +- package_policy update and addupdate now check if user-supplied + version is larger than currently installed - updates only if so +- Help text of cf-report -r corrected - a list of key hashes is + required, not ip addresses. +- New Emacs mode for CFEngine policy files (thanks to Ted Zlatanov!) +- Warnings are on edit_line changes can now give greater degree of information + without spamming promise logs +- Class expressions parser accepts `||` as an alias for `|` again. +- Invalidation of package list cache on installation/removal of + packages. +- New option cf-key -r to remove host key by IP or hostname. +- Added detection of network interfaces which belong to BSD jails. +- Improved robustness of multi-threaded code, in particular fix + problems with spurious access denials in server and losing of + authentication rules after policy reload. +- cf-promises accepts option -b matching cf-agent, which causes it + to do not complain about missing bundlesequence. +- New functions and(), not(), or() and concat() to ease use of + ifvarclass() clause. +- Full list of issues fixed is available on + https://cfengine.com/bugtracker/changelog_page.php + +## 3.1.5 + +- New class parser, `||` is no longer allowed in expressions (use `|`). +- Class setting in the promise types insert_lines, delete_lines, + replace_patterns, field_edits, vars, classes is restored. +- suspiciousnames implemented. +- New function getvalues(). +- New functions parse{read,int,string}array to match read{read,int,string}array. +- Testsuite added to check for core functionality. +- Syslog prefix is fixed to say `cf3` instead of `community`. + +## 3.1.4 (Bugfix and stability release) + +- Some urgent patches to 3.1.3. +- Class validation parse bug fixed. +- Global zone handling error for solaris fixed. +- Package architectures handled correctly (bug #456). +- Reading and writing of key name "root-.pub" eliminated (bug #442, #453). +- cf-serverd crash because of race condition on SERVER_KEYSEEN fixed. +- Lock purging to avoid remnant complexity explosion (bug #430). +- Some copyright notices added that got lost. + +## 3.1.3 (Stability release) + +- Major memory leaks in cf-monitord, cf-execd, cf-serverd fixed (bug #427). + The daemons now show no growth even with very complex policies. +- cf-serverd crash due to race condition in DeleteScope() fixed (bug #406). +- Added 30 second timeout on recv() on Linux. +- package_noverify_returncode implemented (bug #256). +- A flexible mechanism for setting classes based on return codes of + commands has been introduced. Allows for setting promise kept, + repaired or failed based on any return codes. This is currently + implemented for commands-promises, package-manager commands and + transformer in files. In classes body, see attributes + kept_returncodes, repaired_returncodes, failed_returncodes (bug + #248, #329). +- New function ip2host - reverse DNS lookup (bug #146). + +## 3.1.2 (Scalability/efficiency release) + +- Big efficiency improvements by caching output from + cf-promises. Can also be used for much more efficient policy + deployment (only pull if changed). +- Caching state of ps command for greater efficiency. Reloaded for each bundle. +- Index class lookup improves efficiency of class evaluation for huge configurations. +- Fixed issue where certain promiser strings got corrupted. +- Minor memory access issues fixed. +- Iterator bug introduced in 3.1.0 fixed + +## 3.1.1 (Bugfix release) + +- Memory leaks in server tracked down and fixed. +- List expansion bug (one list items not executed) fixed. +- Security issue introduced by change of runcommand shell policy fixed. If users defined a runcommand for cf-runagent/cf-serverd communication, possible to execute commands. +- cf-key -s command for showing key hash/IP address identity pairs + +## 3.1.0 + +- Change in storage of public keys. Cfengine now hashes the public key and uses this + as the keyname. Keys will be converted automatically. +- The old dynamic addresses lists are deprecated. + Caching of dns and key information for greater server speed. + Change in last-seen format reflects the public key usage. +- New package policy addupdate - installs package if not there and + updates it otherwise. +- Support for package_changes => "bulk" in file repository as well. +- New special function readstringarrayidx, similar to readstringarray, + but uses integer indices. Very useful if first row elements are + not good identifiers (e.g. contains spaces, non-unique, etc.). +- Change two log formats to use time() instead of date() + - filechanges + - total compliance +- Change from using md5 to sha256 as default digest for commercial version, + community retains md5 for compat. +- Commands not returning 0 in commands-promises are flagged + as repair_failed. +- Adjustable timeout on connect(). Defaults to 10 seconds, adjustable + with default_timeout in agent control. +- Redesign of the knowledge map infrastructure. +- Now possible to use variables to call methods, e.g + ``` + methods: + "name $(list)" usebundle => $(list)("abc"); + ``` + See reference manual notes +- Changes to normal ordering to optimize execution. +- Increased stability by always initializing Attribute and Promise + structures. +- When running cf-promises in dry-run mode (-n), the user does not need + to put binaries in WORKDIR/bin. For example, non-privileged users can verify root + policies. +- Source control revision added in version string if run in verbose mode + (e.g. "cf-promises -vV"). This needs some refining, uses revision of a header now. +- New semantics in return values of list functions. Null values are now allowed + and there is no iteration over empty lists. The value "cf_null" is reserved for + use as a null iterator. + +## 3.0.5p1 + +- Showing paths allowed/denied access to when cf-serverd is run in verbose mode. +- Bug in server fixed for dynamic addresses. +- File handle closure bugfix - too many open databases. +- Seg fault in mount files fix. +- Twin used in cf-execd without checking. +- Check_root set wrong directory permissions at source not destination. +- Error message degraded in body definition. +- Undefined body not warned as error. +- Various build enahncements. +- Package_list_update called only once per manager, and fixed crash. +- Version number bug in packages. + +## 3.0.5 + +- Encryption problems fixed - client key buffer was uninitialized. +- Classes-promisers are now automatically canonified when class + strings are defined, to simplifying the use of variables in classes. +- New scalars sys.cf_version and sys.nova_version that hold Cfengine version information. +- Attribute package_delete_convention added, to allow customizable + package name in delete command during update. +- package_list_update_ifelapsed limit added. +- Private variable $(firstrepo) is available in package_name_convention + and package_delete_convention in order to expand the full path to + a package, which is required by some managers. +- Some of the threading code is rewritten and made more robust. This includes + synchronizing access to the lastseen database from the server. +- Bad initialization of BSD flags fixed +- Multiple variable expansion issues in control fixed for server and agent +- Allowed ignore_missing_bundles to affect methods: bundles too +- Run agent trust dialogue fixed +- Bug in CPU monitoring, increasing time scale caused linear decay + of CPU measurement. +- Bug in Setuid log storage, fix. +- Hooks added for new Nova virtualization promises. +- Multithreading mutex failed to collide during cfservd leading to dropped authentication under heavy load. + +## 3.0.4 + +- Class cancellation in promises to create better class feedback, + allows emulation of switch/case semantics etc +- Value of SA measurement promises +- Special function getenv() which returns the contents of an + environment variable (on all platforms). +- New function translatepath for generic Windows +- New function escape() to escape literals as regular expressions (like SQL) +- New function host2ip for caching IP address lookup +- New function regextract for setting variables with backreferences +- New variables for the components $(sys.cf_agent), $(sys.cf_know) etc + pointing to the binaries. +- More robust integrated database implementation; closing all + handles when receiving signals, self-healing on corruption. +- Package installation on localhost without a manager like yum completed, + multiple repositories searched, and universal methods. +- Numerous bugfixes + +## 3.0.3 + +- sha256 .. new hashes in openssl included in syntax tree. +- End of line autocropping in readfile (hopefully intelligent) +- hashmatch function incorrectly implemented - old debugging code left behind. Fix. +- sys.crontab variable +- Unknown user is now interpretated as "same user", so that we give CFEngine a chance to + fix +- Unregistered addresses no longer report "(Non registered IP)", but return as the address + itself when doing reverse lookups. + +## 3.0.2 + +- IMPORTANT: Change in normal ordering of editing. replace comes + after insert lines Much testing and minor bug fixing +- Memory leaks fixed +- Many hooks added for Nova enterprise extensions. +- promise_output reports now placed in WORKDIR/reports directory +- Initialization correction and self-correx in monitord +- Many new body constraints added. +- Code readied for enterprise version Nova. +- -b option can override the bundlesequence (must not contain parameters yet) +- collapse_destination_dir option added to copy so that files can be + aggregated from subdirectories into a single destination. + +## 3.0.1 + +- First standalone release, independent of CFEngine 2 + Purge old definitions and check consistency. +- NB: changed search_mode to be a list of matching values +- Reporting rationalized in cf-promises with -r only to avoid + leaving output files everywhere. +- Hooks added for upcoming commercial additions to CFEngine. +- Added classify() and hostinnetgroup() functions +- Added additional change management options for change detection +- Package management added - generic mechanisms. +- Limits on backgrounding added to avoid resource contention during CFEngine runs. +- Image type added to cf-know. +- New classes for quartly shifts: Morning,Afternoon,Evening,Night +- Bug fixes in editfiles - line insertion for multiple line objects +- Change the name of the variables and context from the monitord for + better separation of data, and shorter names. sys -> mon + average -> av, stddev -> dev +- Canonical name for windows changed from "nt" to "windows", also version names + added "vista","xp" etc.. +- License notices updated for dual license editions. + +## 3.0.0 + +- First release of CFEngine 3. Known omissions: + - no support for ACLs + - no support for packages + - no support for interface configuration +- These will be added in the next release. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0b917efaf9..600ab1bbe5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,7 +51,7 @@ When submitting your pull request, please make sure you: * Tidy up the commit log by squashing commits and [writing good commit messages](#commits). -* Add one or more [ChangeLog Entries](#changelog) to the commit(s). +* Add one or more [changelog entries](#changelog) to the commit(s). * Become familiar with the *Northern.tech AS Contributor statement* as described in the [*AUTHORS*](./AUTHORS) file. @@ -193,7 +193,7 @@ cf-net: Fixed networking issues on windows ### Changelog -Most new features and fixes should have an entry in the `ChangeLog` file. +Most new features and fixes should have an entry in the `CHANGELOG.md` file. We have an automatic way of generating them before the release, by properly formatting *commit messages*. * To write arbitrary message in the ChangeLog: @@ -213,7 +213,7 @@ Changes which don't affect users, like changes in tests or in tools which are no All changelog entries should also include a reference to a ticket: `Ticket: CFE-1234` - + Note that the `Changelog` and `Ticket` entries must be in a *commit message* and not the description of a PR. Sometimes is necessary to redact a `Changelog` entry, for example a commit needs diff --git a/ChangeLog b/ChangeLog deleted file mode 100644 index d5e3fc1e20..0000000000 --- a/ChangeLog +++ /dev/null @@ -1,3381 +0,0 @@ -3.24.0: - - Added a sanity check to policy parser that checks for and warns - in case of promise declarations with no actions. The motivation - for this check is to aid policy writers in detecting semantic - errors early. (ENT-11137) - - Added sys.os_name_human for Alpine, postmarketOS, OpenBSD and NetBSD - - Added warning log message when OS is not recognized (CFE-4342) - - Adjusted locale settings in masterfiles stage common script to - handle more cases (ENT-11885) - - Adjusted package module inventory to include quotes around - fields when needed (CFE-4341) - - Added 'sys.os_name_human' and 'sys.os_version_major' variables - for Amazon. Additionally changed value of 'sys.flavor' from - 'AmazonLinux' to 'amazon_linux_2', so that it is similar to other - supported Linux distros. This change was necessary, due to the - fact that the 'sys.os_version_major' variable is derived from - it. However, the 'AmazonLinux' class previously derived from - 'sys.flavor' is still defined for backwards compatibility. - (ENT-10817) - - CFEngine now uses PCRE2 for regular expressions (ENT-10629) - - CFEngine processes no longer suffer from the "Invalid argument" - issues when working with LMDB (ENT-11543) - - Changed cf-apache systemd unit to reload configuration gracefully - (ENT-11526) - - Changed cf-execd's sleep behavior so it attempts to wake up at - the beginning of every minute (ENT-11765) - - File copying now uses more efficient implementation on Linux - platforms (CFE-4380) - - Fixed bug in double expansion of foreign list variables with namespaces - (ENT-11923) - - Fixed bug related to failing backwards directory traversial when - using forward slashes in path argument of the findfiles_up() - policy function on Windows. - - Fixed bug where 'default:sys.fqhost' contained many spaces when domain is - set in body common control (CFE-4053) - - Fixed cf-support call to cf-promises to collect all classes and vars - (CFE-4300) - - Fixed package promises with only promisers and no other attributes - (CFE-4315, CFE-4398, CFE-4408) - - Modified package promise default. If platform_default is present - use that package module. (CFE-4315) - - Ownership of symlinks is now handled properly (ENT-11235) - - SELinux no longer breaks exporting large reports as PDF (ENT-11154) - - The 'arglist' attribute in the 'commands' promises now preserves - whitespaces in the arguments. Whitespaces are currently not preserved on - Windows, or if the 'useshell' attribute is set to anything other than - '"noshell"'. (CFE-2724, CFE-4294) - - Trailing newline on insert_tree promisers no longer removes - ending tag for select_xpath (CFE-3806) - - cf-agent has two new options --no-augments and - --no-host-specific-data to skip loading augments - (def.json or def_preferred.json) and host-specific - data (host_specific.json), respectively (ENT-10792) - - cf-agent now has a new option --skip-bootstrap-service-start to - skip starting CFEngine services during the bootstrap process - (ENT-11932) - - cf-runalerts.service no longer exists, alerts are now - periodically run by cf-reactor (ENT-11538) - - depth_search acting on a non-directory promiser now handles such - file as if the promise didn't use depth_search. A warning is issued in this case. - (ENT-8996) - - masterfiles-stage.sh now supports a new --check-only option - (ENT-9386) - -3.23.0: - - Added selinux policy to allow cf-hub to initiate scheduled reports - (ENT-10696, ENT-9825) - - Added version_compare() policy function (CFE-3991) - - Bodies can now inherit attributes containing global variables - (CFE-4254) - - Cached policy function results now take into account number of arguments - and function name (CFE-4244) - - Fixed infinite loop on error bug while reading interface exception file - - Fixed inventoried policy release id when masterfiles-stage.sh deploys with cfbs - (ENT-10832) - - Improved locale override in masterfiles stage scripts (ENT-10753) - - Improved syntax description for validjson() (ENT-9759) - - Made cf-support use coredumpctl for core analysis only when configured in kerenl.core_pattern - (ENT-9985) - - Modified classesmatching() function to search parent bundles with inherit => true - (ENT-5850) - - Moved expected location of ignore_interfaces.rx from $(sys.inputdir) to - $(sys.workdir). If the file is found in $(sys.inputdir) but not in - $(sys.workdir), we will still process it for backwards compatability, - but issue a warning prompting the user to move it to the appropriate - location. (ENT-9402) - - Only CFEngine processes are now killed as expired lock owners - (CFE-3982) - - SELinux no longer blocks CFEngine deamons in reading security parameters from /proc/sys/kernel - (ENT-9684) - - cf-hub is now allowed to use the TLS kernel module on - SELinux-enabled systems (ENT-9727) - - cf_lock.lmdb is no longer restored from backup on - every boot (CFE-3982) - - packagesmatching() and packageupdatesmatching() now look for the software - inventory databases in the state directory and use them if found. This - change enables the usage of these functions in standalone policy files - without the demand for specifying the default package inventory attribute - in body common control. However, you still need the default package - inventory attribute specified in the policy framework for the software - inventory databases to exist in the first place and to be maintained. - (ENT-9083) - - CFEngine locks are now purged dynamically based on the local locks DB - usage/size ranging from no purging (<=25% usage) (ENT-8201, CFE-2136, ENT-5898) - - `cf-check repair` now rotates DB files with high usage (>95%) (CFE-3374) - - Full LMDB files are now handled gracefully by moving them aside and using new - empty LMDB files (ENT-8201) - - `cf-check repair` now supports the `--test-write` option to check if DBs can - be written to as part of identifying DBs that need repairing (CFE-3375) - - `cf-check diagnose` now shows DB usage and a hint if rotation is required - - /usr/bin/getent is now attempted to be used if /bin/getent doesn't exist (CFE-4256) - -3.22.0: - - Added --help option to cf-support and aligned output with other - components (ENT-9740) - - Added classes and vars to cf-support (CFE-4160) - - Added condition to runalerts service to require stamp directory - (ENT-9711) - - Added mctp_socket class to selinux policy (ENT-10206) - - Added native core dump handling in cf-support for Solaris (ENT-9786) - - Added needed SELinux class lockdown for latest RHEL 9 hosts (ENT-9685) - - Adjusted cf-support for exotic/legacy POSIX systems (ENT-9340) - - Adjusted cf-support for hpux mktemp command (ENT-9786) - - Directories are now created with correct perms (CFE-4114) - - Variables & classes modules automatically tagged (ENT-7725) - - Changed bootstrap policy to preserve log level for debug, verbose, - and info (CFE-4121) - - Created new policy function isreadable (ENT-9380) - - Enabled expireafter attribute for custom promise types (CFE-4083) - - Enabled install-time SELinux policy compiling (ENT-9685) - - Expired agents now terminate custom promise modules (CFE-4083) - - Fixed debug module expand logging for scalars (CFE-4122) - - Fixed syntax description of validjson() (ENT-9759) - - Prevented cf-support from searching more than 1 level for core files - (ENT-9981) - - Started checking status of all cf- prefixed systemd services in - cf-support (ENT-9804) - - validjson() no longer accepts trailing bogus data (CFE-4080) - -3.21.0: - - Added cf-support utility for generating support information - (ENT-9037) - - Adjusted cf-check and package module code for empty updates list - (ENT-9050) - - '$(this.promiser)' can now be used in 'files' promise - attributes 'if', 'ifvarclass' and 'unless' - (CFE-2262, ENT-7008) - - Fixed storage promise for nfs on MacOS (CFE-4093) - - Fixed definition of _low_ldt class from cf-monitord (CFE-4022) - - Insertion of contents of a file with blank lines into - another file with blank lines no longer results in - mixed content (ENT-8788) - - Added suggestion to use a negative lookahead when non-convergent edits - are attempted - (CFE-192) - - Unresolved function calls that return scalar values - are now considered OK for constraints expecting - strings during syntax check (CFE-4094) - - cf-monitord now honors monitorfacility in body monitor control - (ENT-4492) - - cf-serverd now periodically reloads its policy if it - contains unresolved variables (e.g. $(sys.policy_hub) - in 'allowconnect'). (ENT-8456) - - cf-serverd now starts in the network-online.target on - systemd-based systems (ENT-8456) - - edit_line bundles can now use the new - $(edit.empty_before_use) variable mirroring the value of - edit_defaults=>empty_before_use of the related files promise - (ENT-5866) - - Package modules with unresolved variables in their - names are now skipped in package queries (ENT-9377) - - Removed unsupported name_connect capability for udp_socket class - (ENT-8824) - - 'meta' attribute can now be used in custom promises (CFE-3440) - - Custom promise modules can now support the 'action_policy' - feature allowing promises of their custom types to be used - in dry-run and simulation modes and in combination with - 'action_policy => "warn"'. (CFE-3433) - - Use of custom promise modules that don't fully specify - protocol now results in warning (CFE-3433) - - Warnings are logged if levels of log messages from - custom promise modules don't match results of their - related promises (CFE-3433) - - Adjusted SELinux policy for RHEL 9 (ENT-8824) - - Fixed SELinux policy to allow hub to send emails (ENT-9557, ENT-9473) - - SELinux no longer breaks SQL queries with large result - sets on RHEL 8 hubs (ENT-9496) - - Added SELinux LDAP port access for Mission Portal (ENT-9694) - - Allowed ciphers are now properly split into TLS 1.3 - cipher suites and ciphers used for TLS 1.2 and older - (ENT-9018) - - Fixed git_cfbs_deploy_refspec in masterfiles_stage leaving temp dir - (ENT-9039) - - -3.20.0: - - 'rxdirs' now defaults to "false". This means that the read permission - bit no longer implies execute bit for directories, by default. - Permission bits will be exactly as specified. To restore the old behavior - you can still enable 'rxdirs' explicitly. (CFE-951) - - 'N' or 'Ns' signal specs can now be used to sleep - between signals sent by 'processes' promises - (CFE-2207, ENT-5899) - - Directories named .no-distrib are no longer copied from policy server - (in bootstrap/failsafe) (ENT-8079) - - Files promises using content attribute or template method now create - files by default unless `create => "false"` is specified. (CFE-3955, - CFE-3916) - - template_method mustache and inline_mustache now create file in promiser, - if template rendering was successfull and file does not exist. (ENT-4792) - - Added support for use of custom bodies in custom promise types - (CFE-3574) - - Custom promise modules now never get promise data with unresolved variables - (CFE-3434) - - Custom promises now use standard promise locking and support ifelapsed - (CFE-3434) - - Enable comment-attribute for custom promise types (CFE-3432) - - cf-secret encrypt now encrypts for localhost if no key or host is - specified (CFE-3874) - - CFEngine now builds with OpenSSL 3 (ENT-8355) - - CFEngine now requires OpenSSL 1.0.0 or newer (ENT-8355) - - Moved Skipping loading of duplicate policy file messages from VERBOSE to DEBUG - (CFE-3934) - - CFEngine processes now try to use getent if the builtin user/group - info lookup fails (CFE-3937) - - No longer possible to undefine reserved hard classes (ENT-7718) - - Unspecified 'rxdirs' now produces a warning (CFE-951) - - Fixed wrong use of log level in users promises log messages (CFE-3906) - - Fixed default for ignore_missing_bundles and ignore_missing_inputs - The issue here was that these attributes should default to false, - but when they are assigned with an unresolved variable, they - would default to true. (ENT-8430) - - Added protocol 3 (cookie) to syntax description (ENT-8560) - - Moved errors from data_sysctlvalues from inform to verbose (CFE-3818) - - Fixed inconsistencies with methods promises and missing bundles - Previously, methods promises acted differently depending on if - you specify the bundle with usebundle or in the promiser string. - This change removes the inconsistent checking which was only - happening on promises with usebundle. It also ensures that - the agent will abort if trying to use an undefined bundle, - regardless of whether it was using promiser string or usebundle. - This change, combined with the fix for ignore_missing_bundles - and ignore_missing_inputs, allow you to use inputs and bundles - conditionally (like we do for the enterprise federation policy) - and still have the agent abort in the correct situations - (when a bundle is actually missing and you haven't enabled - ignore_missing_bundles). The downside is that there are some - potential situations where undefined bundles would be detected - earlier previously (both correctly and incorrectly). (ENT-8430) - -3.19.0: - - -N/--negate now prevents persistent classes from being defined - (ENT-5886) - - 'null' JSON value is now handled as empty data in augments/host-specific data - (ENT-7434) - - Added a new common control attribute 'system_log_level' - For specifying the minimum log level required for log messages to - go to the system log. (ENT-7594) - - Added support for cfbs managed policy set to masterfiles staging script (ENT-7709) - - Trailing commas can now be used in policy argument lists (CFE-3734) - - Changed cf-key option --print-digest to take an optional argument. - cf-key now defaults to the public key file in workdir, if no argument - is specified or an empty string is given as the argument. (CFE-3682) - - Cached functions are now always called inside promises with 'iflapsed => "0"' - (CFE-3754) - - Enabled 'handle' attribute for custom promise types (CFE-3439) - - Enabled 'depends_on' attribute for custom promise types (CFE-3438) - - Enabled 'with' attribute for custom promise types (CFE-3441) - - Don't fail on new file creation when backups are enabled - (CFE-3640) - - Extended 'hostsseen()' policy function to return host keys (CFE-2546) - - Moved httpd.pid to root of httpd workdir (ENT-7966) - - Only real changes in files now produce info messages (CFE-3708) - - Reports with unexpanded variable references are now - attempted to be held off until the reference expands - (CFE-3776) - - Set apache umask to 0177 (ENT-7948) - - The --skip-bootstrap-policy-run option now skips the update policy - (ENT-7500, ENT-7511) - - Added measurement names in cf-check dump (ENT-7452) - - Value of '$(with)' is now expanded even if it contains unresolved variable references - (CFE-3776) - - cf-serverd now binds to both IPV6 and IPV4 if bindtointerface is unspecified - (ENT-7362) - - cf-serverd now reports if fails to bind to all possible addresses/interfaces - (ENT-7362) - - Fixed dbm_quick.c DBPrivRead() argument type (CFE-3737) - - Fixed dbm_tokyocab.c DBPrivRead() argument type (CFE-3737) - - Fixed crashes (Segfaults) in VariableIsSecret() (ENT-7678) - - Fixed crashes (Segfaults) in VariablesMatching() (ENT-7678) - -3.18.0: - - "No action for file" warning is no longer triggered when only - 'content => "something"' is used (CFE-3507) - - "source=promise_iteration" variables are no longer created in - foreign bundles (ENT-7029) - - 'cf-remote install' now supports the '--trust-keys' option for - pre-establishing trust before bootstrap (CFE-3485) - - 'cf-remote spawn' now supports adding new VMs to an existing group - (CFE-3502) - - 'rename => newname()' now supports relative paths (CFE-3537) - - 'variables' and 'classes' in CMDB and augments data now support - 'comment' fields (CFE-3638) - - Included custom promise type libraries in src tarball - (CFE-3575, CFE-3576) - - --ignore-preferred-augments now sets a hard class; ignore_preferred_augments - This class makes it easy for cf-agent / cf-execd policy to - propagate the option to other binaries (CFE-3656) - - Added 'classes' body support for custom promises (CFE-3437) - - Added a new --simulate=manifest-full mode - New simulation mode that manifests all changed files as well as - all other files evaluated by the agent run which were not skipped - (by file selection rules) (CFE-3506) - - Added a new runagent_socket_allow_users body executor control attribute - A new attribute that tells cf-execd to grant access to the - runagent.socket to the specified users (ENT-6735) - - Added checks to return value from getpwuid & getgrgid (CFE-3521) - - Added int() policy function (CFE-3616) - - Added new command line option: --ignore-preferred-augments - This option causes the agent to ignore def_preferred.json - always reading def.json (old behavior) (CFE-3656) - - Added policy function type() - - Added policy function findfiles_up (CFE-3577) - - Added policy variable sys.os_name_human (CFE-3569) - - Added policy variable sys.os_version_major (CFE-3569) - - Added shell library for custom promise types with cp example - (CFE-3516) - - Added string() policy function (CFE-3476) - - Augments data now supports meta information for classes - and a new 'variables' object for variables with meta information - (CFE-3633) - - Fixed case where malformed input could trigger buffer overflow - in policy function format (CFE-3525) - - Ability to report some number of lines from the END of a file by - specifying number_of_lines as a negative number using printfile - (CFE-3558) - - CFEngine binaries now load host specific data - ($(sys.workdir)/data/host_specific.json) before Augments relative - to policy entry (def.json) (ENT-6789) - - CFEngine processes are now properly identified in syslog on - non-GNU/Linux systems (ENT-7100) - - CMDB data now supports meta information for classes - and a new 'variables' object for variables with meta information - (CFE-3633) - - Changed custom promise type interpreter attribute to be optional - (CFE-3562) - - Changed files promise repaired log level to verbose (CFE-3631) - - Changed log message about whitespace in class expressions to be error - (CFE-3560) - - Changed sys var attribute names: - "OS type" was changed to "Kernel", "OS kernel" was changed to "Kernel Release" - (ENT-6551) - - Clarified error log message about untrusted state directory not being private - (CFE-3599) - - Classes from augments are now defined as soft classes - within the 'namespace' context instead of being hard - classes. Policies using classes from augments in policy files - using namespaces need to be updated to refer to the augments - classes with the 'default:' prefix (CFE-3632) - - Custom promise modules using JSON protocol now support data attributes - (CFE-3654) - - Custom promise modules using JSON protocol now support slist attributes - (CFE-3444) - - Custom promise types can now be declared in separate files (CFE-3510) - - Custom promise types can now report back result classes (CFE-3515) - - Custom promises now support the 'log_level' attribute (CFE-3436) - - Each custom promise module is now only spawned once - and handles all promises of its matching type(s) (CFE-3572) - - Early failing custom promises now properly set result classes - (CFE-3645) - - Exit code from remote agent run is now sent to cf-runagent (CFE-3594) - - Fixed crash when attempting to put methods promises in bundles - which are not agent bundles (CFE-3672) - - Fixed memory leak in package module code (ENT-5752) - - Fixed memory leak in simulate mode (CFE-3498) - - Fixed some more sign-compare warnings (CFE-3415) - - Improved error handling / logging of data received from promise module - - Improved log messages for commands promise outcomes and return codes - (CFE-3604) - - Made errors about failed validation of custom promises less noisy - - Namespace and bundle can now be specified in augments and CMDB data - (CFE-3633) - - New observations of root owned SETUID programs moved from WARN to NOTICE - (ENT-6519) - - Policy function format() no longer truncates strings lager than 4KiB - (CFE-2686) - - Policy function storejson() no longer truncates strings lager - than 4096 bytes (CFE-2507) - - Promise type is now sent to custom promise modules (CFE-3563) - - Reduced the noise caused by packages promises being skipped in - evaluation passes 2 and 3 (ENT-6553) - - Set Filedescriptor Limit to a more practial Size (CFE-3625) - - Stopped emitting warning and recording result when observing new - SETGID files (ENT-6750) - - Stopped updating files promise result with WARN (notkept) when - setuid files are encountered (ENT-6519) - - Unspecified 'files' constraints no longer cause '_kept' classes - to be defined (CFE-3578) - - Updated contrib/masterfiles-stage scripts and instructions to be - accurate (ENT-6165) - - Fixed using a custom promise module with two different - interpreters results in an error (CFE-3572) - Value of the - 'files_single_copy' body control attribute is now logged in - verbose logging mode (CFE-3622) - - Variables and classes defined in cmdb cannot be re-defined in - augments (ENT-7079) - - Verbose log now contains comments associated with 'vars' and - 'classes' promises (CFE-2442, CFE-2443) - - cf-agent now checks that promise module logs expected errors - - cf-agent now sends correct information to promise module in header - - cf-execd now executes cf-agent for "localhost" requests via the - runagent.socket (ENT-7090) - - cf-execd now handles requests to run cf-runagent on given hosts - (ENT-6182) - - cf-execd now runs cf-agent from a child process instead of a - thread on POSIX systems (ENT-6182) - - cf-runagent now exits with a code reflecting remote agent run - status(es) (CFE-3594) - - cf-serverd now supports systemd-based socket activation - - def_preferred.json is now used instead of def.json if it exists - Old clients will ignore it, allowing you to have 2 - versions of the augments file, 1 for compatibility - with old clients, and 1 for utilizing the new feautres. - (CFE-3656) - - files_single_copy body agent control attribute can now be an - empty list (CFE-3622) - - files_single_copy no longer treats paths of copied files as - regular expressions (CFE-3621) - - log_level is properly sent to promise modules in both validate - and evaluate requests (CFE-3564) - - unless can now be used with custom promise types (CFE-3431) - - CFEngine processes now reuse log facility from previous run for - early logging before policy is loaded (ENT-6955) - -3.17.0: - - cf-agent can now simulate the changes done to files in a chroot, printing - diff or manifest information about what it would do in a normal evaluation. - Use the new command line option: `--simulate=diff` or `--simulate=manifest`. - Please note that only files and packages promises are simulated currently. - - Custom promise types can now be added using promise modules (CFE-3273) - - cf-monitord now uses /proc/net/* files to get network information if - possible (CFE-2945) - - Added new policy function execresult_as_data() (CFE-3315) - - Added optional argument to execresult for choosing between stdout and - stderr (CFE-3108) - - Outcome classes are now always defined for promiser in files promises - (CFE-3369) - - and(), or(), not() now return boolean and cannot be used directly in - slist vars. They can now be used in other places where a boolean is - expected. (Most notably and / or promise attributes). The return values - can be converted to strings using concat(), if necessary (CFE-3470) - - Backgrounded commands are now correctly executed in the child process - (CFE-3379) - - CFEngine policy bodies can now be completely empty - - Directory listings in files changes monitoring are now only updated - when there is a change (CFE-3382) - - Promises with 'action => bg()' no longer break reporting data (ENT-6042) - - Spaces inside square brackets (slist/data index) are now allowed in - class expressions (CFE-3320) - - Variables specifying data/list names in @() references are now expanded - (CFE-2434) - - Added warnings when trying to use {{.}} to expand containers in mustache - templates (CFE-3457, CFE-3489) - - Limited unqualified host and domain name to 511 characters (CFE-3409) - - AVCs are no longer produced for CFEngine processes accessing /proc/net - (CFE-3240) - - Fixed how we check for `--cols` argument to `ps` (ENT-6098) - - Fixed a memory leak in users promises - - Fixed a small memory leak in cf-promises (CFE-3461) - - Fixed expansion of variables in data/list references (CFE-3299) - -3.16.0: - - Added 'cf-secret' binary for host-specific encryption (CFE-2613) - - 'cf-check diagnose --test-write' can now be used to test writing - into LMDB files (ENT-4484) - - 'if' constraint now works in combination with class contexts - (CFE-2615) - - Added $(sys.cf_version_release) variable (ENT-5348) - - Added new macros to parser: else, maximum_version, between_versions, - before_version, at_version and after_version. Version macros now - accept single digits (CFE-3198) - - Added cf-postgres requirement to cf-apache and cf-hub systemd units - (ENT-5125) - - Added files promise content attribute (CFE-3276) - - Added string_trim() policy function (CFE-3074) - - Added warning if CSV parser parses nothing from non-empty file - (CFE-3256) - - All changes made by 'files' promises are now reported. Also, - directory and file creations are now properly reported as 'info' - messages. And failures in edit_xml result in promises marked as - failed not interrupted. Purged dirs and files are reported as - repaired (ENT-5291, CFE-3260) - - Bootstrap to loopback interface is now allowed, with a warning - (CFE-3304) - - Client initiated reporting was fixed on RHEL 8.1 (ENT-5415) - - Fixed rare crashing bug when parsing zombie entries in ps output. The - problem was only ever observed on AIX, but could theoretically happen - on any platform depending on exact libc behavior. (ENT-5329) - - Fixed an issue causing duplicate entries in sys.interfaces, and - sys.hardware. (CFE-3046) - - Fixed ifelse() to return fallback in case of unresolved variables - (ENT-4653) - - Fixed locking of promises using log_repaired / log_string with - timestamps (CFE-3376) - - Fixed memory leak in handling of inline JSON in policy evaluation - - Fixed memory leak in readlist functions (CFE-3263) - - Fixed race condition when multiple agents are acquiring critical - section locks simultaneously (CFE-3361) - - Fixed selection of standard_services when used from non-default - namespace (ENT-5406) - - Fixed service status cfengine3 on systemd managed hosts (ENT-5528) - - Fixed some memory leaks and crashes in policy evaluation (CFE-3263) - - Improved error message for invalid body attribute names (CFE-3273) - - Improved management of secondary groups to avoid intermediary state - failures (ENT-3710) - - LMDB files are now created with correct permissions (ENT-5986) - - Log messages about broken Mustache templates are now errors (CFE-3263) - - Made classfiltercsv() fail properly on invalid class expression index - - Measurements promises with no match no longer produce errors - (ENT-5171) - - Moved error reading file in countlinesmatching() from verbose to error - (CFE-3234) - - Added new data validation policy functions validdata() and validjson() - (CFE-2898) - - New version checking convenience policy functions (CFE-3197) - Added the following policy functions to check against local CFEngine version: - - cf_version_maximum() - - cf_version_minimum() - - cf_version_after() - - cf_version_before() - - cf_version_at() - - cf_version_between() - - Removed (USE AT YOUR OWN RISK) from cf-key help menu for -x (ENT-5090) - - Rewrote helloworld.cf to use files promises content attribute - (CFE-3276) - - The outcome classes are now defined for the top-level directory when - 'include_basedir' is 'false' (ENT-5291) - - Variable references with nested parentheses no longer cause errors - (CFE-3242) - - cf-check: Added a more user friendly message when trying to print - unknown binary data (ENT-5234) - - cf-check: Added data validation for cf_lastseen.lmdb (CFE-2988) - - cf-check: Added nice printing for nova_agent_executions.lmdb - (ENT-5234) - - cf-check: Added validation for timestamps in cf_lock.lmdb (CFE-2988) - - cf-check: Added validation for timestamps in lastseen.lmdb (CFE-2988) - - cf-check: Fixed issue causing repair to target the wrong database file - (ENT-5309) - - cf-check: Symlinked LMDB databases are now preserved in repair - Performs diagnosis and repair on symlink target instead of symlink. - Repaired files / copies are placed alongside symlink target. - In some cases, the symlink target is deleted to repair a corrupt - database, and the symlink is left as a broken symlink. This is - handled gracefully by the agent, it will be recreated. Broken - symlinks are now detected as an acceptable condition in diagnose, - it won't try to repair them or delete them. (ENT-5162) - - storage promises managing nfs mounts should now correctly mount - after editing fstab entries - -3.15.0: - - New policy function basename() added (CFE-3196) - - Added read_module_protocol() policy function - This function reads module protocol from a file, and can be used - for caching the results of commands modules. (CFE-2973) - - The @ character is now allowed in the key of classic arrays defined - by the module protocol (CFE-3099) - - nth() policy function now supports negative indices (CFE-3194) - - Fixed .xy floating point numbers parsing in eval() (CFE-2762) - - Added inform constraint to commands promises, to allow suppression of - INFO log messages (CFE-2973) - - Changed unless constraint to be more consistent with if - For any situation where if would NOT skip a promise, unless - will cause the promise to be skipped. When there are - unresolved variables / function calls, if will skip, unless - will NOT skip. (CFE-3160) - - Default minimum allowed TLS version is now 1.1 (ENT-4616) - - Network protocol version 2 is now called "tls" - "tls" or "2" can be used in places where you specify network - protocol. Log messages were altered, to show "tls" instead of - "latest". (ENT-4406) - - Introduced protocol version 3 - "cookie" - This protocol is identical to version 2 ("tls"), - except it allows the enterprise reporting hub to send - the COOKIE command to enterprise hosts. This command is used for - detecting hosts using duplicate identities. Protocol version "latest" - now points to version 3. For community installations, it should not - make a difference, policy servers will not send this command. The only - visible difference is the new version number (in logs and policy). - (ENT-4406) - - Package modules now hit network when package cache is first initialized - (CFE-3094) - - Fixed promise skipping bug in unless (CFE-2689) - - Fixed error message for unexpanded variables in function calls in unless - (CFE-2689) - - Prevented buffer overflow when policy variable names are longer than - 1024 bytes - - Zero bytes in class guards no longer cause crashes (CFE-3028) - - Fixed bug in ps parsing on OpenBSD / NetBSD causing bootstrap to fail - - Fixed crash in policy/JSON parsing of numbers with too many decimal - points (CFE-3138) - - copy_from without preserve now respects destination mode (ENT-4016) - - Removed stime_range and ttime_range constraints from promise hash - (ENT-4921) - - Fixed promise result when using process_stop in processes type promises - (ENT-4988) - - cf-execd now sends SIGKILL to the agent process in case of - agent_expireafter, after attempting SIGINT and SIGTERM (CFE-2664) - - cf-serverd now tries to accept connection multiple times (CFE-3066) - - Fixed multiple measurements tracking growth of same file (ENT-4814) - - Set create permissions of monitord files in state directory to 0600 - 0600 matches the permissions enforced by policy. - Affected files: - * state/cf_incoming.* - * state/cf_outgoing.* - * state/cf_users - * state/env_data - (ENT-4863) - - Clarified descriptions of io_writtendata and io_readdata (ENT-5127) - - Clarified log message about process_count and restart_class being used - concurrently (CFE-208) - - Agent runs that hit abortclasses now record results (ENT-2471) - - An ID of rhel in os-release file will now define both rhel and redhat - classes (CFE-3140) - - Version specific distro classes are now collected by default in - Enterprise (ENT-4752) - - redhat_8 and redhat_8_0 are now defined on RHEL 8 (CFE-3140) - - Added derived-from-file tag to hard classes based on /etc/redhat-release - (CFE-3140) - - Added sys.bootstrap_id policy variable containing the ID from - /var/cfengine/bootstrap_id.dat, if present (CFE-2977) - - sys.interfaces now contains interfaces even when they only have - IPv6 addresses (ENT-4858) - - IPv6-only interfaces added to sys.hardware_(addresses,mac) (CFE-3164) - - IPv6 addresses are now added to policy variable sys.ip_addresses - (CFE-682) - - IPv6 addresses now respect ignored_interfaces.rx (CFE-3156) - - Hostname now allowed in bindtoaddress (CFE-3190) - - Fixed issue when removing comments from files in various policy functions - This also fixes many erroneous occurences of the error message - mentioning: - - [...] because it legally matches nothing - - (A warning can still appear if a comment regex actually matches nothing). - Also made this comment removing logic faster. - Affected functions include: - * readstringlist() - * readintlist() - * readreallist() - * peers() - * peerleader() - * peerleaders() - * data_readstringarray() - * data_readstringarrayidx() - * data_expand() - * readstringarray() - * readstringarrayidx() - * readintarray() - * readrealarray() - * parsestringarray() - * parsestringarrayidx() - * parseintarray() - * parserealarray() - (CFE-3188, ENT-5019) - - Fixed memory leak in JSON / env file parsing (CFE-3210) - - Fixed memory leak in handling of nfs / fstab (CFE-3210) - - Fixed memory leak in string_replace() and regex_replace() (CFE-3210) - - Fixed memory leak when using with constraint (CFE-3210) - - Fixed minor memory leak in policy evaluation (CFE-3210) - - Fixed small memory leak in SQL database promises (CFE-3210) - - Received SIGBUS now triggers a repair of local DBs (CFE-3127) - - Corrupted LMDB files are now automatically repaired (CFE-3127) - - Keys in the lock database, cf_lock.lmdb, are now human-readable - (CFE-2596) - - Local databases now use synchronous access on AIX and Solaris (ENT-4002) - - Report corrupted local database with a critical log message (CFE-2469) - - Local DB errors are now logged with the particular DB file path (CFE-2469) - - cf-check: repair now preserves readable data in corrupted LMDB files - (CFE-3127) - - cf-check: --dump option was added to the backup command - - cf-check: Added --no-fork to diagnose command (CFE-3145) - - cf-check: Added -M manpage option and other common options (CFE-3082) - - cf-check: No DB files in state dir now causes errors - - cf-check: dump command now dumps DB contents to JSON5 (CFE-3126) - - cf-check: help command can now take a topic as argument - -3.14.0: - - A bootstrap_id.dat file is now generated on every bootstrap - (CFE-2977) - - Added options to cf-net to set minimum TLS version and ciphers - (ENT-4617) - - Added --no-truncate option to cf-key - This option, when used with --show-hosts changes the formatting - of the output. Instead of padding and truncating each of the - fields, they are printed, in full, with no padding, and separated - by a single tab character. The output is not as pretty, but should - be more useful for parsing by other scripts / tooling. (CFE-3036) - - Added a new option --skip-db-check to agent and execd - This option allows you to enable/disable database (LMDB) consistency - checks. Initially it is disabled by default, but this will likely - change. (CFE-2893) - - Added a new utility to contrib: cf-remote - cf-remote is a python + fabric tool to log in to remote hosts - you have ssh access to. It can be used to download, transfer, - and install CFEngine packages as well as bootstrapping etc. - At this point, cf-remote is not packaged with CFEngine, but can be - installed separately from: - https://github.com/cfengine/cf-remote - (CFE-2889) - - Added derived-from-file tags to hard classes based on /etc/debian_version and /etc/issue - - Added a function to filter CSV-files by classes (CFE-2768) - - Forward slash is now an allowed character in module protocol commands - (CFE-2478) - - Augments files can now handle class expressions by appending '::' - A condition in an augments file is treated as a class expression - if it ends in ::. Otherwise it is treated as a regular - expression. (CFE-2954) - - Internal ps command can now handle longer usernames (CFE-2951) - - Made copylink_pattern honor '/../' in copy source (CFE-2960) - - CSV parser now supports CRLF inside double quotes (ENT-4504) - - Added an error when a function defining a variables still fails at - pass 3 (CFE-2983) - - Documented cf-execd and cf-serverd response to SIGHUP in manpage - (CFE-2853) - - Stopped trimming leading zeroes in ubuntu minor version class - The old version detection logic (using /etc/debian_version) was - converting the minor version part to an integer, defining - ubuntu_18_4 instead of ubuntu_18_04. The new platform detection - (based on /etc/os-release) defines ubuntu_18_04. Since both old - and new methods are running to maximize compatibility, both - ubuntu_18_04 and ubuntu_18_4 were defined. - This commit ensures that the old detection logic treats the - minor version (the 04 part) as a string, not an integer. The - change is specific to Ubuntu, and should affect Ubuntu 18.04, - 16.04, 14.04, etc. (CFE-2882) - - SUID log permissions are now properly enforced (CFE-2919) - - Agent log file names are now always lowercase - - Extended module with file protocol for data (CFE-3050) - - Fixed a segfault in 'cf-promises -p json-full' (CFE-3019) - - Added cf-key help output to indicate ability to delete by key digest - (CFE-2997) - - Fixed disabling TLS 1.0 (CFE-3068) - - Fixed growing memory footprint of daemons (CFE-3032) - - Fixed the log message about setting collect_window (ENT-4238) - - Fixed the log message when parsing TIME in 'ps' output fails - - Fixed parsing of YAML values starting with numbers (CFE-2033) - - Fixed sys.flavor on AIX (ENT-3970) - - Fixed 6 cases where promises could get the wrong outcome - All cases were related to error handling and detected using - static code analysis (LGTM). They were limited to cf-monitord - and cf-agent (guest_environments and files promise types). Due - to a programming mistake, promise results would sometimes be - overwritten with 'skipped' outcome. Keeping the previous - value or making the promises 'not kept' is expected behavior. - Added a query to our CI (LGTM) to make sure we catch this error - on new contributions. - - Fixed an issue while parsing ps output on AIX (ENT-4295) - - Fixed a memory leak in filesexist function (ENT-4313) - - Fixed a memory leak in mustache rendering (ENT-4313) - - Fixed a memory leak in: differences(), intersection(), unique() - (ENT-4586) - - Fixed a segfault in policy parser (ENT-4022) - - Connection cache is now global (CFE-2678) - - Increased verbosity of AcquireLock permission error (ENT-4395) - - Message about invalid class characters from module protocol moved to VERBOSE - (CFE-2887, CFE-3008) - - Prevented buffer overflows in cf-monitord data parsing - - Private keys generated by cf-key are no longer encrypted - Private key files encrypted with a broken cipher and default - hard coded passphrase provide no real security, and is only an - inconvenience. Maybe it was intended to add a password prompt - later, but it's been 10 years now, and the cipher and passphrase - remain untouched. The function which reads keys still supports - both encrypted and unencrypted keys, it will decrypt if necessary. - - Reduce SSL/TLS shutdowns on bad networks (CFE-3023) - - Removed programming error in handling of process_count body - Previously, having a failing function call inside in_range_define - or out_of_range_define would cause a programming error when - trying to define that as a class. Fixed it by detecting the - case, printing a normal error, and skipping defining the class. (CFE-2067) - - Set policy->release_id to "failsafe"/"bootstrap" when running failsafe.cf - (CFE-3031) - - Switched permissions of various temporary files in state to 0600 - These files were created with 0644 permissions, and then - repaired in policy. However, since they are deleted / recreated - periodically, it causes INFO noise. Safer and better user - experience to create them with restricted permissions to - begin with. - Affected files: - * $(sys.statedir)/cf_procs - * $(sys.statedir)/cf_rootprocs - * $(sys.statedir)/cf_otherprocs - (ENT-4601) - - string_split segments are now truncated to 1024 bytes instead of - crashing (CFE-3047) - - Unresolved function calls in process_select body are now skipped - Function calls which always fail, like getuid("nosuchuser"), are - never resolved. Previously this would cause a programming error, - since the body is expected to have a list of strings, not - unresolved function calls. - The function calls are silently skipped (with a verbose message) - as this matches the behavior of calling the functions in a vars - promise, and using that as a body parameter. - (CFE-1968) - - cf-check directories can now be controlled from ENV vars (CFE-2994) - - cf-check: Added backup command - This command copies lmdb files to a timestamped backup directory. - (ENT-4064) - - cf-check: diagnose and backup now use state directory by default - (ENT-4064) - -3.13.0: - - Add support for TLS 1.3 and its ciphersuites - - Add 'feature' hard classes for supported TLS versions - Different versions of TLS are supported depending on what version - of OpenSSL CFEngine was compiled and linked with. Newly added - feature hard classes bring that information to the - policy. Classes like these are now defined (for supported - versions of TLS): - feature_tls source=agent,hardclass - feature_tls_1 source=agent,hardclass - feature_tls_1_0 source=agent,hardclass - feature_tls_1_1 source=agent,hardclass - feature_tls_1_2 source=agent,hardclass - feature_tls_1_3 source=agent,hardclass - - Add a new variable $(sys.default_policy_path) - A new sys variable that provides the path of the default policy - file evaluated when no file is specified with the '-f' option. - - Add an option to skip the initial policy run on bootstrap - In some cases it may not be desired to run the policy as the last - step of the bootstrap. This can be done with the new - '--skip-bootstrap-policy-run' option for cf-agent. (CFE-2826) - - Trigger promises.cf as the last step of bootstrap (CFE-2826) - - Add support for overriding the package module's path (CFE-2103) - - Add support for setting package module interpreter (CFE-2880) - - Added --log-level option to all components - This allows you to specify any log level (info, verbose, debug etc.). - It is also less strict, allowing different spelling. As an example, - --log-level i, --log-level INFO, --log-level inform are all the same. - - Added a new binary: cf-check - Corrupt local databases (LMDB) continues to be a problem. - cf-check will be used to diagnose and remediate problems - with corrupt databases. It is a standalone binary, which - doesn't evaluate policy or use the local databases, thus - it can be used in situations where the other binaries - like cf-agent would hang. - cf-check replaces our lmdb database dumper, lmdump. - cf-check lmdump or symlinking / renaming it to lmdump - will make cf-check have the exact same behavior as lmdump. - cf-check will include much more functionality in the future - and some of the code will be added to other binaries, - for example to do health checks of databases on startup. - Ticket: (ENT-4064) - - Added function string_replace. (CFE-2850) - - Allow dots in variable identifiers with no such bundle - As described and discussed in CFE-1915, defining remote variables - (injecting variables into remote bundles) is dangerous and must - be blocked. However, using a dot-separated common prefix for - variables raises no security concerns and can be considered - valid. (CFE-1915) - - Allow requiring TLS 1.3 as the minimum version - - Apply augments after vars, classes and inputs in def.json - (CFE-2741, CFE-2844) - - Bundle name is now part of the log message when aborting a bundle - (CFE-2793) - - Class names set by module protocol are automatically canonified - (CFE-2877, CFE-2887) - - Classes failsafe_fallback and bootstrap_mode are now reported by default - - Correct log level for data_readstringarray* (CFE-2922) - - Do not iterate over JSON objects' properties in mustache (CFE-2125) - - Do not render templates when passed invalid data (CFE-2194) - - Eliminated error messages caused by attempting to kill expired processes - (CFE-2824) - - Fix cf-runalerts systemd unit conditions so the service will run - (ENT-3929) - - Fix the off-by-one error in cf-runagent background process spawning - (CFE-2873) - - Fixed OOB read / heap buffer overflow in evaluator (ENT-4136) - - Fixed a memory leak which occured when reloading RSA keys from disk - (CFE-2857) - - Fixed a memory leak which occured while loading augments files - (CFE-2913) - - Fixed an issue with splay time in cf-execd (CFE-2931) - - Fixed error handling and memory leak in cf-key (CFE-2918) - - Fixed memory leak in JSON to policy conversion (ENT-4136) - - Fixed memory leak in lmdb cleanup (CFE-2918) - - Fixed memory leaks in cf-agent during bootstrap (CFE-2918) - - Fixed memory leaks in variablesmatching() and findfiles() (CFE-2918) - - Fixed missing class with mustache templates in warn_only mode - (CFE-2600) - - Fixed small memory leak in cf-serverd (CFE-2918) - - Fixed small memory leak in cf-upgrade (ENT-4136) - - Fixed small memory leaks of environment variable strings (CFE-2918) - - LMDB database dumper, lmdump, no longer creates empty databases - (ENT-4064) - - Made variablesmatching functions treat args regexes more correctly - variablesmatching() and variablesmatching_as_data() no longer - use string comparison to find matches. The documentation is clear; - arguments should be regexes (so you have to escape special - characters). - bundle agent main - { - vars: - "myvar" - string => "example", - meta => {"os[linux]"}; - "matches" - slist => variablesmatching(".*", "os\[linux\]"); - reports: - "Match: $(matches)"; - } - The above example is correct. If you don't escape the brackets - like above, it will no longer work. (You probably shouldn't use - brackets in tags anyway). - - Prevent the init script from managing processes inside containers - (ENT-3800) - - Read mustache-rendered files in text mode when comparing digest - (ENT-2526) - - Reload persistent classes on config reload in cf-execd and cf-serverd - (CFE-2857) - - Fixed issue with @if macro failing when it is on the first line. - (CFE-2817) - - Fixed issue with cf-agent intermittently hanging on windows - sometimes (ENT-3756) - - Change GIT_BRANCH to GIT_REFSPEC and remove Design Center vars - (ENT-4023) - - os-release file is now used for hard classes and sys.flavor on all linuxes - This will improve platform detection on newer operating systems where - /etc/os-release (or /usr/lib/os-release) is present. - A hard class will be set for the value of the ID key (canonified with - underscores), if it exists. If both ID and VERSION_ID exist, multiple - hard classes will be set for all parts of the version number. The - special variable sys.flavor will also be set by determining major - version from VERSION_ID. - Example os-release file: - ID=coreos - VERSION_ID=1185.3.0 - For the example above, sys.flavor will be coreos_1185 and 4 hard - classes will be set; coreos_1185_3_0, coreos_1185_3, coreos_1185, - and coreos. - For backwards compatibility, older distribution specific logic is still - executed and may overwrite sys.flavor and define hard classes as before. - - Refactor use of atexit to use custom cleanup function instead. On Windows - atexit() unloads DLLs before and/or during atexit functions being called - which causes bad behavior. (ENT-3756) - -3.12.0b1: - New Features: - - Add a --key-type option to specify RSA key size to cf-key - - New hash_to_int policy function (CFE-2733) - - Issue a warning on ignored locking attributes (CFE-2748) - - Add IPv6 hard classes with the "ipv6_" prefix (CFE-2310) - - Introduce "missing_ok" attribute in body copy_from - This allows to ignore missing sources in file copy operations (CFE-2365) - - Enable Xen hypervisor detection on all x86 platforms (CFE-2203) - - Add sys.policy_entry variables (CFE-2572) - - Added inline_mustache template method (CFE-1846) - - New component cf-net (cf-net is a CLI for the CFEngine network protocol, - useful for debugging, testing etc) and accompanying policy variable - sys.cf_net containing path to cf-net binary - - Changes: - - Load augments at the end of context discovery - This means that classes defined as part of the context discovery - (e.g. 'am_policy_hub' and 'policy_server') can be used in the - augments (CFE-2482) - - Open measurements promise type from enterprise cf-monitord - - Transform filesexist() into a collecting function (CFE-2744) - - Load process table when actually needed for a processes promise (ENT-2536) - - Ignore commented out entries in fstab when edit_fstab is true (CFE-2198) - - Do not move obstructions in warn policy mode (CFE-2740) - - Made the max bytes parameter to file reading functions optional (CFE-2656) - - Do not tag large volatile variables for inventory - sys.interfaces_data, sys.inet and sys.inet6 are commonly larger than the - maximum data size allowed to be collected by cf-hub. Data larger than 1k - is truncated. Instead of reporting truncated data this change stops - tagging the variable so that it will not be collected to the Enterprise - hub and will not be available in Mission Portal. (ENT-3483) - - cf-execd now re-parses augments on policy reload (CFE-2406) - - Improve misleading verbose message - For constraints if/ifvarclass/unless, we now print the whole rval of the constraint. - Previously the message was just "skipping variable because ifvarclass is not defined" while the variable itself was defined. - Old message example: - verbose: Skipping promise 'mailto' because 'if'/'ifvarclass' is not defined - Changed to: - verbose: Skipping promise 'mailto' because 'ifvarclass => not(isvariable("mailto"))' is not defined - (CFE-2697) - - Promise comments for file changes moved to verbose (ENT-3414) - - Suppress output from systemctl based restart of services in - bootstrap/failsafe (CFE-1459) - - Parser can now handle larger inbut buffers (CFE-1886) - - Improve logging of ACL errors (ENT-3455) - - cf-execd systemd service now only kills cf-execd itself (ENT-3395) - - Load multiple augments from "augments" string array in def.json - (CFE-2084) - - Improve support for Alpine Linux - - Set the exit value when running cf-key - When running cf-key to generate new keys, set the exit value of the - program to be 0 on success and 1 on failure. This makes it easier to - catch errors during setup of a new machine. - Change the default behavior of the program to not write anything to stdout, - opting to use the Log() function which can write to stdout and will also - allow output to be sent to syslog. - Add a --inform option to set the global log level to LOG_LEVEL_INFO. - Change the permissions of the randseed file to 600 and catch the exception - if the chmod call fails. - - Properly reverse-resolve DNS names longer than 63 chars (ENT-3379) - - Properly redirect init script to systemd on debian systems (ENT-3326) - - Bug fixes: - - Disallow modifications of variables from a remote bundle (CFE-1915) - - Speedup evalution by not copying variables table when expanding a promise - (CFE-2524) - - Resolve subkey conflicts when converting to JSON - Whenever there is a conflict of array variable definitions prefer - the container subkeys over simple values when converting to JSON - (CFE-2536) - - Do not ignore meta promises in server bundles (CFE-2066) - - Add a debug log for computed class in splayclass - - Don't error when calling isexecutable on broken link (CFE-741) - - Fix segfault when no show-evaluated-vars/classes is specified - - Fix memory leak in cf-execd, triggered when sending email failed (CFE-2712) - - Fix IPv6 parsing to be un-reversed (CFE-2580) - - Fix bug preventing permission changes on Unix sockets (CFE-1782) - - Fix storage mount promise when existing mountpoint has a similar path - (CFE-1960) - - Fix segfault when cf-promises -p is called against a file with syntax - errors (CFE-2696) - - Fix rare cf-execd hang (CFE-2719) - - Fix mergedata segfault when called on a non-container (CFE-2704) - - Do not segfault if policy_server.dat only contains whitespaces and/or line breaks - - Fix segfault on JSON policy files with no bundles and bodies (CFE-2754) - - -3.11.0: - New Features: - - Allow function calls in promiser using universal "with" attribute - (CFE-1092) - - Add example of with attribute (CFE-1092) - - Detect Amazon Linux and set "AmazonLinux" hard class and - sys.flavour variable - - New sysctlvalue() and data_sysctlvalues() functions from /proc/sys - (CFE-2513) - - readdata() also auto-detects .yml files as YAML - - Added support for ENV and CSV file parsing (CFE-1881) - - Added vars and classes for CoreOS (ENT-3043) - - cf-agent: implement --show-evaluated-vars and --show-evaluated-classes - - Support for custom ports and host names as policy hub (CFE-953) - - cf-promises: allows --show-vars and --show-classes to take an optional filter - - Added a new tool: cf-net. cf-net is a CLI for the CFEngine - network protocol, useful for debugging, testing etc (CFE-2493) - - New policy variable: sys.cf_net contains path to cf-net binary - - Read /etc/os-release into sys.os_release (CFE-1881) - - Changes: - - readintlist() now prints an error if the - file contains real numbers, not integers, and aborts; previously it was - printing an info-level error message, was half-reading an integer out of - the real, and was continuing successfully. - - "make tar-package" should create a tarball with the contents of - "make install" (ENT-3041) - - Allow opening symlinks owned by root or by the current user - (CFE-2516) - - Change warning message about depth_search on a non directory to - DEBUG level - - Ensure synchronous start and stop with systmectl (ENT-2841) - - Put logs in /var/log and PID files in /var/run when using FHS layout - (CFE-2449) - - readstringlist(), readintlist(), readreallist(): Print - verbose instead of error message if file can not be read - - cf-serverd: Do not close connection when file does not exist - (CFE-2532) - - policy_server.dat now appends a newline and supports host & port - - Allow string_head and string_tail to take negative arguments - - getvalues(inexistent_var) returns an empty list. - Restores 3.7.x and earlier behaviour. (CFE-2479) - - Partially restore old getvalues(array) behaviour - Bugfix: getvalues() now behaves correctly for old CFEngine - arrays of depth 1 - Behaviour change: it always returns a list now. Even when v is a simple - string (i.e. not an iterable) it will return an slist with one element: - the value of the string variable. - Known issues: getvalues() still misbehaves with double-indexed arrays - (see CFE-2504, CFE-2536) - - The source version of CFEngine now installs binaries into - bin folder instead of sbin folder (CFE-2448) - - Don't error during dry run for proposed execution (CFE-2561) - - Print verbose instead of error message when readfile() fails (CFE-2512) - - cf-serverd: Auto configure max open files ulimit according to - maxconnections (CFE-2575) - - Made the max bytes parameter to file reading functions optional. - Affects readfile(), readenvfile(), readcsv() - - Bug fixes: - - Fix insert_lines related memory corruption (CFE-2520) - - Prevent LMDB assertion on AIX by ensuring nested DB calls are - not occuring during signal handler cleanup (CFE-1996) - - Fix a bug which could cause cf-execd to believe there was - an error when sending the email report, when there really wasn't - - zendesk#3204: Fix "lastseenexpireafter" 32-bit signed int overflow - - Fix cf-execd not exiting immediately with SIGTERM on AIX (ENT-3147) - - Fix automatic service stops based on runlevel (redhat/centos) - (CFE-2611) - - Fix cf-serverd crash when reporting corrupted data (ENT-3023) - - Fix rare output truncation on Solaris 10/11 (CFE-2527) - - Fix crash on Solaris when ps ucb variant is not available (CFE-2506) - - Fix logic to detect when running under a Xen Hypervisor (CFE-1563) - - Fix "lastseenexpireafter" 32-bit signed int overflow (zendesk#3204) - - Fix IPv6 parsing to be un-reversed (CFE-2580) - -3.10.0: - New features/additions: - - All new features/additions for 3.8 and 3.9 are also included in 3.10. - - Add: Classes body tailored for use with diff - - New feature: Classes promise: allow classes without an expression to default to defined. - - Support for custom ports and host names as policy hub (CFE-953) - - Add: Definition of from_cfexecd for cf-execd initiated runs - (CFE-2386) - - Add < <= > >= operators to eval(). - - Add testing jUnit and TAP bundles and include them in stdlib.cf - - New function isipinsubnet() (ENT-7949) - - LogDebug(): implement module-based debug logging. - Now most DEBUG messages are *not* printed even when "-d" is in use, but - the specific debug module has to be enabled on the command line. For - example to enable all log modules, run: - cf-agent -d --log-modules=all - - Add: edit_line contains_literal_string to stdlib - - Add variablesmatching_as_data() function paralleling variablesmatching() - (Redmine #7885) - - Allow specifying agent maxconnections via def.json (CFE-2461) - - Add getuserinfo() function - - Add body agent control select_end_match_eof option. (CFE-2390) - - Add class to enable post transfer verification during policy updates - - Add ability to append to bundlesequnece with def.json (CFE-2460) - - policy_server.dat now appends a newline and supports host & port - - Changes: - - Rewrite iteration engine to avoid combinatorial explosion with nested variable expansions. - This speeds up enormously the execution of policies that included long - slists or JSON containers, that in the past didn't even terminate. - Change: "cf_null" string literal was changed to not be something - special, and it's now a string that can be used anywhere, like - in slists or part of bundlesequence etc. - NOTE: Old policy should be grep'ed for "cf_null" and in case such - occurences were handled specially, they should be reworked. - Change: "--empty-list--" is now never printed by format(), - an empty list is now printed as "{ }". - Change: Order of pre-evaluation was slightly changed, A new "vars" pass - at the beginning of pre-evaluation was added. It used to be - classes-vars, but it was changed to vars-classes-vars. As a - result some classes or variables might be evaluated at a - different time than before. As always try to write policy code that works no matter what the - order of execution is. - One way is to always *guard* the execution of functions to avoid - bogus function results. For example the following will avoid - running execresult() bevore the file has been created: - execresult("cmd /path/to/filename") if => fileexists("/path/to/filename"); - C internals: NULL Rlist is now perfectly valid, in fact it is the only - way to denote an empty Rlist. - C internals: Since a slist variable can be NULL, API of - EvalContextVariableGet() changed: The way to detect if a - variable is found, is not to check return value for NULL, - but to check returned *type* for CF_DATA_TYPE_NONE. - Fixed what I could find as wrong API uses. (CFE-2162) - - Allow arbitrary service policies (CFE-2402) - - Behaviour change: cf-execd: Do not append -Dfrom_cfexecd to exec_command . - (CFE-2386) - - Failsafe/Bootstrap no longer copy files starting with .git (like .gitignore) or .mailmap - (CFE-2439) - - Change: Enable strict transport security - - Change: Disable http TRACE method - - Change: Verify transfered files during policy update - - Allow getvariablemetatags() and getclassmetatags() to get a specific tag key - - Change: Use more restrictive unix socket perms (ENT-2705) - - Add sys.user_data container for user starting agent. - - Pass package promise options to underlying apt-get call (#802) - (CFE-2468) - - Change: Enable agent component management policy on systemd hosts - (CFE-2429) - - Change: Switch processes restart_class logging to verbose - - Change: Log level for keeping verbatim JSON to DEBUG (CFE-2141) - - Change: Require network before CFEngine services (CFE-2435) - - Behaviour change: getvalues(inexistent_var) returns an empty list. - Restores 3.7.x and earlier behaviour. (CFE-2479) - - Behaviour change: when used with CFEngine 3.10.0 or greater, - bundles set_config_values() and set_line_based() are appending a - trailing space when inserting a configuration option with empty value. - (CFE-2466) - - Behaviour change: getvalues() always returns a list now. Even when v is a simple - string (i.e. not an iterable) it will return an slist with one element: - the value of the string variable. - - Behaviour change: readintlist() now prints an error if the - file contains real numbers, not integers, and aborts; previously it was - printing an info-level error message, was half-reading an integer out of - the real, and was continuing successfully. - - Ensure synchronous start and stop with systemctl (ENT-2841) - - Change select_region INI_section to match end of section or end of file - (CFE-2519) - - Bug fixes: - - Fix files promise not setting ACL properly on directories. (CFE-616) - - Upgrade CFEngine dependencies to the following versions: - - lixml2 2.9.4 - - OpenSSL 1.0.2j - - LibYAML 0.1.7 - - Curl 7.50.3 - - Fix cumulative() to accept up to 1000 years, like it's documented. - - Fixed parsing of host name/IP and port number in cf-runagent - (CFE-546) - - Fix intermittent error message of type: - "error: Process table lacks space for last columns: " (CFE-2371) - - storage: Properly initialize the list of current mounts (CFE-1803) - - Fix 'contain' attribute 'no_output' having no effect when - the 'commands' promise is using 'module => "true"'. (CFE-2412) - - Fix bug which caused empty emails to be sent from cf-execd - if there was no previous output log and the new log was fully filtered - by email filters. (ENT-2739) - - Allow ifelse(FALSE, $(x), "something else") to work. (CFE-2260) - - Fix connection cache, reuse connections when possible. (CFE-2447) - - Fix rare bug that would sometimes prevent redis-server from launching. - - Fix bug in files promise when multiple owners are promised - but first one doesn't exist, and improve logging . (CFE-2432) - - Define kept outcome with action warn if edit_line is as expected - (CFE-2424) - - Example using getvariablemetatags() and getclassmetatags() to get a specific tag key - - Remove 2k limit on strings length when writing JSON policies - (CFE-2383) - - Fix ttime_range constraint to go higher than 2G as number of seconds. - - Change: cronjob bundle tolerates different spacing - - Allow editing fields in lines longer than 4k (CFE-2438) - - Don't send empty emails for logs where everything is filtered. - (ENT-2739) - - Allow maplist(), maparray(), and mapdata() to evaluate function calls during iteration - (ARCHIVE-1619) - - insert_lines is no longer implicitly matching EOF as - end of the region if 'select_end' pattern is not matched . (CFE-2263) - - Change: Remove executable bit from systemd units (CFE-2436) - - cf-serverd should reload def.json when reloading policy (CFE-2406) - - Fix cf-monitord detection of usernames of the process table on AIX. - - Speed up local and remote file copying and fix spurious errors. - (ENT-2769) - - Fix occasional segfault when running getindices() on a - variable that has indices of multiple depths (e.g. both "a[x]" and - "a[x][y]"). (CFE-2397) - - When no file is provided when calling cf-promises - with cf or json output, use promises.cf by default. This restores the - previous behavior. (CFE-2375) - - Fix: Services starting or stopping unnecessarily (CFE-2421) - - Change: Split systemd units (CFE-2278) - - EOF is matched as an end of the region in edit_line - promises only if 'select_end_match_eof' parameter is true. (CFE-2263) - - Fix double logging of output_prefix, and log process name for cf-agent syslog messages. - (CFE-2225) - - Be less verbose if a network interface doesn't have a MAC address. - (CFE-1995) - - Fix: CFEngine choking on standard services (CFE-2806) - - Fix insert_lines related memory corruption (CFE-2520) - - Fix cf-serverd crash when reporting corrupted data. (ENT-3023) - - Fix ability to manage INI sections with metachars for - manage_variable_values_ini and set_variable_values_ini (CFE-2519) - - Fix apt_get package module incorrectly using interactive mode. - - Fix crash on Solaris when ps ucb variant is not available. (CFE-2506) - - cf-serverd: Do not close connection when file does not exist. - (CFE-2532) - - getvalues() now behaves correctly for old CFEngine arrays of depth 1. - Known issues: getvalues() still misbehaves with double-indexed arrays - (see (CFE-2504, CFE-2536) - -3.9.0: - New features/additions: - - Add optional interface parameter to iprange() to match only one interface. - - Allow '=' in symbolic modes (Redmine #7826) - - Add: FreeBSD ports package module - - New package module for FreeBSD pkg package manager. - - Add support for adding/removing fifos in policy - - Add Linux parsing of /proc/net/ data. - - sys.inet - - sys.inet6 - - sys.interface_data - - Data is returned as a data container. - - See documentation for more details. (Jira CFE-1991) - - sys.ip2iface: new reverse mapping variable from IP to interface name - - Namespaced classes can now be specified on the command line. - - Namespaces can now be passed to cf-runagent -D and --remote-bundles - (Redmine #7856) - - Add 'cf-full' and 'json-full' to cf-promises '-p' option. - They generate output based on the entire policy. The existing 'cf' - already behaved this way, and it has now been changed to generate - output only for a single file, which the existing 'json' option - already does. - - New language functions: processexists() and findprocesses() - (Redmine #7633) - - Implement new regex_replace() function. (Redmine #7346) - - Add log rotation policy for state/classes.jsonl log. (Redmine #7951) - - Added collect_vars utility bundle to stdlib - - Intoduce report_class_log attribute to body agent control. - (Redmine #7951) - - Add standard_services service_method allowing for explicit usage - - cf-promises --show-vars can now show JSON variables. - - Add json_pipe mode to mapdata(), which allows piping a - JSON container to an external program for manipulation and receiving - JSON back. The jq tool is a good example where this mode can be - useful. A corresponding $(def.jq) variable has also been added with - a default path to this tool. See documentation for mapdata() for - more information and examples. (Jira CFE-2071) - - Behaviour change: "true" is always defined and "false" is never defined in a context expression. - - Add: nimclient package module for AIX - This module provides basic functionality for using nimclient as a means - to ensure packages are either present or absent. It does not support - listing package updates available or provide any special caching. - - Add callstack_callers() and callstack_promisers() functions. - - Log variable definitions in debug output. (Redmine #7137) - - Add: Memory information to host info report (Jira CFE-1177) - - In Mustache templates, one can now use {{#-top-}} and - {{/-top-}} tags to iterate over the top level element in a - container. (Redmine #6545) - - Add network_connections() function that parses /proc/net - - Provide new -w argument to override the workdir for testing - - New feature: Emails sent by cf-execd can be filtered to get - rid of emails for unwanted log messages. The attributes - mailfilter_include and mailfilter_exclude in body executor - control control what to include. See documentation for cf-execd for - more information. (Jira CFE-2283) - - Add: file_make_mustache bundle to render mustache templates - - Add '-n' flag to cf-key to avoid host name lookups. - - cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor multiple -D, -N and -s arguments - (Redmine #7191) - - Add "canonify" mode to mapdata(). - - Add: printfile bodies to stdlib - - Add: New results classes body [] (Redmine #7418, #7481) - - Implement cf-runagent --remote-bundles and cf-serverd "bundle" access promise. - (Redmine #7581) - - Add commands promise arglist attribute, augmenting args attribute. - - It's now possible to reference variables in inline JSON, - for example: mergedata('[ thing, { "mykey": otherthing[123] } ]'). - thing and otherthing[123] will be resolved as variables, since - they are unquoted. See the documentation for more details. - (Redmine #7871) - - Allow inline JSON to be used in the following function - calls: - - data_expand() - - difference() - - every() - - filter() - - format() - - getindices() - - getvalues() - - grep() - - intersection() - - join() - - length() - - makerule() - - mapdata() - - maplist() - - mean() - - mergedata() - - none() - - nth() - - parsejson() - - product() - - regarray() - - reglist() - - reverse() - - shuffle() - - some() - - sort() - - storejson() - - string_mustache() - - sublist() - - sum() - - unique() - - url_get() - - variance() - For example: mergedata('[ "thing", { "mykey": "myvalue" } ]') - See the documentation for more details. (Jira CFE-2253) - - Add: edit_line contains_literal_string to stdlib - - Add body agent control select_end_match_eof option. (Jira CFE-2390) - - Changes: - - Change: classesmatching(): order of classes changed - - Change: getindices(), getvalues(), variablesmatching(), maparray(): - order of variables returned has changed - - Change: set_quoted_values uses bundle scoped classes - - Change: set_config_values uses bundle scoped classes - - Change: set_variable_values uses bundle scoped classes - - Change: set_config_values_matching uses bundle scoped classes - - Change: manage_variable_values_ini uses bundle scoped classes - - Change: set_line_based should use bundle scoped classes - (Jira CFE-1959) - - getvalues() will now return a list also for data containers, - and will descend recursively into the containers. (Redmine #7116) - - Change: Improve git drop user support - - Use new package promise as default package promise - implementation. (Jira CFE-2332) - - Don't follow symbolic links when copying extended attributes. - - When a bodydefault:_ body is - defined, it will be used by all promises of type - unless another body is explicitly used. - - cf-serverd no longer appends "-I -Dcfruncommand" to - cfruncommand, this has to be done manually in masterfiles - body server control. (Redmine #7732) - - eval() function arguments mode and options are now - optional. - - sort() function argument mode is now optional. - - Change: returnszero() no longer outputs the output of a command. - The output can be seen by enabling info mode (-I). - - cfruncommand is not executed under shell. (Redmine #7409) - - Remove: Apache CGI module - - Change: Make maxbytes arg of readjson() and readyaml() optional - - Classes matching agent control's abortclasses are - now printed before exit, even if they are defined in common bundles. - Previously the regex (in abortclasses) that matched the class was - printed if the class was defined in a common bundle, but the class - itself was printed if it was defined in an agent bundle. With this - change, the defined class that caused the abort is always printed. - - Remove: Support for email settings from augments_file (Redmine #7682) - - Change: set_variable_values_ini uses bundle scoped classes - - findfiles() now skips relative paths. (Redmine #7981) - - Clients connections using non TLS protocol are rejected - by default. . (Jira CFE-2339) - - Change: Policy files specified in the "inputs" section of - def.json will no longer be auto-loaded. One has to refer to the - which are using the "inputs" field inside def.json. (Redmine #7961) - - Change: Separate binary details from policy update (Redmine #7662) - - Add guard for binary upgrade during bootstrap (Redmine #7861) - - Change: Modernize pkg module and package_method - - Remove: Userdir apache module - - filestat(path, "linktarget") now follows non-absolute links and returns full path of target. - This introduces a change in behaviour. Here is an example: - $ ls -l /bin/sh - lrwxrwxrwx 1 root root 4 Jun 4 2015 /bin/sh -> dash - Previously the filestat function would return "dash", and would also log - an error that the file can not be read. Now it will return "/bin/dash" - (or the final destination if it happens that /bin/dash is also a - symlink). - You can still get the previous behaviour by using - filestat(path, "linktarget_shallow"). (Redmine #7404) - - Define (bootstrap|failsafe)_mode during update.cf when triggerd from failsafe.cf - (Redmine #7861) - - Behavior change: The promise string of a processes - promise now matches just the command line of each process instead of - the line that is output by ps. This was done to reduce fragmentation - between platforms, since ps is a very nonstandardized tool. - (Jira CFE-2161) - - Allowed namespace names made more strict, to disallow - namespaces that cannot be reached. (Redmine #7903) - - Behavior change: When using readintlist(), readreallist() - or readstringlist(), parsing an empty file will no longer result in a - failed function call, but instead an empty list. Failure to open the - file will still result in a failed function call. - - insert_lines is no longer implicitly matching EOF as - end of the region if 'select_end' pattern is not matched . - (Jira CFE-2263) - - EOF is matched as an end of the region in edit_line - promises only if 'select_end_match_eof' parameter is true. - (Jira CFE-2263) - - Bug fixes: - - Upgrade CFEngine dependencies to the following versions: - - Curl 7.48.0 - - libxml2 2.9.4 - - LMDB 0.9.18 - - OpenLDAP 2.4.44 - - OpenSSL 1.0.2h - - PCRE 8.38 - (Jira ENT-2720) - - Upgrade dependencies to latest minor versions. - For Community / Enterprise: - For Enterprise: - - Fix bug which sometimes misparses user names in ps output. - - Fix: Problem with git not dropping privileges soon enough - - Allow def.json up to 5MB instead of 4K. - - It is possible to edit the same value in multiple regions - of one file. (Redmine #7460) - - CFEngine on Windows no longer truncates log messages if the - program in question is killed halfway through. - - Fixed a bug which caused def.json not being able to define - classes based on other hard classes. (Jira CFE-2333) - - Change: Tighten Enterprise hub permissions (Jira ENT-2708) - - Fix a regression which would sometimes cause "Permission - denied" errors on files inside directories with very restricted - permissions. (Redmine #7808) - - Fix use-after-free in ArrayMap and HashMap (Redmine #7952) - - Package repositories are no more hit every time package promise - is evaluated on SUSE. - - Fix a bug which sometimes caused package promises to be - skipped with "XX Another cf-agent seems to have done this since I - started" messages in the log, most notably in long running cf-agent - runs (longer than one minute). (Redmine #7933) - - TTY detection should be more reliable. (Redmine #7606) - - cf-promises -p cf now produces valid CFEngine code (Redmine #7956) - - Fix ps options for FreeBSD to check processes only in current host and not in jails - - cf-runagent now properly supports multiple -D or -s arguments - (Redmine #7191) - - Fix: Work around impaired class definition from augments - (Jira CFE-2333) - - Fix "No such file or directory" LMDB error on heavily loaded hosts. - (Jira CFE-2300) - - Check for empty server response in RemoteDirList after decryption - (Redmine #7908) - - Small performance optimization when cf-execd scans emails before sending. - - Fix handling of closed connections during transactions - (Redmine #7926) - - The core ps parsing engine used for processes promises - has been rewritten from scratch, and should be more robust than - before. (Jira CFE-2161) - - Fix the lexer which could not handle empty newline(s) - before a @endif. - - groupexists() no longer fails to detect a group name - starting with a digit. (Jira CFE-2351) - - Fix HP-UX specific bug that caused a lot of log output to disappear. - - Fix unresolved variable (Redmine #7931) - - Change: Suppress standard services noise on SUSE (Redmine #6968) - - Reduce verbosity of yum package module (Redmine #7485) - - cf-runagent: Allow connections to localhost instead of failing silently. - - Show errors regarding failure to copy extended attributes - when doing a local file copy. Errors could happen when copying - across two different mount points where the support for extended - attributes is different between the mount points. - - Fix classes being set because of hash collision in the implementation. - (Redmine #7912) - - Fix build failure on FreeBSD 7.1 (Redmine #7415) - - Improve logging when managing setuid/setgid - - Reduce verbosity of apt_get package module (Redmine #7485) - - packagesmatching() and packageupdatesmatching() should work - when new package promise is used. (Jira CFE-2246) - - Fix bug which could render host unable to recover from a - syntax error, even if failsafe.cf was utilized. This could happen if - the file containing the syntax error was specified in the def.json - special file. (Redmine #7961) - - Prevent crash in cf-execd email code when policy server is not set. - - In case of networking error, assume checksum is wrong - - Fix two cases where action_policy warn still produces errors - (Redmine #7274) - - Fix bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) - - @if minimum_version now correctly ignores lines starting with '@' - (Redmine #7862) - - No longer hang when changing permissions/ownership on fifos - (Redmine #7030) - - readfile() and read*list() should print an error if they fail to read file. - (Redmine #7702) - - The isvariable() function call now correctly accepts all - array variables when specified inline. Previously it would not accept - certain special characters, even though they could be specified - indirectly by using a variable to hold it. (Redmine #7088) - - Fix file descriptor leak when there are network errors. - - Improve robustness of process table parsing on Solaris. - (Jira CFE-2161) - - Installing packages containing version numbers using yum - now works correctly. (Redmine #7825) - - Parse def.json vars, classes and inputs from the C - code. This fixes a bug where certain entries in this file would be - parsed too late to have any effect on the evaluation. - (Redmine #7453, #7615) - - Change package modules permissions on hub package so that - hub can execute package promises. (Redmine #7602) - - Fix: CFEngine choking on standard services (Jira CFE-2086) - - Fix: cf-upgrade on SUSE - - Fix: Stop CFEngine choking on systemctl output (Jira CFE-2806) - - storage: Properly initialize the list of current mounts - (Jira CFE-1803) - - Fix bug which caused empty emails to be sent from cf-execd - if there was no previous output log and the new log was fully filtered - by email filters. (Jira ENT-2739) - - Don't send empty emails for logs where everything is filtered. - (Jira ENT-2739) - - Fix intermittent error message of type: - "error: Process table lacks space for last columns: " - (Jira CFE-2371) - - Be less verbose if a network interface doesn't have a MAC address. - (Jira CFE-1995) - -3.8.2: - Fixes: - - Update library dependencies to latest version. - Libraries upgraded: - - curl 7.47.0 - - LMDB 0.9.18 - - MySQL 5.1.72 - - OpenLDAP 2.4.44 - - OpenSSL 1.0.2g - - PostgreSQL 9.3.11 - - Redis 3.0.7 - - rsync 3.1.2 - PHP was kept at 5.6.17 because of problems with the 5.6.19 version. - - Reduce verbosity of apt_get package module (Redmine #7485) - - Reduce verbosity of yum package module (Redmine #7485) - - The isvariable() function call now correctly accepts all - array variables when specified inline. Previously it would not accept - certain special characters, even though they could be specified - indirectly by using a variable to hold it. (Redmine #7088) - - Don't follow symbolic links when copying extended attributes. - - Fix a bug which sometimes caused package promises to be - skipped with "XX Another cf-agent seems to have done this since I - started" messages in the log, most notably in long running cf-agent - runs (longer than one minute). (Redmine #7933) - - Fix bug which could render host unable to recover from a - syntax error, even if failsafe.cf was utilized. This could happen if - the file containing the syntax error was specified in the def.json - special file. (Redmine #7961) - - Change: Policy files specified in the "inputs" section of - def.json will no longer be auto-loaded. One has to refer to the - $(def.augments_inputs) variable in the policy (the standard - masterfiles policies include this by default). This only affects - installations which are not based on the standard masterfiles, and - which are using the "inputs" field inside def.json. (Redmine #7961) - - Fix file descriptor leak when there are network errors. - - Fix cf-serverd error messages with classic protocol clients - (Redmine #7818) - - Installing packages containing version numbers using yum - now works correctly. (Redmine #7825) - - Fix ps options for FreeBSD to check processes only in current host and not in jails - - Fix build failure on FreeBSD 7.1 (Redmine #7415) - - Show errors regarding failure to copy extended attributes - when doing a local file copy. Errors could happen when copying - across two different mount points where the support for extended - attributes is different between the mount points. - - Fix classes being set because of hash collision in the implementation. - (Redmine #7912) - - Allow def.json up to 5MB instead of 4K. - - Fix a regression which would sometimes cause "Permission - denied" errors on files inside directories with very restricted - permissions. (Redmine #7808) - - Change: Suppress standard services noise on SUSE (Redmine #6968) - - Changes: - - Change: classesmatching(): order of classes changed - -3.8.1: - Changes: - - Upgrade CFEngine dependencies to the following versions: - - OpenSSL 1.0.2e - - PCRE 8.38 - - libxml2 2.9.3 - - OpenLDAP 2.4.43 - - libcurl 7.46.0 - - Upgrade LMDB to version 0.9.17. (Redmine #7879) - - Bug fixes: - - @if minimum_version now correctly ignores lines starting with '@' - (Redmine #7862) - - Add guard for binary upgrade during bootstrap (Redmine #7861) - - Namespaced classes can now be specified on the command line. - - Fix bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) - - Fix two cases where action_policy warn still produces errors - (Redmine #7274) - - Parse def.json vars, classes and inputs from the C - code. This fixes a bug where certain entries in this file would be - parsed too late to have any effect on the evaluation. - (Redmine #7453, #7615) - - Fix HP-UX specific bug that caused a lot of log output to disappear. - - Check for empty server response in RemoteDirList after decryption - (Redmine #7908) - - getvalues() will now return a list also for data containers, - and will descend recursively into the containers. (Redmine #7116) - - Define (bootstrap|failsafe)_mode during update.cf when triggerd from failsafe.cf - (Redmine #7861) - - -3.8.0: - New features/additions: - - New feature: Bodies can now inherit attribute values from - other bodies by specifying "inherit_from" with the name of the body to - inherit from, plus any arguments it accepts. For example: - body classes myclasses - { - inherit_from => classes_generic("myname"); - } - (Redmine #4309) - - Add url_get() function. (Redmine #6480) - - Add @if feature() syntax - @if feature work like @if minimum_version but allows distinguishing - between features chosen at compile time. - - Extend module protocol to create persistent classes. - To use it, have the module print a line with "^persistence=" - before printing any class names. "persistence=0" goes back to non- - persistent classes. (Redmine #7302) - - Add: New results classes body (Redmine #7418) - - Add: Debug reports in cfe_internal_cleanup_agent_reports - - Add: Path to svcprop in stdlib - - Add: masterfiles-stage script to contrib - - Whitespace is now allowed in class expressions for - readability, between class names and operators. (Redmine #7152) - - Changes: - - Change: Clarify bootstrap/failsafe reports - - Change: Improve in-line docs for internal log maintenance - - Change: Improve efficiency and debug reports (Redmine #7527) - - Remove: 3.5 support from masterfiles policy framework - - Long promiser strings with multiple lines are now - abbreviated in logs. (Redmine #3964) - - Change: Reunify Version based policy split - - Change: Separate binary details from policy update (Redmine #7662) - - Remove /var/cfengine/cf3..runlog. (Redmine #6957) - - Change: sys.libdir and sys.local_libdir to non version specific path - - sys.libdir now resolves to $(sys.inputdir)/lib - - sys.local_libdir now resolves to lib (Redmine #7559) - - Moved the following files to /var/cfengine/log/: - - /var/cfengine/promise_summary.log - - /var/cfengine/cfagent..log - - Change: Separate binary details from policy update (Redmine #7662) - - Remove: Support for email settings from augments_file (Redmine #7682) - - Bug fixes: - - It is possible to edit the same value in multiple regions - of one file. (Redmine #7460) - - Change package modules permissions on hub package so that - hub can execute package promises. (Rednime #7602) (Redmine #7602) - - Fix exporting CSV reports through HTTPS. (Redmine #7267) - - cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor - multiple -D, -N and -s arguments (Redmine #7191) - - readfile() and read*list() should print an error if they fail to read file. - (Redmine #7702) - - No longer hang when changing permissions/ownership on fifos - (Redmine #7030) - - Fix broken HA policy for 3rd disaster-recovery node. - - Fix: Policy errors for 3.5 and 3.6 - - Mustache templates: Fix {{@}} key when value is not a - primitive. The old behavior, when iterating across a map or array of - maps, was to abort if the key was requested with {{@}}. The new - behavior is to always replace {{@}} with either the key name or the - iteration position in the array. An error is printed if {{@}} is used - outside of a Mustache iteration section. - - Fix build with musl libc. (Redmine #7455) - - Fixed a bug which could cause daemons to not to be killed - correctly when upgrading or manually running "service cfengine3 stop". - (Redmine #7193) - - Fix daemons not restarting correctly on upgrade on AIX. - - Package promise: Fix inability to install certain packages - with numbers. (Redmine #7421) - - Redmine #6027 Directories should no more be changed randomly - into files. (Redmine #6027) - - Improve cf-serverd's lock contention because of getpwnam() - call. (Redmine #7643) (Redmine #7643) - - action_policy "warn" now correctly produces warnings instead - of various other verbosity levels. (Redmine #7274) - - If there is an error saving a mustache template file - it is now logged with log-level error (was inform). - - The JSON parser now supports unquoted strings as keys. - - Reduce malloc() thread contention on heavily loaded - cf-serverd, by not exiting early in the logging function, if no message - is to be printed. (Redmine #7624) (Redmine #7624) - - Fix a bug which caused daemons not to be restarted on - upgrade. (Redmine #7528) - - Include latest security updates for dependencies. - - Fixed bug which would cause bff and depot packages not to - run package scripts on removal. (Redmine #7193) - - Fix upgrade causing error message under systemd because of open ports. - - Fixed several bugs which prevented CFEngine from loading - libraries from the correct location. This affected several platforms. - (Redmine #6708) - - Legacy package promise: Result classes are now defined if - the package being promised is already up to date. (Redmine #7399) - - failsafe.cf will be created when needed. (Redmine #7634) - (Redmine #7634) - - If file_select.file_types is set to symlink and there - are regular files in the scanned directory, CFEngine no longer - produces an unnecessary error message. (Redmine #6996) - - Fix 'AIX_PREINSTALL_ALREADY_DONE.txt: cannot create' error - message on AIX. - - Fix package promise not removing dependent packages. (Redmine #7424) - - Fix: Solaris packages no longer contain duplicate library - files, but instead symlinks to them. (Redmine #7591) - - Fix select_class not setting class when used in common bundle with slist. - (Redmine #7482) - - Fix "@endif" keyword sometimes being improperly processed - by policy parser. (Redmine #7413) - - Fix noise from internal policy to upgrade windows agents - (Redmine #7456) - - cfruncommand now works if it contains spaces, with the TLS protocol. - (Redmine #7405) - - Fix warning "Failed to parse csv file entry" with certain very long - commands promises. (Redmine #7400) - - CFEngine no longer erronously passes -M to useradd on HP-UX. (Redmine #6734) - - cf-monitord no longer complains about missing thermal zone files. - (Redmine #7238) - - systemd is now detected correctly if it is a symlink (Redmine #7297) - - TTY detection should be more reliable. (Redmine #7606) - (Redmine #7606) - - -3.7.3 - Fixes: - - Reduce verbosity of yum package module (Redmine #7485) - - Reduce verbosity of apt_get package module (Redmine #7485) - - Upgrade dependencies to latest patch versions. - Upgraded libraries: - - curl 7.47.0 - - libxml2 2.9.3 - - LMDB 0.9.18 - - MySQL 5.1.72 - - OpenLDAP 2.4.44 - - OpenSSL 1.0.2g - - PCRE 8.38 - - PostgreSQL 9.3.11 - - Redis 2.8.24 - - rsync 3.1.2 - PHP was kept at 5.6.17 because of problems with the 5.6.19 version. - - Parse def.json vars, classes, and inputs in C (Redmine #7453) - - Namespaced classes can now be specified on the command line. - - getvalues() will now return a list also for data containers, - and will descend recursively into the containers. (Redmine #7116) - - @if minimum_version now correctly ignores lines starting with '@' - (Redmine #7862) - - Fix definition of classes from augments file - - Don't follow symbolic links when copying extended attributes. - - Fix ps options for FreeBSD to check processes only in current host and not in jails - - Fix cf-serverd error messages with classic protocol clients - (Redmine #7818) - - Change: Suppress standard services noise on SUSE (Redmine #6968) - - The isvariable() function call now correctly accepts all - array variables when specified inline. Previously it would not accept - certain special characters, even though they could be specified - indirectly by using a variable to hold it. (Redmine #7088) - - Show errors regarding failure to copy extended attributes - when doing a local file copy. Errors could happen when copying - across two different mount points where the support for extended - attributes is different between the mount points. - - Fix bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) - - Fix file descriptor leak when there are network errors. - - Fix a regression which would sometimes cause "Permission - denied" errors on files inside directories with very restricted - permissions. (Redmine #7808) - - Check for empty server response in RemoteDirList after decryption - (Redmine #7908) - - Allow def.json up to 5MB instead of 4K. - - Add guard for binary upgrade during bootstrap (Redmine #7861) - - Fix HP-UX specific bug that caused a lot of log output to disappear. - - Fix a bug which sometimes caused package promises to be - skipped with "XX Another cf-agent seems to have done this since I - started" messages in the log, most notably in long running cf-agent - runs (longer than one minute). (Redmine #7933) - - Define (bootstrap|failsafe)_mode during update.cf when triggerd from failsafe.cf - (Redmine #7861) - - Fix two cases where action_policy warn still produces errors - (Redmine #7274) - - Fix classes being set because of hash collision in the implementation. - (Redmine #7912) - - Fix build failure on FreeBSD 7.1 (Redmine #7415) - - Installing packages containing version numbers using yum - now works correctly. (Redmine #7825) - - Changes: - - Change: classesmatching(): order of classes changed - - 3.7.3 - Fixes: - - Reduce verbosity of yum package module (Redmine #7485) - - Reduce verbosity of apt_get package module (Redmine #7485) - - Upgrade dependencies to latest patch versions. - Upgraded libraries: - - curl 7.47.0 - - libxml2 2.9.3 - - LMDB 0.9.18 - - MySQL 5.1.72 - - OpenLDAP 2.4.44 - - OpenSSL 1.0.2g - - PCRE 8.38 - - PostgreSQL 9.3.11 - - Redis 2.8.24 - - rsync 3.1.2 - PHP was kept at 5.6.17 because of problems with the 5.6.19 version. - - Parse def.json vars, classes, and inputs in C (Redmine #7453) - - Namespaced classes can now be specified on the command line. - - getvalues() will now return a list also for data containers, - and will descend recursively into the containers. (Redmine #7116) - - @if minimum_version now correctly ignores lines starting with '@' - (Redmine #7862) - - Fix definition of classes from augments file - - Don't follow symbolic links when copying extended attributes. - - Fix ps options for FreeBSD to check processes only in current host and not in jails - - Fix cf-serverd error messages with classic protocol clients - (Redmine #7818) - - Change: Suppress standard services noise on SUSE (Redmine #6968) - - The isvariable() function call now correctly accepts all - array variables when specified inline. Previously it would not accept - certain special characters, even though they could be specified - indirectly by using a variable to hold it. (Redmine #7088) - - Show errors regarding failure to copy extended attributes - when doing a local file copy. Errors could happen when copying - across two different mount points where the support for extended - attributes is different between the mount points. - - Fix bad option nlwp to vzps on Proxmox / OpenVZ. (Redmine #6961) - - Fix file descriptor leak when there are network errors. - - Fix a regression which would sometimes cause "Permission - denied" errors on files inside directories with very restricted - permissions. (Redmine #7808) - - Check for empty server response in RemoteDirList after decryption - (Redmine #7908) - - Allow def.json up to 5MB instead of 4K. - - Add guard for binary upgrade during bootstrap (Redmine #7861) - - Fix HP-UX specific bug that caused a lot of log output to disappear. - - Fix a bug which sometimes caused package promises to be - skipped with "XX Another cf-agent seems to have done this since I - started" messages in the log, most notably in long running cf-agent - runs (longer than one minute). (Redmine #7933) - - Define (bootstrap|failsafe)_mode during update.cf when triggerd from failsafe.cf - (Redmine #7861) - - Fix two cases where action_policy warn still produces errors - (Redmine #7274) - - Fix classes being set because of hash collision in the implementation. - (Redmine #7912) - - Fix build failure on FreeBSD 7.1 (Redmine #7415) - - Installing packages containing version numbers using yum - now works correctly. (Redmine #7825) - - Changes: - - Change: classesmatching(): order of classes changed - - -3.7.2: - Bug fixes: - - readfile() and read*list() should print an error if they fail to read file. - (Redmine #7702) - - Fix 'AIX_PREINSTALL_ALREADY_DONE.txt: cannot create' error - message on AIX. - - If there is an error saving a mustache template file - it is now logged with log-level error (was inform). - - Change: Clarify bootstrap/failsafe reports - - Fixed several bugs which prevented CFEngine from loading - libraries from the correct location. This affected several platforms. - (Redmine #6708) - - If file_select.file_types is set to symlink and there - are regular files in the scanned directory, CFEngine no longer - produces an unnecessary error message. (Redmine #6996) - - Fix: Solaris packages no longer contain duplicate library - files, but instead symlinks to them. (Redmine #7591) - - cf-agent, cf-execd, cf-promises, cf-runagent and cf-serverd honor - multiple -D, -N and -s arguments (Redmine #7191) - - Fix "@endif" keyword sometimes being improperly processed - by policy parser. (Redmine #7413) - - It is possible to edit the same value in multiple regions - of one file. (Redmine #7460) - - Fix select_class not setting class when used in common bundle with slist. - (Redmine #7482) - - Fix broken HA policy for 3rd disaster-recovery node. - - Directories should no more be changed randomly - into files. (Redmine #6027) - - Include latest security updates for 3.7. - - Reduce malloc() thread contention on heavily loaded - cf-serverd, by not exiting early in the logging function, if no message - is to be printed. (Redmine #7624) - - Improve cf-serverd's lock contention because of getpwnam() - call. (Redmine #7643) - - action_policy "warn" now correctly produces warnings instead - of various other verbosity levels. (Redmine #7274) - - Change: Improve efficiency and debug reports (Redmine #7527) - - Change package modules permissions on hub package so that - hub can execute package promises. (Redmine #7602) - - No longer hang when changing permissions/ownership on fifos - (Redmine #7030) - - Fix exporting CSV reports through HTTPS. (Redmine #7267) - - failsafe.cf will be created when needed. (Redmine #7634) - - Mustache templates: Fix {{@}} key when value is not a - primitive. The old behavior, when iterating across a map or array of - maps, was to abort if the key was requested with {{@}}. The new - behavior is to always replace {{@}} with either the key name or the - iteration position in the array. An error is printed if {{@}} is used - outside of a Mustache iteration section. - - Legacy package promise: Result classes are now defined if - the package being promised is already up to date. (Redmine #7399) - - TTY detection should be more reliable. (Redmine #7606) - - Masterfiles: - - Add: Path to svcprop in stdlib - - Add: New results classes body [] (Redmine #7418, #7481) - - Remove: Support for email settings from augments_file (Redmine #7682) - -3.7.1: - Bug fixes: - - Fix daemons not restarting correctly on upgrade on AIX. (Redmine #7550) - - Fix upgrade causing error message under systemd because of open ports. - - Fix build with musl libc. (Redmine #7455) - - Long promiser strings with multiple lines are now - abbreviated in logs. (Redmine #3964) - - Fixed a bug which could cause daemons to not to be killed - correctly when upgrading or manually running "service cfengine3 stop". - (Redmine #7193) - - Package promise: Fix inability to install certain packages - with numbers. - - Fix package promise not removing dependent packages. (Redmine #7424) - - Fix warning "Failed to parse csv file entry" with certain very long - commands promises. (Redmine #7400) - - Fix misaligned help output in cf-hub. (Redmine #7273) - - Augmenting inputs from the augments_file (Redmine #7420) - - Add support for failover to 3rd HA node located outside cluster. - - Upgrade all dependencies for patch release. - - Fix a bug which caused daemons not to be restarted on - upgrade. (Redmine #7528) - -3.7.0: - New features: - - New package promise implementation. - The syntax is much simpler, to try it out, check out the syntax: - packages: - "mypackage" - policy => "absent/present", - - # Optional, default taken from common control - package_module => apt_get, - - # Optional, will only match exact version. May be - # "latest". - version => "32.0", - - # Optional. - architecture => "x86_64"; - - Full systemd support for all relevant platforms - - New classes to determine whether certain features are enabled: - * feature_yaml - * feature_xml - For the official CFEngine packages, these are always enabled, but - packages from other sources may be built without the support. - - New readdata() support for generic data input (CSV, YAML, JSON, or auto) - - YAML support: new readyaml() function and in readdata() - - CSV support: new readcsv() function and in readdata() - - New string_mustache() function - - New data_regextract() function - - eval() can now be called with "class" as the "mode" argument, which - will cause it to return true ("any") if the calculated result is - non-zero, and false ("!any") if it is zero. - - New list_ifelse() function - - New mapdata() function as well as JSON support in maparray(). - - filestat() function now supports "xattr" argument for extended - attributes. - - "ifvarclass" now has "if" as an alias, and "unless" as an inverse - alias. - - Ability to expand JSON variables directory in Mustache templates: - Prefix the name with '%' for multiline expansion, '$' for compact - expansion. - - Ability to expand the iteration *key* in Mustache templates with @ - - Canonical JSON output: JSON output has reliably sorted keys so the - same data structure will produce the same JSON every time. - - New "@if minimum_version(x.x)" syntax in order to hide future language - improvements from versions that don't understand them. - - Compile time option (--with-statedir) to - override the default state/ directory path. - - Fix error messages/ handling in process signalling which no longer - allowed any signals to fail silently - - Also enable shortcut keyword for cf-serverd classic protocol, eg to - simplify the bootstrap process for clients that have different - sys.masterdir settings (Redmine #3697) - - methods promises now accepts the bundle name in the promiser string, - as long as it doesn't have any parameters. - - In a services promise, if the service_method bundle is not specified, - it defaults to the promiser string (canonified) with "service_" as a - prefix. The bundle must be in the same namespace as the promise. - - Inline JSON in policy files: surrounding with parsejson() is now - optional *when creating a new data container*. - - New data_expand() function to interpolate variables in a data container. - - Add configurable network bandwidth limit for all outgoing - connections ("bwlimit" attribute in "body common control") . To - enforce it in both directions, make sure the attribute is set on both - sides of the connection. - - Secure bootstrap has been facilitated by use of - "cf-agent --boostrap HUB_ADDRESS --trust-server=no" - - Implement new TLS-relevant options (Redmine #6883): - - body common control: tls_min_version - - body server control: allowtlsversion - - body common control: tls_ciphers - - body server control: allowciphers (preexisting) - - Changes: - - Improved output format, less verbose, and messages are grouped. - - cf-execd: agent_expireafter default was changed to 120 minutes - (Redmine #7113) - - All embedded databases are now rooted in the state/ directory. - - TLS used as default for all outgoing connections. - - process promise now reports kept status instead of repaired if a - signal is not sent, even if the restart_class is set. The old - behavior was to set the repaired status whenever the process was not - running. (Redmine#7216). - - Bootstrapping requires keys to be generated in advance using cf-key. - - Disable class set on reverse lookup of interfaces IP addresses. - (Redmine #3993, Redmine #6870) - - Define a hard class with just the OS major version on FreeBSD. - - Abort cf-agent if OpenSSL's random number generator can't - be seeded securely. - - Masterfiles source tarball now installs using the usual commands - "./configure; make install". - - Updated Emacs syntax highlighting template to support the latest - syntax enhancements in 3.7. - - Deprecations: - - Arbitrary arguments to cfruncommand (using "cf-runagent -o") are - not acceptable any more. (Redmine #6978) - - 3.4 is no longer supported in masterfiles. - - Bug fixes: - - Fix server common bundles evaluation order (Redmine#7211). - - Limit LMDB disk usage by preserving sparse areas in LMDB files - (Redmine#7242). - - Fixed LMDB corruption on HP-UX 11.23. (Redmine #6994) - - Fixed insert_lines failing to converge if preserve_block was used. - (Redmine #7094) - - Fixed init script failing to stop/restart daemons on openvz/lxc - hosts. (Redmine #3394) - - rm_rf_depth now deletes base directory as advertised. (Redmine #7009) - - Refactored cf-agent's connection cache to properly differentiate - hosts using all needed attributes like host and port. - (Redmine #4646) - - Refactored lastseen database handling to avoid inconsistencies. - (Redmine #6660) - - cf-key --trust-key now supports new syntax to also update the - lastseen database, so that clients using old protocol will trust - the server correctly. - - Fixed a bug which sometimes caused an agent or daemon to kill or stop - itself. (Redmine #7075, #7244) - - Fixed a bug which made it difficult to kill CFEngine daemons, - particularly cf-execd. (Redmine #6659, #7193) - - Fixed a bug causing systemd not to be detected correctly on Debian. - (Redmine #7297) - - "cf-promises -T" will now correctly report the checked out commit, - even if you haven't checked out a Git branch. (Redmine #7332) - - Reduce verbosity of harmless errors related to socket timeouts and - missing thermal zone files. (Redmine #6486 and #7238) - - Masterfiles: - - Added: - - Support for user specified overring of framework defaults without - modifying policy supplied by the framework itself (see - example_def.json) - - Support for def.json class augmentation in update policy - - Run vacuum operation on postgresql every night as a part of - maintenance. - - Add measure_promise_time action body to lib (3.5, 3.6, 3.7, 3.8) - - New negative class guard cfengine_internal_disable_agent_email so - that agent email can be easily disabled by augmenting def.json - - Changed: - - Relocate def.cf to controls/VER/ - - Relocate update_def to controls/VER - - Relocate all controls to controls/VER - - Only load cf_hub and reports.cf on CFEngine Enterprise installs - - Relocate acls related to report collection from bundle server - access_rules to controls/VER/reports.cf into bundle server - report_access_rules - - Re-organize cfe_internal splitting core from enterprise specific - policies and loading the appropriate inputs only when necessary - - Moved update directory into cfe_internal as it is not generally - intended to be modified - - services/autorun.cf moved to lib/VER/ as it is not generally intended - to be modified - - To improve predictibility autorun bundles are activated in - lexicographical order - - Relocate services/file_change.cf to cfe_internal/enterprise. This - policy is most useful for a good OOTB experience with CFEngine - Enterprise Mission Portal. - - Relocate service_catalogue from promsies.cf to services/main.cf. It is - intended to be a user entry. This name change correlates with the main - bundle being activated by default if there is no bundlesequence - specified. - - Reduce benchmarks sample history to 1 day. - - Update policy no longer generates a keypair if one is not found. - (Redmine: #7167) - - Relocate cfe_internal_postgresql_maintenance bundle to lib/VER/ - - Set postgresql_monitoring_maintenance only for versions 3.6.0 and - 3.6.1 - - Move hub specific bundles from lib/VER/cfe_internal.cf into - lib/VER/cfe_internal_hub.cf and load them only if policy_server policy - if set. - - Re-organize lib/VER/stdlib.cf from lists into classic array for use - with getvalues - - Removed: - - Diff reporting on /etc/shadow (Enterprise) - - Update policy from promise.cf inputs. There is no reason to include - the update policy into promsies.cf, update.cf is the entry for the - update policy - - _not_repaired outcome from classes_generic and scoped_classes generic - (Redmine: # 7022) - - Fixes: - - standard_services now restarts the service if it was not already - running when using service_policy => restart with chkconfig (Redmine - #7258) - - -3.6.5: - Features: - - Introduced "systemd" hard class. (Redmine #6995) - - Added paths to dtrace, zfs and zpool on FreeBSD in masterfiles. - - Bug fixes: - - Fixed build error on certain RHEL5 and SLES10 setups. (Redmine #6841) - - Fixed a bug which caused dangling symlinks not to be removed. - (Redmine #6582) - - Fixed data_readstringarrayidx function not preserving the order of the - array it's producing. (Redmine #6920) - - Fixed a bug which sometimes caused CFEngine to kill the wrong daemon - if both the host and a container inside the host were running - CFEngine. (Redmine #6906) - - Made sure the rm_rf_depth bundle also deletes the base directory. - (Redmine #7009) - - Fixed monitord reporting wrongly on open ports. (Redmine #6926) - - Skip adding the class when its name is longer than 1024 characters. - Fixed core dump when the name is too large. (Redmine #7013) - - Fixed detection of stopped process on Solaris. (Redmine #6946) - - Fixed infinite loop (Redmine #6992) plus a couple more minor - bugs in edit_xml promises. - -3.6.4: - Features: - - Introduced users promises support on HP-UX platform. - - Introduced process promises support on HP-UX platform. - - Bug fixes: - - Fixed bug on FreeBSD which sometimes led to the wrong process being - killed (Redmine #2330) - - Fixed package version comparison sometimes failing with rpm package - manager (Redmine #6807) - - Fixed a bug in users promises which would sometimes set the wrong - password hash if the user would also be unlocked at the same time. - - Fixed a bug on AIX which would occasionally kill the wrong process. - - Improved error message for functions that require an absolute path. - (Redmine #6877) - - Fixed some spelling errors in examples. - - Fixed error in out-of-tree builds when building cf-upgrade. - - Fixed a bug which would make cf-agent exit with an error if it was - built with a custom log directory, and that directory did not exist. - - Fixed ordering of evaluating promises when depends_on is used. - (Redmine #6484, Redmine #5462) - - Skip non-empty directories silently when recursively deleting. - (Redmine #6331) - - Fix memory exhaustion with list larger than 4994 items. - (Redmine # 6672) - - Fix cf-execd segfault on IP address detection (Redmine #6905). - - Fix hard class detection of RHEL6 ComputeNode (Redmine #3148). - -3.6.3 - New features: - - Support for HP-UX 11.23 and later - - Experimental support for Red Hat Enterprise Linux 7 - - Bug fixes: - - Fix getindices on multi-dimensional arrays (Redmine #6779) - - Fix mustache template method to run in dryrun mode (Redmine #6739) - - Set mailto and mailfrom settings for execd in def.cf (Redmine #6702) - - Fix conflation of multi-index entries in arrays (Redmine #6674) - - Fix promise locking when transferring using update.cf (Redmine #6623) - - Update JSON parser to return an error on truncation (Redmine #6608) - - Fix sys.hardware_addresses not expanded (Redmine #6603) - - Fix opening database txn /var/cfengine/cf_lastseen.lmdb: - MDB_READERS_FULL when running cf-keys --show-hosts (Redmine #6602) - - Fix segfault (Null pointer dereference) when select_end in - delete_lines never matches (Redmine #6589) - - Fix max_file_size => "0" not disabling or allowing any size - (Redmine #6588) - - Fix ifvarclass, with iteration over list, failing when deleting - files with time condition (Redmine #6577) - - Fix classes defined with "or" constraint are never set if any value - doesn't evaluate to a scalar (Redmine #6569) - - Update "mailfrom" default in default policy (Redmine #6567) - - Fix logrotate ambiguity of filename (Redmine #6563) - - Fix parsing JSON files (Redmine #6549) - - Reduce write count activity to /var partition (Redmine #6523) - - Fix files delete attribute incorrectly triggering promise_kept - (Redmine #6509) - - Update services bundle output related to chkconfig when run in - inform mode. (Redmine #6492) - - Fix Solaris serverd tests (Redmine #6406) - - Fix broken bechaviour of merging arrays with readstringarray - (Redmine #6369) - - Fix ifelapsed bug with bundle nesting (Redmine #6334) - - Fix handling cf_null in bundlesequence (Redmine #6119) - - Fix maparray reading whole input array when using subarray - (Redmine #6033) - - Fix directories being randomly changed to files (Redmine #6027) - - Update defaults promise type to work with classes (Redmine #5748) - - systemd integration in services promises (Redmine #5415) - - Fix touch attribute ignoring action = warn_only (Redmine #3172) - - Fix 4KB string limit in functions readfile, string_downcase, - string_head, string_reverse, string_length, string_tail, - string_upcase (Redmine #2912) - -3.6.2 - Bug fixes: - - Don't regenerate software_packages.csv every time (Redmine #6441) - - Improve verbose message for package_list_command - - Fix missing log output on AIX (Redmine #6434) - - Assorted fixes to dirname() esp on Windows (Redmine #4716) - - Fix package manager detection - - Fix build issues on FreeBSD - - Allow copying of dead symbolic links (Redmine #6175) - - Preserve order in readstringarrayidx (Redmine #6466) - - Fix passing of unexpanded variable references to arrays - (Redmine #5893) - - Use entries for new {admin,deny}_{ips,hostnames} constraints in - the relevant legacy lists (Redmine #6542) - - Cope with ps's numeric fields overflowing to the right - - Interpret failing function calls in ifvarclass as class not set - (Redmine #6327) - - Remove unexpanded lists when extending lists (Redmine #6541) - - Infer start-time of a process from elapsed when needed - (Redmine #4094) - - Fix input range definition for laterthan() function (Redmine #6530) - - Don't add trailing delimiter when join()'ing lists ending with a - null-value (Redmine #6552) - - 9999999999 (ten 9s) or higher has been historically used as an upper - bound in CFEngine code and policy but because of overflow on 32-bit - platforms it caused problems with big numbers. Fixed in two ways: - first change all existing policy uses to 999999999 (nine 9s instead - of eleven 9s), second fix the C code to not wrap-around in case of - overflow, but use the LONG_MAX value (Redmine #6531). - - cf-serverd and other daemons no longer reload their configuration - every minute if CFEngine is built with an inputs directory outside - of the work directory (not the default). (Redmine #6551) - -3.6.1 - New features: - - Introduced Solaris and AIX support into the 3.6 series, with many associated build and - bug fixes. - - Changes: - - Short-circuit evaluation of classes promises if class is already set (Redmine #5241) - - Fix to assume all non-specified return codes are failed in commands promises (Redmine #5986) - - cf-serverd logs reconfiguration message to NOTICE (was INFO) so that it's always logged in syslog - - Bug fixes: - - File monitoring has been completely rewritten (changes attribute in files promise), which - eliminates many bugs, particularly regarding files that are deleted. Upgrading will keep - all monitoring data, but downgrading again will reinitialize the DB, so all files will be - reported as if they were new. (Redmine #2917) - - $(this.promiser) expands in files promises for 'transformer', 'edit_template', - 'copy_from.source', 'file_select.exec_program', 'classes' and 'action' bodies - (Redmine #1554, #1496, #3530, #1563) - - 'body changes' notifies about disappeared files in file monitoring (Redmine #2917) - - Fixed CFEngine template producing a zero sized file (Redmine #6088) - - Add 0-9 A-Z _ to allowed context of module protocol (Redmine #6063) - - Extend ps command column width and prepend zone name on Solaris - - Fixed strftime() function on Solaris when called with certain specifiers. - - Fixed users promise bug regarding password hashes in a NIS/NSS setup. - - Fixed $(sys.uptime), $(sys.systime) and $(sys.sysday) in AIX. (Redmine #5148, #5206) - - Fixed processes_select complaining about "Unacceptable model uncertainty examining processes" (Redmine #6337) - - ps command for linux has been changed to cope with big rss values (Redmine #6337) - - Address ps -axo shift on FreeBSD 10 and later (Redmine #5667) - - methods and services promises respect action_policy => "warn" (Redmine #5924) - - LMDB should no longer deadlock if an agent is killed on the hub while holding the DB lock. - Note that the change only affects binary packages shipped by CFEngine, since the upstream - LMDB project has not yet integrated the change. (Redmine #6013) - -3.6.0 - - Changes: - - Changes to logging output - - Add process name and pid in syslog message (GitHub #789) - - cf-serverd logging levels are now more standardised: - - INFO logs only failures - - VERBOSE logs successful requests as well - - DEBUG logs actual protocol traffic. - - cf-serverd now logs the relevant client IP address on - each message. - - Logging contexts to local database (cf_classes.tcdb) has been deprecated. - - 'usebundle' promisees are logged for all the bundle promises - - output from 'reports' promises has nothing prefixed except 'R: ' - - a log line with stack path is generated when the promise type evaluated changes - - LMDB (symas.com/mdb) is the default database for local data storage : use version 0.9.9 or later - cf-agent --self-diagnostics (-x) is only implemented for TCDB, not for LMDB - - port argument in readtcp() and selectservers() may be a - service name (e.g. "http", "pop3"). - - Enable source file in agent copy_from promises to be a relative path. - - file "changes" reporting now reports with log level "notice", instead of "error". - - process_results default to AND'ing of set attributes if not specified (Redmine #3224) - - interface is now canonified in sys.hardware_mac[interface] to align with - sys.ipv4[interface] (Redmine #3418) - - cf-promises no longer errors on missing bodies when run without --full-check (-c) - - Linux flavor "SUSE" now correctly spelled with all uppercase in variables and class names - (Redmine #3734). The "suse" lowercase version is also provided for convenience (Redmine #5417). - - $(this.promise_filename) and $(..._dirname) variables are now absolute paths. (Redmine #3839) - - Including the same file multiple times in 'body control inputs' is not an error - - portnumber in body copy_from now supports service names like - "cfengine", "pop3" etc, check /etc/services for more. - - The failsafe.cf policy, run on bootstrap and in some other - unusual cases, has been extracted from C code into libpromises/failsafe.cf - - masterfiles - - cf_promises_validated is now in JSON format - - timestamp key is timestamp (sec since unix epoch) of last time validated - - the masterfiles now come from https://github.com/cfengine/masterfiles and are - not in the core repository - - cf-serverd calls cf-agent with -Dcfruncommand when executing cf-runagent requests - - Mark as removed: promise_notkept_log_include, promise_notkept_log_exclude, promise_repaired_log_include, - promise_repaired_log_exclude, classes_include, classes_exclude, variables_include, - variables_exclude attributes from report_data_select body (syntax is valid but not functional). - They have been replaced by the following attributes: promise_handle_include, - promise_handle_exclude, metatags_include, metatags_exclude. - - New features: - - New promise type "users" for managing local user accounts. - - TLS authentication and fully encrypted network protocol. - Additions specific to the new type of connections: - - New attribute "allowlegacyconnects" in body server control, - which enables serving policy via non-latest CFEngine protocol, - to the given list of hosts. If the option is absent, it - defaults to allow all hosts. To refuse non-TLS connections, - specify an empty list. - - New attribute "protocol_version" in body copy_from, and body - common control, which defines the preferred protocol for - outgoing connections.. Allowed values at the moment: "0" or - "undefined", "classic" or "1", "latest" or "2". By leaving the - copy_from option as undefined the common control option is - used, and if both are undefined then classic protocol is used - by default. - - The new networking protocol uses TLS for authentication, - after which all dialog is encrypted within the established - TLS session. cf-serverd is still able to speak the legacy - protocol with old agents. - - The 'skipverify' option in 'body server control' is - deprecated and only left for compatibility; it does - nothing - - cf-serverd does not hang up the connection if some request - fails, so that the client can add more requests. - - For the connections using the new protocol, all of the - paths in bundle server access_rules now differentiate - between a directory and a file using the trailing - slash. If the path exists then this is auto-detected and - trailing slash appended automatically. You have to append - a trailing slash manually to an inexistent or symbolic - path (e.g. "/path/to/$(connection.ip)/") to force - recursive access. - - New in 'access' promises for 'bundle server access_rules' - - Attributes "admit_ips", "admit_hostnames", "admit_keys", - "deny_ips", "deny_hostnames", "deny_keys" - - "admit_keys" and "deny_keys" add the new functionality - of controlling access according to host identity, - regardless of the connecting IP. - - For these new attributes, regular expressions - are not allowed, only CIDR notation for "admit/deny_ips", exact - "SHA=..." strings for "admit/deny_keys", and exact hostnames - (e.g. "cfengine.com") or subdomains (starting with dot, - e.g. ".cfengine.com") for "admit/deny"_hostnames. Same rules - apply to 'deny_*' attributes. - - These new constraints and the paths in access_rules, can contain - special variables "$(connection.ip)", "$(connection.hostname)", - "$(connection.key)", which are expanded dynamically for every - received connection. - - For connections using the new protocol, "admit" and "deny" - constraints in bundle server access_rules are being phased - out, preferred attributes are now "admit_ips", "deny_ips", - "admit_hostnames", "deny_hostnames", "admit_keys", - "deny_keys". - - New "shortcut" attribute in bundle server access_rules used to - dynamically expand non-absolute request paths. - - masterfiles - - standard library split: lib/3.5 (compatibility) and lib/3.6 (mainline) - - many standard library bundles and bodies, especially packages- and file-related, - were revised and fixed - - supports both Community and Enterprise - - new 'inventory/' structure to provide OS, dmidecode, LSB, etc. system inventory - (configured mainly in def.cf) - - cf_promises_release_id contains the policy release ID which is the GIT HEAD SHA - if available or hash of tree - - a bunch'o'bundles to make starting with CFEngine easier: - - file-related: file_mustache, file_mustache_jsonstring, file_tidy, dir_sync, file_copy, - file_link, file_hardlink, file_empty, file_make - - packages-related: package_absent, package_present, package_latest, - package_specific_present, package_specific_absent, package_specific_latest, package_specific - - XML-related: xml_insert_tree_nopath, xml_insert_tree, xml_set_value, xml_set_attribute - - VCS-related: git_init, git_add, git_checkout, git_checkout_new_branch, - git_clean, git_stash, git_stash_and_clean, git_commit, git - - process-related: process_kill - - other: cmerge, url_ping, logrotate, prunedir - - New command line options for agent binaries - - New options to cf-promises - - '--show-classes' and '--show-vars' - - '--eval-functions' controls whether cf-promises should evaluate functions - - Colorized output for agent binaries with command line option '--color' - (auto-enabled if you set CFENGINE_COLOR=1) - - New language features - - New variable type 'data' for handling of structured data (ie JSON), - including supporting functions: - - 'data_readstringarray' - read a delimited file into a data map - - 'data_readstringarrayidx' - read a delimited file into a data array - - 'datastate' - create a data variable with currently set classes and variables - - 'datatype' - determine the type of the top element of a container - - 'format' - %S can be used to serialize 'data' containers into a string - - 'mergedata' - merge two data containers, slists/ilists/rlists, or "classic" - arrays into a data container - - 'parsejson' - create a data container from a JSON string - - 'readjson' - create a data container from a file that contains JSON - - 'storejson' - serialize a data container into a string - - Most functions operating on lists can also operate on data containers - - pass a data container to a bundle with the @(container) notation - - the module protocol accepts JSON for data containers with the '%' sigil - - Tagging of classes and variables allows annotating of language construct with - meta data; supporting functionality: - - The module protocol in 'commands' promises has been extended to allow setting - of tags of created variables and classes, and the context of created variables - - 'getclassmetatags' - returns list of meta tags for a class - - 'getvariablemetatags' - returns list of meta tags for a variable - - 'body file control' has an 'inputs' attribute to include library files and other - dependencies - - bundlesequences can be built with bundlesmatching() based on bundle name and tags - - New attributes in existing promise types and bodies - - New option 'preserve_all_lines' for insert_type in insert_lines promises - - Caching of expensive system functions to avoid multiple executions of - execresult() etc, can be controlled via cache_system_functions attribute in - body common control - - New option 'mailsubject' in body executor control allows defining the subject - in emails sent by CFEngine - - Support for Mustache templates in 'files' promises; use 'template_method' and - 'template_data' attributes. Without 'template_data' specified, uses datastate(). - - New and improved functions - - 'bundlesmatching' - returns list of defined bundles matching a regex and tags - - 'canonifyuniquely' - converts a string into a unique, legal class name - - 'classesmatching' - returns list of set classes matching a regex and tags - - 'eval' - evaluates mathematical expressions; knows SI k, m, g quantifiers, e.g. "100k" - - 'findfiles' - list files matching a search pattern; use "**" for recursive searches - - 'makerule' - evaluates whether a target file needs to be rebuilt from sources - - 'max', 'min' - returns maximum and minimum of the numbers in a container or list - (sorted by a 'sort' method) - - 'mean' - returns the mean of the numbers in a container or list - - 'nth' - learned to look up by key in a data container holding a map - - 'packagesmatching' - returns a filtered list of installed packages. - - 'readfile' - learned to read system files of unknown size like those in /proc - - 'sort' - can sort lexicographically, numerically (int or real), by IP, or by MAC - - 'string_downcase', 'string_upcase' - returns the lower-/upper-case version of a - string - - 'string_head', 'string_tail' - returns the beginning/end of a string - - 'string_length' - returns the length of a string - - 'string_reverse' - reverses a string - - 'string_split' - improved implementation, deprecates 'splitstring' - - 'variablesmatching' - returns a list of variables matching a regex and tags - - 'variance' - returns the variance of numbers in a list or container - - New hard classes - - Introduced alias 'policy_server' for context 'am_policy_hub' (the latter will - be deprecated) - - all the time-based classes have GMT equivalents - - New variables - - 'sys.bindir' - the location of the CFEngine binaries - - 'sys.failsafe_policy_path' - the location of the failsafe policy file - - 'sys.inputdir' - the directory where CFEngine searches for policy files - - 'sys.key_digest' - the digest of the host's cryptographic key - - 'sys.libdir', 'sys.local_libdir' - the location of the CFEngine libraries - - 'sys.logdir' - the directory where the CFEngine log files are saved - - 'sys.masterdir' - the location of masterfiles on the policy server - - 'sys.piddir' - the directory where the daemon pid files are saved - - 'sys.sysday' - the number of days since the beginning of the UNIX epoch - - 'sys.systime' - the number of seconds since the beginning of the UNIX epoch - - 'sys.update_policy_path' - the name of the update policy file - - 'sys.uptime' - the number of minutes the host has been online - - 'this.promise_dirname' - the name of the file in which the current promise - is defined - - 'this.promiser_uid' - the ID of the user running cf-agent - - 'this.promiser_gid' - the group ID of the user running cf-agent - - 'this.promiser_ppid' - the ID of the parent process running cf-agent - - Deprecations: - - 'splitstring' - deprecated by 'string_split' - - 'track_value' - - 'skipverify' - - Bug fixes: for a complete list of fixed bugs, see Redmine at https://cfengine.com/dev - - Various fixes in evaluation and variable resolution - - Improve performance of list iteration (Redmine #1875) - - Removed limitation of input length to internal buffer sizes - - directories ending with "/" are not ignored - - lsdir() always return a list now, never a scalar - - 'abortclasses' fixed to work in common bundles and other cases - - Namespaced 'edit_line' bundles now work (Redmine#3781) - - Lists are interpolated in correct order (Redmine#3122) - - cf-serverd reloads policies properly when they change - - Lots of leaks (memory and file descriptor) fixed - -3.5.3 - Changes: - - Improved security checks of symlink ownership. A symlink created by a user pointing - to resources owned by a different user will no longer be followed. - - Changed the way package versions are compared in package promises. (Redmine #3314) - In previous versions the comparison was inconsistent. This has been fixed, but may - also lead to behavior changes in certain cases. In CFEngine 3.5.3, the comparison - works as follows: - - For instance: - apache-2.2.31 ">=" "2.2.0" - will result in the package being installed. - - Bug fixes: - - Fix cf-monitord crash due to incorrect array initialization (Redmine #3180) - - Fix cf-serverd stat()'ing the file tree every second (Redmine #3479) - - Correctly populate sys.hardware_addresses variable (Redmine #2936) - - Add support for Debian's GNU/kfreebsd to build system (Redmine #3500) - - Fix possible stack corruption in guest_environments promises (Redmine #3552) - - Work-around hostname trunctation in HP-UX's uname (Redmine #3517) - - Fix body copy purging of empty directories (Redmine #3429) - - Make discovery and loading of avahi libraries more robust - - Compile and packaging fixes for HP-UX, AIX and Solaris - - Fix fatal error in lsdir() when directory doesn't exist (Redmine #3273) - - Fix epoch calculation for stime inrange calculation (Redmine #2921) - -3.5.2 - Bug fixes: - - Fix delayed abortclasses checking (Redmine #2316, #3114, #3003) - - Fix maplist arguments bug (Redmine #3256) - - Fix segfaults in cf-pomises (Redmine #3173, 3194) - - Fix build on Solaris 10/SmartOS (Redmine #3097) - - Sanitize characters from /etc/issue in sys.flavor for Debian (Redmine #2988) - - Fix segfault when dealing with files or data > 4K (Redmine #2912, 2698) - - Don't truncate keys to 126 characters in getindices (Redmine #2626) - - Files created via log_* actions now have mode 600 (Redmine #1578) - - Fix wrong log message when a promise is ignored due to 'ifvarclass' not matching - - Fix lifetime of persistent classes (Redmine #3259) - - Fix segfault when process_select body had no process_result attribute - Default to AND'ed expression of all specified attributes (Redmine #3224) - - Include system message in output when acl promises fail - - Fix invocation of standard_services bundle and corresponding promise compliance (Redmine #2869) - -3.5.1 - - Changes: - - File changes are logged with log level Notice, not Error - - The CFEngine Standard Library in masterfiles/libraries is now split into - promise-type specific policy files, and lives in a version-specific directory. - This should have no impact on current code, but allows more granular include of - needed stdlib elements (Redmine #3044) - - Bug fixes: - - Fix recursive copying of files (Redmine #2965) - - Respect classes in templates (Redmine ##2928) - - Fix timestamps on Windows (Redmine #2933) - - Fix non-root cf-agent flooding syslog (Redmine #2980) - - Fix email flood from cf-execd due to timestamps in agent output (Redmine #3011) - - Preserve security context when editing or copying local files (Redmine #2728) - - Fix path for sys.crontab on redhat systems (Redmine #2553) - - Prevent incorrect "insert_lines promise uses the same select_line_matching anchor" warning (Redmine #2778) - - Fix regression of setting VIPADDRESS to 127.0.0.1 (Redmine #3010) - - Fix "changes" promise not receiving status when file is missing (Redmine #2820) - - Fix symlinks being destroyed when editing them (Redmine #2363) - - Fix missing "promise kept" status for the last line in a file (Redmine #2943) - -3.5.0 - - New features: - - classes promises now take an optional scope constraint. - - New built-in functions: every, none, some, nth, sublist, uniq, filter - - every - - none - - some - - nth - - sublist - - uniq - - filter - - classesmatching - - strftime - - filestat - - ifelse - - maparray - - format - - cf-promises flag --parse-tree is replaced by --policy-output-format=, requiring the - user to specify the output format (none, cf, json) - - cf-promises allows partial check of policy (without body common control) without integrity check; - --full-check enforces integrity check - - Agent binaries support JSON input format (.json file as generated by cf-promises) - - cf-key: new options --trust-key/-t and --print-digest/-p - - Class "failsafe_fallback" is defined in failsafe.cf when main policy contains errors and - failsafe is run because of this - - Add scope attribute for body classes (Redmine #2013) - - Better diagnostics of parsing errors - - Error messages from parser now show the context of error - - New cf-agent option: --self-diagnostics - - New output format, and --legacy-output - - Warnings for cf-promises. - - Enable zeroconf-discovery of policy hubs for automatic bootstrapping - if Avahi is present - - Support for sys.cpus on more platforms than Linux & HPUX - - Changes: - - Parser no longer allows ',' after promiser or promisee. must be either ';' or lval - - Make parser output in GCC compatible format the only supported format - (remove --gcc-brief-format flag) - - - Silence license warnings in Enterprise Free25 installations - - action_policy => "warn" causes not_kept classes to be set on promise needing repair. - - Command line option version (-V) now prints a shorter parsable version without graphic - - Implicit execution of server and common bundles taking arguments is skipped in cf-serverd. - - WARNING: option --policy-server removed, require option to --bootstrap instead - - process promises don't log if processes are out of range unless you - run in verbose mode - - reports promises are now allowed in any context (Redmine #2005) - - cf-report has been removed - - cf-execd: --once implies --no-fork - - Version info removed from mail subject in the emails sent by cf-execd. - The subject will only contain "[fqname/ipaddress]" instead of "communnity/nova [fqname/ipaddress]" - Please change your email filters accordingly if necessary. - - "outputs" promise type is retired. Their semantics was not clear, and the functionality - is better suited for control body setting, not a promise. - - Tokyo Cabinet databases are now automatically checked for - correctness during opening. It should prevent a number of issues - with corrupted TC databases causing binaries to hang. - - Improved ACL handling on Windows, which led to some syntax changes. We now consistently - use the term "default" to describe ACLs that can be inherited by child objects. These - keywords have received new names: - acl_directory_inherit -> acl_default - specify_inherit_aces -> specify_default_aces - The old keywords are deprecated, but still valid. In addition, a new keyword - "acl_inherit" controls inheritance behavior on Windows. This feature does not exist on - Unix platforms. (Redmine #1832) - - Networking code is moved from libpromises to its own library, - libcfnet. Work has begun on making the API more sane and thread-safe. - Lots of legacy code was removed. - - Add getaddrinfo() replacement in libcompat (borrowed from PostgreSQL). - - Replace old deprecated and non thread-safe resolver calls with - getaddrinfo() and getnameinfo(). - - Hostname2IPString(), IPString2Hostname() are now thread-safe, and are - returning error when resolution fails. - - Running cf-execd --once now implies --no-fork, and also does not wait - for splaytime to pass. - - execresult(), returnszero() and commands promises no longer requires the first word - word to be an absolute path when using the shell. (Part of Redmine #2143) - - commands promises useshell attribute now accepts "noshell" and "useshell" values. Boolean - values are accepted but deprecated. (Part of Redmine #2143) - - returnszero() now correctly sets the class name in this scenario (Part of - Redmine #2143): - classes: - "commandfailed" not => returnszero("/bin/nosuchcommand", "noshell"); - - Bugfixes: - - Bundles are allowed to be empty (Redmine #2411) - - Fixed '.' and '-' not being accepted by a commands module. (Redmine #2384) - - Correct parsing of list variables by a command module. (Redmine #2239) - - Fixed issue with package management and warn. (Redmine #1831) - - Fixed JSON crash. (Redmine #2151) - - Improved error checking when using fgets(). (Redmine #2451) - - Fixed error message when deleting nonexistent files. (Redmine #2448) - - Honor warn-only when purging from local directory. (Redmine #2162) - - Make sure "restart" and "reload" are recognized keywords in packages. (Redmine #2468) - - Allocate memory dynamically to avoid out-of-buffer or out-of-hash - situations - - Fix edit_xml update of existing attributes (Redmine #2034) - - Use failsafe policy from compile-time specified workdir (Redmine #1991) - - ifvarclass checked from classes promises in common bundles - - Do not wait for splaytime when executing only once - - Disable xml editing functionality when libxml2 doesn't provide necessary APIs (Redmine #1937) - - Out-of-tree builds should work again, fixed a bunch of related bugs. - - Fixed race condition in file editing. (Redmine #2545) - - Fixed memory leak in cf-serverd and others (Redmine #1758) - -3.4.5: (Bugfix and stability release) - - Bugfixes: - - Make qualified arrays expand correcty (Redmine #1998, Mantis #1128) - - Correct possible errors in tcdb files when opening - - Avoid possible db corruption when mixing read/write and cursor operations - - Allow umask value of 002 (Redmine #2496) - -3.4.4: (Bugfix and stability release) - - Bugfixes: - - Prevent possible crash when archiving files (GitHub #316) - - Don't create symlinks to cf-know in update policy - - Don't enable xml support if libxml2 is too old (Redmine #1937) - -3.4.3: (Bugfix and stability release) - - Bugfixes: - - Don't flood error messages when processes are out of defined range - - Prevent segmentation fault in cf-monitord -x (Redmine #2021) - - When copying files, use same file mode as source file, rather than 0600 (Redmine #1804) - - Include xpath in messages generated by edit_xml operations (Redmine #2057) - -3.4.2: (Bugfix and stability release) - - Bugfixes: - - Fixes to policies in masterfiles (see masterfiles/Changelog for details) - - Fixes for OpenBSD (GitHub #278) - - Do not canonify values specified in abortbundleclasses/abortclasses (Redmine #1786) - - Fix build issues on NetBSD, SLES 12.2 - - Improve error message when libxml2 support is not compiled (Redmine #1799) - - Fix potential segmentation fault when trimming network socket data (GitHub #233) - - Fix potential segmentation fault when address-lookups in lastseen db failed (GitHub #233) - - Execute background promise serially when max_children was reached, rather - than skipping them (GitHub #233) - - Fix segmentation fault in cf-promises when invoked with --reports (Redmine #1931) - - Fix compilation with Sun Studio 12 (Redmine #1901) - - Silence type-pun warning when building on HP-UX (GitHub #287) - -3.4.1: (Bugfix and stability release) - - New feature/behavior: - - cf-execd terminates agent processes that are not responsive - for a configurable amount of time (see agent_expireafter in body - executor control), defaulting to 1 week - - Bugfixes: - - Fix regression of classmatch() failing with hard classes (Redmine #1834) - - Create promise-defined and persistent classes in correct - namespace (Redmine #1836) - - Several fixes to namespace support - - Fix several crash bugs caused by buffer overflow and race - conditions in cf-serverd - - Regenerate time classes in cf-execd for each run (Redmine #1838) - - edit_xml: fix select_xpath implementation and update documentation - NOTE: code that uses select_xpath_region needs to be changed to - select_xpath - - edit_xml: make sure that text-modification functions don't overwrite - child nodes - - edit_xml: improve error logging - -3.4.0 - - New features: - - Added rpmvercmp utility to compare versions of RPM packages for - accurate sorting of RPM packages for packages promises. - - Implement network timeout on server side to avoid keeping stale - connections for hours. - - XML editing capabilities. See the documentation for edit_xml - body. Note the new dependency: libxml2. - - Implement inheritance of local classes by bundles called using - "usebundle". By default classes are not inherited. See the - examples/unit_inherit.cf for an example. - - Moved from Nova/Enterprise: - - POSIX ACL support, - - "outputs" promise type, - - remote syslog support. - - packages_default_arch_command hook in packages promises, to - specify default architecture of the packages on the system. - - packages_version_less_command / packages_version_equal_command hooks - in packages promises, to specify external command for native package - manager versions comparison - - agent_expireafter in body executor control allows you to set a - timeout on all cf-agent runs, to enforce a threshold on the - number of concurrent agents - - Running in Solaris zone is now detected and classes "zone" and - "zone_" are created in this case. - - VirtualBox support added to guest_environment promises. - - guest_environment promises are supported under OS X. - - The "depends_on" attribute is now active, for the partal ordering - of promises. If a promise depends on another (referred by handle) - it will only be considered if the depends_on list is either kept - or repaired already. - - ** WARNING: When upgrading, make sure that any existing use - of depends_on does not make some promises being - unintentionally ignored. This can happen if you are - currently referring to non-existent or never-run handles - in depends_on attributes. - - methods return values, initial implementation - - New format for cf-key -s, includes timestamp of last connection - - cf-promises --parse-tree option to parse policy file and dump it - in JSON format - - Namespaces support for bundles and bodies. See the - examples/unit_namespace*.cf for the usage. - - Default arguments for bundles. See the examples/unit_defaults.cf - - Metadata promise type. See the examples/unit_meta.cf - - New semantics: - - Methods promises now return the status of promises - kept within them. If any promise was not kept, the method is not - kept, else if any promise is repaired, the method was repaired - else it was kept. - - Remote variable access in namespaces by $(namespace:bundle.variable) - - Changed functionality: - - cf-execd -F switch no longer implies 'run once'. New -O/--once - option is added to achieve this behaviour. This makes cf-execd - easier to run from systemd, launchd and other supervision - systems. - - Misc: - - Support for the following outdated platforms and corresponding - classes has been removed. De facto those platforms were - unsupported for a long time, as CFEngine codebase uses C99 - language features unavailable on old platforms: - - - SunOS 3.x (sun3) - - SunOS 4.x (sun4) - - Ultrix (ultrix) - - DEC OSF/1 AXP (osf) - - Digital UNIX (digital) - - Sony NEWS (newsos) - - 4.3BSD (bsd4_3) - - IRIX (irix, irix4, irix64) - - IBM Academic Operating System (aos) - - BSD/OS / BSDi / BSD/386 (bsdos) - - NeXTSTEP (nextstep) - - GNU Hurd (gnu) - - NEC UX/4800 (ux4800) - - (Old news) Since 3.3.0 the layout of CFEngine Community packages - has changed slightly. - - cf-* binaries have been moved to /var/cfengine/bin, due to the - following reasons: - - cf-* binaries are linked to libraries installed to - /var/cfengine/lib, so placing binaries in /usr/local/sbin does not - increase reliability of the CFEngine, - - keeping whole CFEngine under single prefix (/var/cfengine) - makes packaging simpler, - - it matches the layout of CFEngine Enterprise packages. - - Please adjust your policies (the recommended ways to deal with - the move are either to adjust $PATH to include /var/cfengine or to - create symlinks in /usr/local/sbin in case you are relying on - binaries to be available in $PATH). - - Workdir location is properly changed if --prefix or --enable-fhs - options are supplied to configure (Mantis #1195). - - Added check for broken libmysqlclient implementations (Mantis #1217). - - Standard library is updated from COPBL repository. - - cf-know is no longer built in Community releases. The only - functionality useful in Community, namely the reference manual - generation, is provided by new compile-time cf-gendoc tool. - - Filename (for storing filechanges) changed - from file_change.log -> file_changes.log (in /var/cfengine/state) - - New format for storing file changes introduced: - [timestamp,filename,,Message] - - N = New file found - C = Content Changed - S = Stats changed - R = File removed - - Acceptance test suite passes on Mac OS X. - - Changed some port numbers to replace old services with imap(s) - - archlinux hard class on Arch Linux. - - Detect BSD Make and automatically switch to GNU Make during build. - - Bugfixes: - - cfruncommand for cf-execd is an arbitrary shell command now (Mantis #1268). - - Fixed broken "daily" splayclasses (Mantis #1307). - - Allow filenames up to 4096 bytes in network transfers (Redmine #1199). - - Fix stale state preserved during cf-serverd reload (Redmine #1487). - - Free disk space calculation is fixed (Mantis #1120). - - Numerous portability bugfixes (especially OpenBSD, Solaris, AIX-related). - - Compatibility fixes for AIX, HP-UX, Solaris (Mantis #1185, Mantis #1177, Mantis #1109). - - Fixed broken socklen_t configure check under OpenBSD (Mantis #1168). - - Fixed hang in cf-promises under OpenBSD (Mantis #1113). - - Fixed endless loop in evaluating "$()" construct (Mantis #1023). - - Fixed check for old PCRE versions (Mantis #1262). - - Fixed insertion of multi-line blocks at the start of file (Mantis #809). - - Fixed numerous memory leaks. - - Fixes for metadata that were not resolvable - - Fixes for namespaces that would not support metadata and variable expansion - - Point-to-point network interfaces are detected and reported by CFEngine (Mantis #1246) - - Partial non-GNU userspace support in acceptance testsuite (Mantis #1255) - - Full list of issues fixed is available on - https://cfengine.com/bugtracker/changelog_page.php (old bug tracker) - and https://cfengine.com/dev/projects/core/versions/34 (new bug tracker) - -3.3.9: (Bugfix and stability release) - - Bugfixes: - - Do not lose hard classes in cf-serverd during policy reload - (Mantis #1218). - - Implement receive network timeout in cf-serverd. Prevents - overloading cf-serverd with stale connections. - -3.3.8: (Bugfix and stability release) - - Versions 3.3.6, 3.3.7 were internal and weren't released. - - Bugfixes: - - Propery set sys.domain variable if hostname is fully-qualified. - - Fixed several small memory leaks. - - Make network timeout for network reads configurable. Previously - it was hardcoded to be 30 seconds, which was not enough for - cf-runagent invoking cf-agent on big policies (Mantis #1028). - -3.3.5: (Bugfix and stability release) - - Bugfixes: - - Fixed cf-execd memory leak on hosts with cf-monitord running. - - Robustify against wrongly-sized entires in embedded databases. - - Standard library: - - Bugfixes from upstream COPBL repository. - - standard_services bundle from upstream COPBL repository. - - -3.3.4: (Bugfix and stability release) - - Evaluation of policies: - - Fix wrong classes set after installation of several packages - using packages promises (Mantis #829). - - Fix segfault using edit_template on existing file (Mantis #1155). - - Misc: - - Fix memory leak during re-read of network interfaces' - information in cf-execd/cf-serverd. - -3.3.3: (Bugfix and stability release) - - Evaluation of policies: - - Zero-length files are valid for readfile() and similar functions - (Mantis #1136). - - Unchoke agent in case it encounters symlinks in form ./foo - (Similar to Mantis #1117). - - Misc: - - Fix generation of reference manual on machines with umask more - relaxed than 022. - - Use statvfs(3) on OpenBSD to obtain filesystem information - (Mantis #1135). - -3.3.2: (Bugfix and stability release) - - Evaluation of policies: - - Do not segfault if file copy was interrupted due to network - connectivity or server going away (Mantis #1089). - - Do not segfault if log_failed attribute is present in body, but - log_kept is not (Mantis #1107). - - Do not mangle relative paths in symlinks during file copy - Previously symlink a -> b was mangled to a -> ./b. - (Mantis #1117) - - Properly compare 1.0 and 1.0.1 in packages promises. Previously - only versions with equal amount of "segments" were comparable - (Mantis #890, #1066). - - Base policy: - - Properly set permissions on files for /var/cfengine/lib on HP-UX - (Mantis #1114). - - Standard library (cfengine_stdlib.cf) is synced with COPBL - repository. - - Misc: - - Do not create huge file in case corrupted TokyoCabinet database - is detected (Mantis #1106). - - Fix file descriptor leak on error paths, may have caused crashes - of cf-execd and cf-serverd (Issue #1096). - - Fix intermittent segfault in cf-execd (Mantis #1116). - - Impose an upper limit on amount of listening sockets reported by - cf-monitord. Huge amounts of listening sockets caused cf-agent to - segfault on next run (Mantis #1098). - - Add missing function prototypes caused errors during compilation - on HP-UX (Mantis #1109). - - Fix compilation on Solaris 11 (Mantis #1091). - -3.3.1: (Bugfix and stability release) - - Evaluation of policies: - - Do not cut off name of bundle in variables interpolation (Mantis #975). - - Do not segfault in function evaluation guarded by ifvaclass clause (Mantis #1084, #864). - - Do not segfault if "classes" promise does not declare any value to be evaluated (Mantis #1074). - - Do not segfault in database promises if there is no - database_operation provided (Mantis #1046). - - Built-in functions: - - Fix countclassesmatching() function which was misbehaving trying - to match classes starting with alphanumeric symbol (Mantis #1073). - - Fix diskfree() to return kilobytes, as described in documentation (Mantis #980, #955). - - Fix hostsseen() function to avoid treating all hosts as not - being seen since 1970 (Mantis #886). - - Do not output misleading error message if readtcp() is unable to connect (Mantis #1085). - - Command-line interface: - - -d option previously reqired an argument, though help message disagreed (Mantis #1053). - - Disable --parse-tree option, not ready for the release (Mantis #1063). - - Acept -h as a --help option. - - Ensure that cf-execd might be started right after being shut down. - - Misc: - - Plug file descriptor leak after failed file copy (Mantis #990). - - Fix unsafe admit rules in default promises.cf (Mantis #1040). - - Fix splaytime to match documentation: it is specified in minutes, not seconds (Mantis #1099). - - Packaging: - - Fix owner/group of initscript and profile.d snippet in RPM builds (Mantis #1061, #1058). - - Fix location of libvirt socket CFEngine uses to connect to libvirtd (Mantis #1072). - - Install CoreBase to /var/cfengine/masterfiles during installation (Mantis #1075). - - Do not leave old cf-twin around after upgrade (Mantis #1068) - - Do not leave rcS.d symlinks after purging .deb package (Mantis #1092). - -3.3.0 - - New promise types: - - Guest environments promises, which allow to manipulate virtual - machines using libvirt. - - Database promises, which allow to maintain schema of MySQL and - PostgreSQL databases. Database promises are in "technical preview" - status: this promise type is subject to change in future. - - Services promises for Unix, allows abstraction of details - on managing any service - - New built-in functions: - - dirname() to complement lastnode() - - lsdir() - - maplist() to apply functions over lists - - New features: - - Allow defining arrays from modules. - - Allow both process_stop' and signals' constraints in - processes' promises at the same time. - - cf-promises --gcc-brief-format option to output warnings and - errors in gcc-compatible syntax which to ease use "go to next - error" feature of text editors. - - Iteration over lists is now allowed for qualified (non-local) lists. - - New built-in variables and classes (Linux): - - Number of CPUs: $(sys.cpus), 1_cpu, 2_cpus etc - - New built-in variables and classes (Unices): - - $(sys.last_policy_update) - timestamp when last policy change was seen by host - - $(sys.hardware_addresses) - list of MAC adresses - - $(sys.ip_addresses) - list of IP addresses - - $(sys.interfaces) - list of network interfaces - - $(sys.hardware_mac[$iface]) - MAC address for network interface - - mac_:: - discovered MAC addresses - - Changes: - - Major cleanup of database handling code. Should radically decrease - amount of database issues experienced under heavy load. - - *WARNING*: Berkeley DB and SQLite backends are *removed*, use - Tokyo Cabinet or QDBM instead. Both Tokyo Cabinet and QDBM are - faster than Berkeley DB in typical CFEngine workloads. - - Tokyo Cabinet requires C99 environment, so it should be - available on every contemporary operating system. - - For the older systems QDBM, which relies only on C89, is a - better replacement, and deemed to be as portable, as Berkeley DB. - - Change of lastseen database schema. Should radically decrease - I/O contention on lasteen database. - - Automatic reload of policies by cf-execd. - - Documentation is generated during build, PDF and HTML files are - retired from repository. - - Rarely used feature retired: peer connectivity intermittency calculation. - - Memory and CPU usage improvements. - - Testsuite now uses 'make check' convention and does not need root - privileges anymore. - - cf_promises_validated now filled with timestamp, allows digest-copy - for policy instead of mtime copy which is safer when clocks are unsynchronised - - The bundled failsafe.cf policy now has trustkey=false to avoid IP spoofing - attacks in default policy - - See the full list of bugfixes at - https://cfengine.com/bugtracker/changelog_page.php - -3.2.4: (Bugfix and stability release) - - Fixed failure in network transfer in case of misbehaving peer - - A few tiny memory leaks on error paths fixed - -3.2.3: (Bugfix and stability release) - - A few tiny memory leaks fixed - - Improved performance of cf-serverd under heavy load with - TokyoCabinet database - - Full list of issues fixed is available on - https://cfengine.com/bugtracker/changelog_page.php - -3.2.2: (Bugfix and stability release) - - Enabled compilation in "large files" mode under AIX - - Alleviated problem with broken file transfers over unstable - internet links. - - Full list of issues fixed is available on - https://cfengine.com/bugtracker/changelog_page.php - -3.2.1: (Bugfix and stability release) - - Fixed compilation under HP-UX and Solaris - - Enabled compilation using HP ANSI C compiler - - Full list of issues fixed is available on - - https://cfengine.com/bugtracker/changelog_page.php - -3.2.0: - New bootstrap method with single-command bootstrapping: - - cf-agent --bootstrap --policy-server 123.456.789.123 - - Associated policy template files are added, partially maintained - by CFEngine - - Bug fixes for file-editing, package versioning, and embedded - database corruption (We recommend using TokyoCabinet instead of - BerkeleyDB if building from source). - - Improved upgrade path for Nova. - - Patches for improved run-agent concurrency - - Reorganization of documentation and community resources - - 100% on regression test suite on 3 operating systems - (Ubuntu, Debian, SuSE on x86-64 hardware) - - Support for multiple release environments - - package_policy update and addupdate now check if user-supplied - version is larger than currently installed - updates only if so - - Help text of cf-report -r corrected - a list of key hashes is - required, not ip addresses. - - New Emacs mode for CFEngine policy files (thanks to Ted Zlatanov!) - - Warnings are on edit_line changes can now give greater degree of information - without spamming promise logs - - Class expressions parser accepts '||' as an alias for '|' again. - - Invalidation of package list cache on installation/removal of - packages. - - New option cf-key -r to remove host key by IP or hostname. - - Added detection of network interfaces which belong to BSD jails. - - Improve robustness of multi-threaded code, in particular fix - problems with spurious access denials in server and losing of - authentication rules after policy reload. - - cf-promises accepts option -b matching cf-agent, which causes it - to do not complain about missing bundlesequence. - - New functions and(), not(), or() and concat() to ease use of - ifvarclass() clause. - - Full list of issues fixed is available on - https://cfengine.com/bugtracker/changelog_page.php - -3.1.5: - - New class parser, '||' is no longer allowed in expressions (use '|'). - - Class setting in the promise types insert_lines, delete_lines, - replace_patterns, field_edits, vars, classes is restored. - - suspiciousnames implemented. - - New function getvalues(). - - New functions parse{read,int,string}array to match read{read,int,string}array. - - Testsuite added to check for core functionality. - - Syslog prefix is fixed to say 'cf3' instead of 'community'. - -3.1.4: (Bugfix and stability release) - - Some urgent patches to 3.1.3. - - Class validation parse bug fixed. - - Global zone handling error for solaris fixed. - - Package architectures handled correctly (bug #456). - - Reading and writing of key name "root-.pub" eliminated (bug #442, #453). - - cf-serverd crash because of race condition on SERVER_KEYSEEN fixed. - - Lock purging to avoid remnant complexity explosion (bug #430). - - Some copyright notices added that got lost. - -3.1.3: (Stability release) - - Major memory leaks in cf-monitord, cf-execd, cf-serverd fixed (bug #427). - The daemons now show no growth even with very complex policies. - - cf-serverd crash due to race condition in DeleteScope() fixed (bug #406). - - Added 30 second timeout on recv() on Linux. - - package_noverify_returncode implemented (bug #256). - - A flexible mechanism for setting classes based on return codes of - commands has been introduced. Allows for setting promise kept, - repaired or failed based on any return codes. This is currently - implemented for commands-promises, package-manager commands and - transformer in files. In classes body, see attributes - kept_returncodes, repaired_returncodes, failed_returncodes (bug - #248, #329). - - New function ip2host - reverse DNS lookup (bug #146). - -3.1.2: (Scalability/efficiency release) - - Big efficiency improvements by caching output from - cf-promises. Can also be used for much more efficient policy - deployment (only pull if changed). - - Caching state of ps command for greater efficiency. Reloaded for each bundle. - - Index class lookup improves efficiency of class evaluation for huge configurations. - - Fixed issue where certain promiser strings got corrupted. - - Minor memory access issues fixed. - - Iterator bug introduced in 3.1.0 fixed - -3.1.1: (Bugfix release) - - Memory leaks in server tracked down and fixed. - - List expansion bug (one list items not executed) fixed. - - Security issue introduced by change of runcommand shell policy fixed. If users defined a runcommand for cf-runagent/cf-serverd communication, possible to execute commands. - - cf-key -s command for showing key hash/IP address identity pairs - -3.1.0: - - Change in storage of public keys. Cfengine now hashes the public key and uses this - as the keyname. Keys will be converted automatically. - - The old dynamic addresses lists are deprecated. - Caching of dns and key information for greater server speed. - Change in last-seen format reflects the public key usage. - - New package policy addupdate - installs package if not there and - updates it otherwise. - - Support for package_changes => "bulk" in file repository as well. - - New special function readstringarrayidx, similar to readstringarray, - but uses integer indices. Very useful if first row elements are - not good identifiers (e.g. contains spaces, non-unique, etc.). - - Change two log formats to use time() instead of date() - - filechanges - - total compliance - - Change from using md5 to sha256 as default digest for commercial version, - community retains md5 for compat. - - Commands not returning 0 in commands-promises are flagged - as repair_failed. - - Adjustable timeout on connect(). Defaults to 10 seconds, adjustable - with default_timeout in agent control. - - Redesign of the knowledge map infrastructure. - - Now possible to use variables to call methods, e.g - methods: - "name $(list)" usebundle => $(list)("abc"); - See reference manual notes - - Changes to normal ordering to optimize execution. - - Increased stability by always initializing Attribute and Promise - structures. - - When running cf-promises in dry-run mode (-n), the user does not need - to put binaries in WORKDIR/bin. For example, non-privileged users can verify root - policies. - - Source control revision added in version string if run in verbose mode - (e.g. "cf-promises -vV"). This needs some refining, uses revision of a header now. - - New semantics in return values of list functions. Null values are now allowed - and there is no iteration over empty lists. The value "cf_null" is reserved for - use as a null iterator. - -3.0.5p1: - - Showing paths allowed/denied access to when cf-serverd is run in verbose mode. - - Bug in server fixed for dynamic addresses. - - File handle closure bugfix - too many open databases. - - Seg fault in mount files fix. - - Twin used in cf-execd without checking. - - Check_root set wrong directory permissions at source not destination. - - Error message degraded in body definition. - - Undefined body not warned as error. - - Various build enahncements. - - Package_list_update called only once per manager, and fixed crash. - - Version number bug in packages. - -3.0.5: - - Encryption problems fixed - client key buffer was uninitialized. - - Classes-promisers are now automatically canonified when class - strings are defined, to simplifying the use of variables in classes. - - New scalars sys.cf_version and sys.nova_version that hold Cfengine version information. - - Attribute package_delete_convention added, to allow customizable - package name in delete command during update. - - package_list_update_ifelapsed limit added. - - Private variable $(firstrepo) is available in package_name_convention - and package_delete_convention in order to expand the full path to - a package, which is required by some managers. - - Some of the threading code is rewritten and made more robust. This includes - synchronizing access to the lastseen database from the server. - - Bad initialization of BSD flags fixed - - Multiple variable expansion issues in control fixed for server and agent - - Allow ignore_missing_bundles to affect methods: bundles too - - Run agent trust dialogue fixed - - Bug in CPU monitoring, increasing time scale caused linear decay - of CPU measurement. - - Bug in Setuid log storage, fix. - - Hooks added for new Nova virtualization promises. - - Multithreading mutex failed to collide during cfservd leading to dropped authentication under heavy load. - - -3.0.4: - - Class cancellation in promises to create better class feedback, - allows emulation of switch/case semantics etc - - Value of SA measurement promises - - Special function getenv() which returns the contents of an - environment variable (on all platforms). - - New function translatepath for generic Windows - - New function escape() to escape literals as regular expressions (like SQL) - - New function host2ip for caching IP address lookup - - New function regextract for setting variables with backreferences - - New variables for the components $(sys.cf_agent), $(sys.cf_know) etc - pointing to the binaries. - - More robust integrated database implementation; closing all - handles when receiving signals, self-healing on corruption. - - Package installation on localhost without a manager like yum completed, - multiple repositories searched, and universal methods. - - Numerous bugfixes - - -3.0.3: - - sha256 .. new hashes in openssl included in syntax tree. - - End of line autocropping in readfile (hopefully intelligent) - - hashmatch function incorrectly implemented - old debugging code left behind. Fix. - - sys.crontab variable - - Unknown user is now interpretated as "same user", so that we give CFEngine a chance to - fix - - Unregistered addresses no longer report "(Non registered IP)", but return as the address - itself when doing reverse lookups. - -3.0.2: - - IMPORTANT: Change in normal ordering of editing. replace comes - after insert lines Much testing and minor bug fixing - - Memory leaks fixed - - Many hooks added for Nova enterprise extensions. - - promise_output reports now placed in WORKDIR/reports directory - - Initialization correction and self-correx in monitord - - Many new body constraints added. - - Code readied for enterprise version Nova. - - -b option can override the bundlesequence (must not contain parameters yet) - - collapse_destination_dir option added to copy so that files can be - aggregated from subdirectories into a single destination. - -3.0.1: - - First standalone release, independent of CFEngine 2 - Purge old definitions and check consistency. - - NB: changed search_mode to be a list of matching values - - Reporting rationalized in cf-promises with -r only to avoid - leaving output files everywhere. - - Hooks added for upcoming commercial additions to CFEngine. - - Added classify() and hostinnetgroup() functions - - Added additional change management options for change detection - - Package management added - generic mechanisms. - - Limits on backgrounding added to avoid resource contention during CFEngine runs. - - Image type added to cf-know. - - New classes for quartly shifts: Morning,Afternoon,Evening,Night - - Bug fixes in editfiles - line insertion for multiple line objects - - Change the name of the variables and context from the monitord for - better separation of data, and shorter names. sys -> mon - average -> av, stddev -> dev - - Canonical name for windows changed from "nt" to "windows", also version names - added "vista","xp" etc.. - - License notices updated for dual license editions. - -3.0.0: - - First release of CFEngine 3. Known omissions: - - no support for ACLs - - no support for packages - - no support for interface configuration - - These will be added in the next release. diff --git a/INSTALL b/INSTALL index f58de97ab5..218a454ce7 100644 --- a/INSTALL +++ b/INSTALL @@ -135,10 +135,10 @@ LDFLAGS=-L/usr/pkg/lib CPPFLAGS=-I/usr/pkg/include ./autogen.sh --enable-debug - gmake -j8 doas /usr/pkg/bin/gmake install -* OpenBSD (7.4 2024-02-15) +* OpenBSD (7.4 2025-10-17) -pkg_add git automake-1.16.5 autoconf-2.71 bison pcre2 m4 libtool lmdb gmake -MAKE=/usr/local/bin/gmake LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include AUTOMAKE_VERSION=1.16 AUTOCONF_VERSION=2.71 ./autogen.sh --enable-debug +doas pkg_add git automake-1.17 autoconf-2.72p0 bison pcre2 m4 libtool lmdb gmake +MAKE=/usr/local/bin/gmake LDFLAGS=-L/usr/local/lib CPPFLAGS=-I/usr/local/include AUTOMAKE_VERSION=1.17 AUTOCONF_VERSION=2.72 ./autogen.sh --enable-debug gmake -j8 doas gmake install @@ -155,6 +155,8 @@ sudo zypper install gdb gcc make lmdb autoconf automake libtool git python3 pcre sudo apk add alpine-sdk lmdb-dev openssl-dev bison flex-dev acl-dev pcre2-dev autoconf automake libtool git python3 gdb ./autogen.sh --without-pam +Note that in order for process promises to work you must install the procps package for a "proper" ps command instead of busybox. + * Termux (2020-04-24) pkg install build-essential git autoconf automake bison flex liblmdb openssl pcre2 libacl libyaml diff --git a/Makefile.am b/Makefile.am index 57ef10f8e7..eaf020ee91 100644 --- a/Makefile.am +++ b/Makefile.am @@ -58,9 +58,9 @@ TAR_OPTIONS = --owner=0 --group=0 export TAR_OPTIONS -EXTRA_DIST = ChangeLog INSTALL README.md LICENSE CFVERSION +EXTRA_DIST = CHANGELOG.md INSTALL README.md LICENSE CFVERSION -doc_DATA = README.md ChangeLog +doc_DATA = README.md CHANGELOG.md # # Some basic clean ups diff --git a/cf-agent/cf-agent.c b/cf-agent/cf-agent.c index f2022aba52..d35e91af7b 100644 --- a/cf-agent/cf-agent.c +++ b/cf-agent/cf-agent.c @@ -1667,7 +1667,7 @@ static void CheckAgentAccess(const Rlist *list, const Policy *policy) for (const Rlist *rp = list; rp != NULL; rp = rp->next) { - if (Str2Uid(RlistScalarValue(rp), NULL, NULL) == uid) + if (Str2Uid(RlistScalarValue(rp), NULL, 0, NULL) == uid) { return; } @@ -1687,7 +1687,7 @@ static void CheckAgentAccess(const Rlist *list, const Policy *policy) bool access = false; for (const Rlist *rp2 = ACCESSLIST; rp2 != NULL; rp2 = rp2->next) { - if (Str2Uid(RlistScalarValue(rp2), NULL, NULL) == sb.st_uid) + if (Str2Uid(RlistScalarValue(rp2), NULL, 0, NULL) == sb.st_uid) { access = true; break; diff --git a/cf-agent/cf_sql.c b/cf-agent/cf_sql.c index aaf936ec71..23684e12cc 100644 --- a/cf-agent/cf_sql.c +++ b/cf-agent/cf_sql.c @@ -384,7 +384,7 @@ void CfCloseDB(CfdbConn *cfdb) /*****************************************************************************/ -void CfVoidQueryDB(CfdbConn *cfdb, char *query) +void CfVoidQueryDB(CfdbConn *cfdb, const char *query) { if (!cfdb->connected) { @@ -398,7 +398,7 @@ void CfVoidQueryDB(CfdbConn *cfdb, char *query) /*****************************************************************************/ -void CfNewQueryDB(CfdbConn *cfdb, char *query) +void CfNewQueryDB(CfdbConn *cfdb, const char *query) { cfdb->result = false; cfdb->row = 0; diff --git a/cf-agent/cf_sql.h b/cf-agent/cf_sql.h index fb55cd3432..fb11a4131e 100644 --- a/cf-agent/cf_sql.h +++ b/cf-agent/cf_sql.h @@ -42,8 +42,8 @@ typedef struct void CfConnectDB(CfdbConn *cfdb, DatabaseType dbtype, char *remotehost, char *dbuser, char *passwd, char *db); void CfCloseDB(CfdbConn *cfdb); -void CfVoidQueryDB(CfdbConn *cfdb, char *query); -void CfNewQueryDB(CfdbConn *cfdb, char *query); +void CfVoidQueryDB(CfdbConn *cfdb, const char *query); +void CfNewQueryDB(CfdbConn *cfdb, const char *query); char **CfFetchRow(CfdbConn *cfdb); char *CfFetchColumn(CfdbConn *cfdb, int col); void CfDeleteQuery(CfdbConn *cfdb); diff --git a/cf-agent/files_edit.c b/cf-agent/files_edit.c index 412e63b0ac..6833efc2d3 100644 --- a/cf-agent/files_edit.c +++ b/cf-agent/files_edit.c @@ -33,6 +33,7 @@ #include #include #include +#include /*****************************************************************************/ @@ -102,9 +103,9 @@ EditContext *NewEditContext(char *filename, const Attributes *a) /*****************************************************************************/ void FinishEditContext(EvalContext *ctx, EditContext *ec, const Attributes *a, const Promise *pp, - PromiseResult *result) + PromiseResult *result, bool save_file) { - if ((*result != PROMISE_RESULT_NOOP) && (*result != PROMISE_RESULT_CHANGE)) + if (!save_file || ((*result != PROMISE_RESULT_NOOP) && (*result != PROMISE_RESULT_CHANGE))) { // Failure or skipped. Don't update the file. goto end; diff --git a/cf-agent/files_edit.h b/cf-agent/files_edit.h index 0b7dd3b6f3..d869669ca4 100644 --- a/cf-agent/files_edit.h +++ b/cf-agent/files_edit.h @@ -47,17 +47,21 @@ typedef struct char *changes_filename; Item *file_start; int num_edits; + int pass; // Current convergence pass (1 to CF_DONEPASSES-1) #ifdef HAVE_LIBXML2 xmlDocPtr xmldoc; #endif NewLineMode new_line_mode; } EditContext; +// Check if we're on the final convergence pass where errors should be reported +#define EDIT_CONTEXT_IS_FINAL_PASS(ec) ((ec)->pass >= CF_DONEPASSES - 1) + // filename must not be freed until FinishEditContext. EditContext *NewEditContext(char *filename, const Attributes *a); void FinishEditContext(EvalContext *ctx, EditContext *ec, const Attributes *a, const Promise *pp, - PromiseResult *result); + PromiseResult *result, bool save_file); #ifdef HAVE_LIBXML2 bool LoadFileAsXmlDoc(xmlDocPtr *doc, const char *file, EditDefaults ed, bool only_checks); diff --git a/cf-agent/files_editline.c b/cf-agent/files_editline.c index a78fa1d62d..db52b2db15 100644 --- a/cf-agent/files_editline.c +++ b/cf-agent/files_editline.c @@ -96,6 +96,7 @@ static bool SanityCheckDeletions(const Attributes *a, const Promise *pp); static bool SelectLine(EvalContext *ctx, const char *line, const Attributes *a); static bool NotAnchored(char *s); static bool SelectRegion(EvalContext *ctx, Item *start, Item **begin_ptr, Item **end_ptr, const Attributes *a, EditContext *edcontext); +static PromiseResult HandleSelectRegionFailure(EvalContext *ctx, const Promise *pp, const Attributes *a, EditContext *edcontext, const char *operation_type); static bool MultiLineString(char *s); static bool InsertFileAtLocation(EvalContext *ctx, Item **start, Item *begin_ptr, Item *end_ptr, Item *location, Item *prev, const Attributes *a, const Promise *pp, EditContext *edcontext, PromiseResult *result); @@ -131,6 +132,7 @@ bool ScheduleEditLineOperations(EvalContext *ctx, const Bundle *bp, const Attrib for (pass = 1; pass < CF_DONEPASSES; pass++) { + edcontext->pass = pass; // Track current pass for convergence for (type = 0; EDITLINETYPESEQUENCE[type] != NULL; type++) { const BundleSection *sp = BundleGetSection(bp, EDITLINETYPESEQUENCE[type]); @@ -390,22 +392,7 @@ static PromiseResult VerifyLineDeletions(EvalContext *ctx, const Promise *pp, Ed } else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext)) { - if (a.region.include_end || a.region.include_start) - { - cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a, - "The promised line deletion '%s' could not select an edit region in '%s'" - " (this is a good thing, as policy suggests deleting the markers)", - pp->promiser, edcontext->filename); - } - else - { - cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a, - "The promised line deletion '%s' could not select an edit region in '%s'" - " (but the delimiters were expected in the file)", - pp->promiser, edcontext->filename); - } - result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); - return result; + return HandleSelectRegionFailure(ctx, pp, &a, edcontext, "line deletion"); } if (!end_ptr && a.region.select_end && !a.region.select_end_match_eof) { @@ -502,11 +489,7 @@ static PromiseResult VerifyColumnEdits(EvalContext *ctx, const Promise *pp, Edit } else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext)) { - cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a, - "The promised column edit '%s' could not select an edit region in '%s'", - pp->promiser, edcontext->filename); - result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); - return result; + return HandleSelectRegionFailure(ctx, pp, &a, edcontext, "column edit"); } /* locate and split line */ @@ -581,11 +564,7 @@ static PromiseResult VerifyPatterns(EvalContext *ctx, const Promise *pp, EditCon } else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext)) { - cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a, - "The promised pattern replace '%s' could not select an edit region in '%s'", - pp->promiser, edcontext->filename); - result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); - return result; + return HandleSelectRegionFailure(ctx, pp, &a, edcontext, "pattern replace"); } snprintf(lockname, CF_BUFSIZE - 1, "replace-%s-%s", pp->promiser, edcontext->filename); @@ -774,11 +753,7 @@ static PromiseResult VerifyLineInsertions(EvalContext *ctx, const Promise *pp, E } else if (!SelectRegion(ctx, *start, &begin_ptr, &end_ptr, &a, edcontext)) { - cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, &a, - "The promised line insertion '%s' could not select an edit region in '%s'", - pp->promiser, edcontext->filename); - result = PromiseResultUpdate(result, PROMISE_RESULT_INTERRUPTED); - return result; + return HandleSelectRegionFailure(ctx, pp, &a, edcontext, "line insertion"); } if (!end_ptr && a.region.select_end && !a.region.select_end_match_eof) @@ -894,7 +869,13 @@ If no such region matches, begin_ptr and end_ptr should point to NULL { if (!include_start) { - if (ip->next == NULL) + /* The start delimiter is the last line of the file, so the + * region (which excludes the delimiter) is empty and sits + * at end of file. Reject it only when select_end_match_eof + * is not set. Otherwise the empty region at EOF is a valid, + * selectable region so that e.g. a trailing INI section can + * still be populated (CFE-2663). */ + if (ip->next == NULL && !a->region.select_end_match_eof) { Log(LOG_LEVEL_VERBOSE, "The promised start pattern '%s' found an empty region at the end of file '%s'", @@ -939,6 +920,60 @@ If no such region matches, begin_ptr and end_ptr should point to NULL /*****************************************************************************/ +static PromiseResult HandleSelectRegionFailure(EvalContext *ctx, const Promise *pp, + const Attributes *a, EditContext *edcontext, + const char *operation_type) +/* + Common error handling for SelectRegion failures across multiple edit operations. + Returns appropriate PromiseResult based on whether we're in final pass or not. + Special handling for line deletions where missing region markers may be intended. +*/ +{ + assert(pp != NULL); + assert(a != NULL); + assert(edcontext != NULL); + assert(operation_type != NULL); + + if (!EDIT_CONTEXT_IS_FINAL_PASS(edcontext)) + { + int remaining_passes = (CF_DONEPASSES - 1) - edcontext->pass; + Log(LOG_LEVEL_VERBOSE, + "The promised %s '%s' could not select edit region in '%s' (pass %d/%d, %d more %s to try)", + operation_type, pp->promiser, edcontext->filename, + edcontext->pass, CF_DONEPASSES - 1, remaining_passes, + remaining_passes == 1 ? "pass" : "passes"); + return PROMISE_RESULT_NOOP; // Allow retry in next pass + } + + // Special case for line deletions: missing markers might be intentional + if (StringEqual(operation_type, "line deletion")) + { + if (a->region.include_end || a->region.include_start) + { + cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, + "The promised %s '%s' could not select an edit region in '%s' after %d passes" + " (this is a good thing, as policy suggests deleting the markers)", + operation_type, pp->promiser, edcontext->filename, CF_DONEPASSES - 1); + } + else + { + cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, + "The promised %s '%s' could not select an edit region in '%s' after %d passes" + " (but the delimiters were expected in the file)", + operation_type, pp->promiser, edcontext->filename, CF_DONEPASSES - 1); + } + return PROMISE_RESULT_INTERRUPTED; + } + + // Standard error for final pass + cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_INTERRUPTED, pp, a, + "The promised %s '%s' could not select an edit region in '%s' after %d passes", + operation_type, pp->promiser, edcontext->filename, CF_DONEPASSES - 1); + return PROMISE_RESULT_INTERRUPTED; +} + +/*****************************************************************************/ + static int MatchRegion(EvalContext *ctx, const char *chunk, const Item *begin, const Item *end, bool regex) /* Match a region in between the selection delimiters. It is @@ -1715,11 +1750,11 @@ static bool MatchPolicy(EvalContext *ctx, const char *camel, const char *haystac char *work = xcalloc(1, work_size); strcpy(work, sp); - int written = snprintf(final, final_size, "\\s*%s", + int written = snprintf(final, final_size, "\\s*%s", work); if (written < 0) { - Log(LOG_LEVEL_ERR, + Log(LOG_LEVEL_ERR, "Unexpected failure from snprintf " "(%d - %s) on '%s' (MatchPolicy)", errno, GetErrorStr(), final); @@ -1729,13 +1764,13 @@ static bool MatchPolicy(EvalContext *ctx, const char *camel, const char *haystac { final = xrealloc(final, work_size); final_size = work_size; - written = snprintf(final, final_size, "\\s*%s", + written = snprintf(final, final_size, "\\s*%s", work); if (written < 0) { - Log(LOG_LEVEL_ERR, + Log(LOG_LEVEL_ERR, "Unexpected failure from snprintf " - "(%d - %s) on '%s' (MatchPolicy)", + "(%d - %s) on '%s' (MatchPolicy)", errno, GetErrorStr(), final); return false; } @@ -1746,7 +1781,7 @@ static bool MatchPolicy(EvalContext *ctx, const char *camel, const char *haystac } else if (opt == INSERT_MATCH_TYPE_IGNORE_TRAILING) { - if (!StringEqualN(final + final_size - 5, "\\s*", 3)) + if (final_size >= 5 && !StringEqualN(final + final_size - 5, "\\s*", 3)) { const size_t work_size = final_size + 3; char *work = xcalloc(1, work_size); @@ -1758,9 +1793,9 @@ static bool MatchPolicy(EvalContext *ctx, const char *camel, const char *haystac int written = snprintf(final, final_size, "%s\\s*", work); if (written < 0) { - Log(LOG_LEVEL_ERR, + Log(LOG_LEVEL_ERR, "Unexpected failure from snprintf " - "(%d - %s) on '%s' (MatchPolicy)", + "(%d - %s) on '%s' (MatchPolicy)", errno, GetErrorStr(), final); return false; } @@ -1771,9 +1806,9 @@ static bool MatchPolicy(EvalContext *ctx, const char *camel, const char *haystac written = snprintf(final, final_size, "%s\\s*", work); if (written < 0) { - Log(LOG_LEVEL_ERR, + Log(LOG_LEVEL_ERR, "Unexpected failure from snprintf " - "(%d - %s) on '%s' (MatchPolicy)", + "(%d - %s) on '%s' (MatchPolicy)", errno, GetErrorStr(), final); return false; } diff --git a/cf-agent/files_editxml.c b/cf-agent/files_editxml.c index 781dfb5eb0..0bc01b5b8a 100644 --- a/cf-agent/files_editxml.c +++ b/cf-agent/files_editxml.c @@ -29,6 +29,8 @@ #include #include #include +#include +#include #include #include #include @@ -42,6 +44,7 @@ #include #include #include /* StringMatch() */ +#include enum editxmltypesequence { @@ -344,6 +347,7 @@ static PromiseResult KeepEditXmlPromise(EvalContext *ctx, const Promise *pp, static bool VerifyXPathBuild(EvalContext *ctx, const Attributes *attr, const Promise *pp, EditContext *edcontext, PromiseResult *result) { assert(attr != NULL); + assert(pp != NULL); Attributes a = *attr; // TODO: Remove this copy xmlDocPtr doc = NULL; CfLock thislock; @@ -351,13 +355,14 @@ static bool VerifyXPathBuild(EvalContext *ctx, const Attributes *attr, const Pro a.transaction.ifelapsed = CF_EDIT_IFELAPSED; - if (a.xml.havebuildxpath) - { - strcpy(rawxpath, a.xml.build_xpath); - } - else - { - strcpy(rawxpath, pp->promiser); + int ret = snprintf(rawxpath, sizeof(rawxpath), "%s", + a.xml.havebuildxpath ? a.xml.build_xpath : pp->promiser); + if (ret < 0 ||(size_t)ret >= sizeof(rawxpath)) { + Log(LOG_LEVEL_VERBOSE, "Build XPath is too long (%d >= %zu)", ret, sizeof(rawxpath)); + RecordFailure(ctx, pp, &a, + "The promised build XPath build is too long"); + *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL); + return false; } if (!SanityCheckXPathBuild(ctx, &a, pp, result)) diff --git a/cf-agent/nfs.c b/cf-agent/nfs.c index fd5c5aafa7..4ba7d095c7 100644 --- a/cf-agent/nfs.c +++ b/cf-agent/nfs.c @@ -468,29 +468,62 @@ int VerifyInFstab(EvalContext *ctx, char *name, const Attributes *a, const Promi mountpt = name; fstype = a->mount.mount_type; + char device[CF_BUFSIZE]; + if (StringEqual(fstype, "cifs") || StringEqual(fstype, "panfs")) + { + NDEBUG_UNUSED int ret = snprintf(device, sizeof(device), "%s%s", host, rmountpt); + assert(ret >= 0 && ret < CF_BUFSIZE); + } + else + { + NDEBUG_UNUSED int ret = snprintf(device, sizeof(device), "%s:%s", host, rmountpt); + assert(ret >= 0 && ret < CF_BUFSIZE); + } + #if defined(__QNX__) || defined(__QNXNTO__) - snprintf(fstab, CF_BUFSIZE, "%s:%s \t %s %s\t%s 0 0", host, rmountpt, mountpt, fstype, opts); + // QNX documents 4 fstab fields : https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.utilities/topic/f/fstab.html + // specialdevice mountpoint type mountoptions + // TODO Remove DUMP and PASS options used here (unsupported)? + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s \t %s %s\t%s 0 0", device, mountpt, fstype, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(_CRAY) char fstype_upper[CF_BUFSIZE]; strlcpy(fstype_upper, fstype, CF_BUFSIZE); ToUpperStrInplace(fstype_upper); - snprintf(fstab, CF_BUFSIZE, "%s:%s \t %s %s\t%s", host, rmountpt, mountpt, fstype_upper, opts); + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s \t %s %s\t%s", device, mountpt, fstype_upper, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); break; #elif defined(__hpux) - snprintf(fstab, CF_BUFSIZE, "%s:%s %s \t %s \t %s 0 0", host, rmountpt, mountpt, fstype, opts); + // HP-UX documents 7 fstab fields: https://nixdoc.net/man-pages/HP-UX/man4/fstab.4.html + // deviceSpecialFile directory type options backupFrequency passNumber comment + // TODO Bring promise comment in as the 7th comment field # promise comment (stripped of newlines) + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s %s \t %s \t %s 0 0", device, mountpt, fstype, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(_AIX) - snprintf(fstab, CF_BUFSIZE, - "%s:\n\tdev\t= %s\n\ttype\t= %s\n\tvfs\t= %s\n\tnodename\t= %s\n\tmount\t= true\n\toptions\t= %s\n\taccount\t= false\n", - mountpt, rmountpt, fstype, fstype, host, opts); + // AIX uses /etc/filesystems: https://www.ibm.com/docs/en/aix/7.2.0?topic=files-filesystems-file + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, + "%s:\n\tdev\t= %s\n\ttype\t= %s\n\tvfs\t= %s\n\tnodename\t= %s\n\tmount\t= true\n\toptions\t= %s\n\taccount\t= false\n", + mountpt, rmountpt, fstype, fstype, host, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(__linux__) - snprintf(fstab, CF_BUFSIZE, "%s:%s \t %s \t %s \t %s", host, rmountpt, mountpt, fstype, opts); + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s \t %s \t %s \t %s", device, mountpt, fstype, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__APPLE__) - snprintf(fstab, CF_BUFSIZE, "%s:%s \t %s \t %s \t %s 0 0", host, rmountpt, mountpt, fstype, opts); + // BSDs document 6 fstab fields https://man.freebsd.org/cgi/man.cgi?fstab(5) + // Device Mountpoint FStype Options Dump Pass + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s \t %s \t %s \t %s 0 0", device, mountpt, fstype, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(__sun) || defined(sco) || defined(__SCO_DS) - snprintf(fstab, CF_BUFSIZE, "%s:%s - %s %s - yes %s", host, rmountpt, mountpt, fstype, opts); + // SunOS uses /etc/fstab and documents 7 fields: https://docs.oracle.com/cd/E19455-01/805-6331/fsadm-59727/index.html + // deviceToMount deviceToFsck mountPoint FStype fsckPass automount? mountOptions + // - is used for deviceToFsck for read-only and network based file systems + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "%s - %s %s - yes %s", device, mountpt, fstype, opts); + assert(ret >= 0 && ret < CF_BUFSIZE); #elif defined(__CYGWIN__) - snprintf(fstab, CF_BUFSIZE, "/bin/mount %s:%s %s", host, rmountpt, mountpt); + // https://cygwin.com/cygwin-ug-net/using.html#mount-table + NDEBUG_UNUSED int ret = snprintf(fstab, CF_BUFSIZE, "/bin/mount %s %s", device, mountpt); + assert(ret >= 0 && ret < CF_BUFSIZE); #else #error "Could not determine format of fstab entry on this platform." #endif @@ -503,7 +536,7 @@ int VerifyInFstab(EvalContext *ctx, char *name, const Attributes *a, const Promi { AppendItem(&FSTABLIST, fstab, NULL); FSTAB_EDITS++; - cfPS(ctx, LOG_LEVEL_INFO, PROMISE_RESULT_CHANGE, pp, a, "Adding file system '%s:%s' to '%s'", host, rmountpt, + cfPS(ctx, LOG_LEVEL_INFO, PROMISE_RESULT_CHANGE, pp, a, "Adding file system entry '%s' to '%s'", fstab, VFSTAB[VSYSTEMHARDCLASS]); *result = PromiseResultUpdate(*result, PROMISE_RESULT_CHANGE); changes += 1; diff --git a/cf-agent/retcode.c b/cf-agent/retcode.c index cc45786e5e..0630a06fc0 100644 --- a/cf-agent/retcode.c +++ b/cf-agent/retcode.c @@ -86,7 +86,7 @@ bool VerifyCommandRetcode(EvalContext *ctx, int retcode, const Attributes *a, co if (!matched) { - cfPS(ctx, info_or_verbose, PROMISE_RESULT_FAIL, pp, a, + cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, a, "Command related to promiser '%s' returned code '%d' not defined as promise kept, not kept or repaired; setting to failed", pp->promiser, retcode); *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL); diff --git a/cf-agent/verify_databases.c b/cf-agent/verify_databases.c index 1b99e1ad20..5c93e15919 100644 --- a/cf-agent/verify_databases.c +++ b/cf-agent/verify_databases.c @@ -743,48 +743,50 @@ static int TableExists(CfdbConn *cfdb, char *name) static bool CreateTableColumns(CfdbConn *cfdb, char *table, Rlist *columns) { - char entry[CF_MAXVARSIZE], query[CF_BUFSIZE]; int i, *size_table, *done; char **name_table, **type_table; int no_of_cols = RlistLen(columns); - Log(LOG_LEVEL_ERR, "Trying to create table '%s'", table); + Log(LOG_LEVEL_VERBOSE, "Trying to create table '%s'", table); if (!NewSQLColumns(table, columns, &name_table, &type_table, &size_table, &done)) { return false; } - if (no_of_cols > 0) + if (no_of_cols <= 0) { - snprintf(query, CF_BUFSIZE - 1, "create table %s(", table); - - for (i = 0; i < no_of_cols; i++) - { - Log(LOG_LEVEL_VERBOSE, "Forming column template %s %s %d", name_table[i], type_table[i], - size_table[i]);; + Log(LOG_LEVEL_ERR, "Attempted to create table '%s' without any columns", table); + return false; + } - if (size_table[i] > 0) - { - snprintf(entry, CF_MAXVARSIZE - 1, "%s %s(%d)", name_table[i], type_table[i], size_table[i]); - } - else - { - snprintf(entry, CF_MAXVARSIZE - 1, "%s %s", name_table[i], type_table[i]); - } + Buffer *query = BufferNew(); + BufferPrintf(query, "create table %s(", table); - strcat(query, entry); + for (i = 0; i < no_of_cols; i++) + { + Log(LOG_LEVEL_VERBOSE, "Forming column template %s %s %d", name_table[i], type_table[i], + size_table[i]);; - if (i < no_of_cols - 1) - { - strcat(query, ","); - } + if (size_table[i] > 0) + { + BufferAppendF(query, "%s %s(%d)", name_table[i], type_table[i], size_table[i]); + } + else + { + BufferAppendF(query, "%s %s", name_table[i], type_table[i]); } - strcat(query, ")"); + if (i < no_of_cols - 1) + { + BufferAppendChar(query, ','); + } } - CfVoidQueryDB(cfdb, query); + BufferAppendChar(query, ')'); + + CfVoidQueryDB(cfdb, BufferData(query)); + BufferDestroy(query); DeleteSQLColumns(name_table, type_table, size_table, done, no_of_cols); return true; } diff --git a/cf-agent/verify_files.c b/cf-agent/verify_files.c index bc65c046a0..b963b45950 100644 --- a/cf-agent/verify_files.c +++ b/cf-agent/verify_files.c @@ -59,6 +59,10 @@ #include #include #include /* PrepareChangesChroot(), RecordFileChangedInChroot() */ +#include +#include +#include +#include static PromiseResult FindFilePromiserObjects(EvalContext *ctx, const Promise *pp); static PromiseResult VerifyFilePromise(EvalContext *ctx, char *path, const Promise *pp); @@ -530,6 +534,20 @@ static PromiseResult VerifyFilePromise(EvalContext *ctx, char *path, const Promi result = PromiseResultUpdate(result, ScheduleLinkOperation(ctx, path, a.link.source, &a, pp)); } + if (a.haveedit || a.content || a.edit_template_string) + { + if (exists || link) + { + if (!HandleFileObstruction(ctx, changes_path, &oslb, &a, pp, &result)) + { + goto exit; + } + // After moving, it no longer exists at the original path + exists = (lstat(changes_path, &oslb) != -1); + link = false; + } + } + /* Phase 3a - direct content */ if (a.content) @@ -562,8 +580,6 @@ static PromiseResult VerifyFilePromise(EvalContext *ctx, char *path, const Promi PromiseResult render_result = WriteContentFromString(ctx, path, &a, pp); result = PromiseResultUpdate(result, render_result); - - goto exit; } /* Phase 3b - content editing */ @@ -735,7 +751,8 @@ static PromiseResult RenderTemplateCFEngine(EvalContext *ctx, const Rlist *bundle_args, const Attributes *attr, EditContext *edcontext, - bool file_exists) + bool file_exists, + bool *save_file) { assert(edcontext != NULL); assert(attr != NULL); @@ -748,7 +765,7 @@ static PromiseResult RenderTemplateCFEngine(EvalContext *ctx, { if (!file_exists && !CfCreateFile(ctx, edcontext->changes_filename, pp, attr, &result)) - { + { RecordFailure(ctx, pp, attr, "Failed to create file '%s' for rendering cfengine template '%s'", edcontext->filename, attr->edit_template); @@ -760,7 +777,7 @@ static PromiseResult RenderTemplateCFEngine(EvalContext *ctx, EvalContextStackPushBundleFrame(ctx, bp, bundle_args, a.edits.inherit); BundleResolve(ctx, bp); - ScheduleEditLineOperations(ctx, bp, &a, pp, edcontext); + *save_file = ScheduleEditLineOperations(ctx, bp, &a, pp, edcontext); EvalContextStackPopFrame(ctx); @@ -860,7 +877,7 @@ static PromiseResult RenderTemplateMustache(EvalContext *ctx, if (!file_exists && !CfCreateFile(ctx, edcontext->changes_filename, pp, attr, &result)) - { + { RecordFailure(ctx, pp, attr, "Failed to create file '%s' for rendering mustache template '%s'", edcontext->filename, message); @@ -971,6 +988,7 @@ PromiseResult ScheduleEditOperation(EvalContext *ctx, char *filename, Rlist *args = NULL; char edit_bundle_name[CF_BUFSIZE], lockname[CF_BUFSIZE]; CfLock thislock; + bool save_file = true; snprintf(lockname, CF_BUFSIZE - 1, "fileedit-%s", filename); thislock = AcquireLock(ctx, lockname, VUQNAME, CFSTARTTIME, a->transaction.ifelapsed, a->transaction.expireafter, pp, false); @@ -998,12 +1016,28 @@ PromiseResult ScheduleEditOperation(EvalContext *ctx, char *filename, if ((vp = PromiseGetConstraintAsRval(pp, "edit_line", RVAL_TYPE_FNCALL))) { fp = (FnCall *) vp; - strcpy(edit_bundle_name, fp->name); + size_t ret = strlcpy(edit_bundle_name, fp->name, sizeof(edit_bundle_name)); + if (ret >= sizeof(edit_bundle_name)) + { + RecordFailure(ctx, pp, a, + "The edit_line bundle name is too long (%zu >= %zu)", + ret, sizeof(edit_bundle_name)); + result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); + goto exit; + } args = fp->args; } else if ((vp = PromiseGetConstraintAsRval(pp, "edit_line", RVAL_TYPE_SCALAR))) { - strcpy(edit_bundle_name, (char *) vp); + size_t ret = strlcpy(edit_bundle_name, (char *) vp, sizeof(edit_bundle_name)); + if (ret >= sizeof(edit_bundle_name)) + { + RecordFailure(ctx, pp, a, + "The edit_line bundle name is too long (%zu >= %zu)", + ret, sizeof(edit_bundle_name)); + result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); + goto exit; + } args = NULL; } else @@ -1036,12 +1070,28 @@ PromiseResult ScheduleEditOperation(EvalContext *ctx, char *filename, if ((vp = PromiseGetConstraintAsRval(pp, "edit_xml", RVAL_TYPE_FNCALL))) { fp = (FnCall *) vp; - strcpy(edit_bundle_name, fp->name); + size_t ret = strlcpy(edit_bundle_name, fp->name, sizeof(edit_bundle_name)); + if (ret >= sizeof(edit_bundle_name)) + { + RecordFailure(ctx, pp, a, + "The edit_xml bundle name is too long (%zu >= %zu)", + ret, sizeof(edit_bundle_name)); + result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); + goto exit; + } args = fp->args; } else if ((vp = PromiseGetConstraintAsRval(pp, "edit_xml", RVAL_TYPE_SCALAR))) { - strcpy(edit_bundle_name, (char *) vp); + size_t ret = strlcpy(edit_bundle_name, (char *) vp, sizeof(edit_bundle_name)); + if (ret >= sizeof(edit_bundle_name)) + { + RecordFailure(ctx, pp, a, + "The edit_xml bundle name is too long (%zu >= %zu)", + ret, sizeof(edit_bundle_name)); + result = PromiseResultUpdate(result, PROMISE_RESULT_FAIL); + goto exit; + } args = NULL; } else @@ -1073,7 +1123,8 @@ PromiseResult ScheduleEditOperation(EvalContext *ctx, char *filename, PromiseResult render_result = RenderTemplateCFEngine(ctx, pp, args, a, edcontext, - file_exists); + file_exists, + &save_file); result = PromiseResultUpdate(result, render_result); } } @@ -1105,7 +1156,7 @@ PromiseResult ScheduleEditOperation(EvalContext *ctx, char *filename, } exit: - FinishEditContext(ctx, edcontext, a, pp, &result); + FinishEditContext(ctx, edcontext, a, pp, &result, save_file); YieldCurrentLock(thislock); if (result == PROMISE_RESULT_CHANGE) { diff --git a/cf-agent/verify_files_utils.c b/cf-agent/verify_files_utils.c index db18da5091..6b819922a6 100644 --- a/cf-agent/verify_files_utils.c +++ b/cf-agent/verify_files_utils.c @@ -22,6 +22,9 @@ included file COSL.txt. */ +#include +#include +#include #include #include @@ -69,6 +72,7 @@ #include /* GetGroupName(), GetUserName() */ #include +#include "cf3.defs.h" #define CF_RECURSION_LIMIT 100 @@ -1551,8 +1555,32 @@ bool CopyRegularFile(EvalContext *ctx, const char *source, const char *dest, con return false; } + /* Use perms from source file if preserve is true, otherwise use perms + * of destination file if it exists, otherwise use default perms. */ + mode_t mode; + if (attr->copy.preserve) + { + mode = sstat->st_mode; + } + else if (dest_exists) + { + mode = dest_stat.st_mode; + } + else + { + mode = CF_PERMS_DEFAULT; + } + mode &= 0777; /* Never preserve SUID bit */ + + /* If perms are promised for this file, use those instead */ + if ((attr->perms.plus != CF_SAMEMODE) && (attr->perms.minus != CF_SAMEMODE)) + { + mode |= attr->perms.plus; + mode &= ~(attr->perms.minus); + } + if (!CopyRegularFileNet(source, ToChangesPath(new), - sstat->st_size, attr->copy.encrypt, conn)) + sstat->st_size, attr->copy.encrypt, conn, mode)) { RecordFailure(ctx, pp, attr, "Failed to copy file '%s' from '%s'", source, conn->remoteip); @@ -1712,7 +1740,7 @@ bool CopyRegularFile(EvalContext *ctx, const char *source, const char *dest, con } } - if (rename(dest, changes_backup) == 0) + if (CopyRegularFileDisk(dest, changes_backup)) { RecordChange(ctx, pp, attr, "Backed up '%s' as '%s'", dest, backup); *result = PromiseResultUpdate(*result, PROMISE_RESULT_CHANGE); @@ -2739,6 +2767,57 @@ static PromiseResult VerifyFileAttributes(EvalContext *ctx, const char *file, co return result; } +bool HandleFileObstruction(EvalContext *ctx, const char *path, const struct stat *sb, const Attributes *attr, const Promise *pp, PromiseResult *result) +{ + // Tell static analysis tools that these pointers do not need to be checked for NULL before dereferencing + assert(sb != NULL); + assert(attr != NULL); + + const mode_t st_mode = sb->st_mode; + const bool move_obstructions = attr->move_obstructions; + + // If path exists, but is not a regular file, it's an obstruction + if (!S_ISREG(st_mode)) + { + if (move_obstructions) + { + if (MakingChanges(ctx, pp, attr, result, "Moving obstructing file '%s'", path)) + { + char backup[CF_BUFSIZE]; + int ret = snprintf(backup, sizeof(backup), "%s.cf-moved", path); + if (ret < 0 || (size_t) ret >= sizeof(backup)) + { + RecordFailure(ctx, pp, attr, "Could not move obstruction '%s': Path too long", + path); + *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL); + return false; + } + + if (rename(path, backup) == -1) + { + RecordFailure(ctx, pp, attr, "Could not move obstruction '%s' to '%s'. (rename: %s)", + path, backup, GetErrorStr()); + *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL); + return false; + } + else + { + RecordChange(ctx, pp, attr, "Moved obstructing path '%s' to '%s'", path, backup); + *result = PromiseResultUpdate(*result, PROMISE_RESULT_CHANGE); + return true; + } + } + } + else if (!S_ISLNK(st_mode)) + { + RecordFailure(ctx, pp, attr, "Path '%s' is not a regular file and move_obstructions is not set", path); + *result = PromiseResultUpdate(*result, PROMISE_RESULT_FAIL); + return false; + } + } + return true; +} + bool DepthSearch(EvalContext *ctx, char *name, const struct stat *sb, int rlevel, const Attributes *attr, const Promise *pp, dev_t rootdevice, PromiseResult *result) { diff --git a/cf-agent/verify_files_utils.h b/cf-agent/verify_files_utils.h index 30a573531d..9f1c863d6b 100644 --- a/cf-agent/verify_files_utils.h +++ b/cf-agent/verify_files_utils.h @@ -35,6 +35,7 @@ extern StringSet *SINGLE_COPY_CACHE; void SetFileAutoDefineList(const Rlist *auto_define_list); void VerifyFileLeaf(EvalContext *ctx, char *path, const struct stat *sb, const Attributes *attr, const Promise *pp, PromiseResult *result); +bool HandleFileObstruction(EvalContext *ctx, const char *path, const struct stat *sb, const Attributes *attr, const Promise *pp, PromiseResult *result); bool DepthSearch(EvalContext *ctx, char *name, const struct stat *sb, int rlevel, const Attributes *attr, const Promise *pp, dev_t rootdevice, PromiseResult *result); bool CfCreateFile(EvalContext *ctx, char *file, const Promise *pp, const Attributes *attr, PromiseResult *result_out); void SetSearchDevice(struct stat *sb, const Promise *pp); diff --git a/cf-agent/verify_packages.c b/cf-agent/verify_packages.c index a98a24e370..97df9d0eae 100644 --- a/cf-agent/verify_packages.c +++ b/cf-agent/verify_packages.c @@ -54,6 +54,7 @@ #include #include #include +#include /* Called structure: @@ -115,7 +116,7 @@ static PromiseResult VerifyPromisedPatch(EvalContext *ctx, const Attributes *a, static char *GetDefaultArch(const char *command); -static bool ExecPackageCommand(EvalContext *ctx, char *command, int verify, int setCmdClasses, const Attributes *a, const Promise *pp, PromiseResult *result); +static bool ExecPackageCommand(EvalContext *ctx, const char *command, int verify, int setCmdClasses, const Attributes *a, const Promise *pp, PromiseResult *result); static bool PrependPatchItem(EvalContext *ctx, PackageItem ** list, char *item, PackageItem * chklist, const char *default_arch, const Attributes *a, const Promise *pp); static bool PrependMultiLinePackageItem(EvalContext *ctx, PackageItem ** list, char *item, int reset, const char *default_arch, const Attributes *a, const Promise *pp); @@ -2578,35 +2579,9 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa continue; } - size_t estimated_size = 0; - - for (const PackageItem *pi = pm->pack_list; pi != NULL; pi = pi->next) - { - size_t size = strlen(pi->name) + strlen(" "); - - switch (pm->policy) - { - case PACKAGE_ACTION_POLICY_INDIVIDUAL: - - if (size > estimated_size) - { - estimated_size = size + CF_MAXVARSIZE; - } - break; - - case PACKAGE_ACTION_POLICY_BULK: - - estimated_size += size + CF_MAXVARSIZE; - break; - - default: - break; - } - } - const Promise *const pp = pm->pack_list->pp; Attributes a = GetPackageAttributes(ctx, pp); - char *command_string = NULL; + Buffer *command_buffer = BufferNew(); switch (action) { @@ -2617,14 +2592,12 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa if (a.packages.package_add_command == NULL) { ProgrammingError("Package add command undefined"); + BufferDestroy(command_buffer); return false; } Log(LOG_LEVEL_INFO, "Installing %-.39s...", pp->promiser); - - estimated_size += strlen(a.packages.package_add_command) + 2; - command_string = xmalloc(estimated_size); - strcpy(command_string, a.packages.package_add_command); + BufferAppendString(command_buffer, a.packages.package_add_command); break; case PACKAGE_ACTION_DELETE: @@ -2634,14 +2607,12 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa if (a.packages.package_delete_command == NULL) { ProgrammingError("Package delete command undefined"); + BufferDestroy(command_buffer); return false; } Log(LOG_LEVEL_INFO, "Deleting %-.39s...", pp->promiser); - - estimated_size += strlen(a.packages.package_delete_command) + 2; - command_string = xmalloc(estimated_size); - strcpy(command_string, a.packages.package_delete_command); + BufferAppendString(command_buffer, a.packages.package_delete_command); break; case PACKAGE_ACTION_UPDATE: @@ -2651,14 +2622,12 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa if (a.packages.package_update_command == NULL) { ProgrammingError("Package update command undefined"); + BufferDestroy(command_buffer); return false; } Log(LOG_LEVEL_INFO, "Updating %-.39s...", pp->promiser); - - estimated_size += strlen(a.packages.package_update_command) + 2; - command_string = xcalloc(1, estimated_size); - strcpy(command_string, a.packages.package_update_command); + BufferAppendString(command_buffer, a.packages.package_update_command); break; case PACKAGE_ACTION_VERIFY: @@ -2668,33 +2637,32 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa if (a.packages.package_verify_command == NULL) { ProgrammingError("Package verify command undefined"); + BufferDestroy(command_buffer); return false; } - estimated_size += strlen(a.packages.package_verify_command) + 2; - command_string = xmalloc(estimated_size); - strcpy(command_string, a.packages.package_verify_command); + BufferAppendString(command_buffer, a.packages.package_verify_command); verify = true; break; default: ProgrammingError("Unknown action attempted"); + BufferDestroy(command_buffer); return false; } /* if the command ends with $ then we assume the package manager does not accept package names */ - - if (*(command_string + strlen(command_string) - 1) == '$') + if (BufferData(command_buffer)[BufferSize(command_buffer) - 1] == '$') { - *(command_string + strlen(command_string) - 1) = '\0'; + BufferTrimToMaxLength(command_buffer, BufferSize(command_buffer) - 1); Log(LOG_LEVEL_VERBOSE, "Command does not allow arguments"); PromiseResult result = PROMISE_RESULT_NOOP; EvalContextStackPushPromiseFrame(ctx, pp); if (EvalContextStackPushPromiseIterationFrame(ctx, NULL)) { - if (ExecPackageCommand(ctx, command_string, verify, true, &a, pp, &result)) + if (ExecPackageCommand(ctx, BufferData(command_buffer), verify, true, &a, pp, &result)) { Log(LOG_LEVEL_VERBOSE, "Package schedule execution ok (outcome cannot be promised by cf-agent)"); } @@ -2711,9 +2679,9 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa } else { - strcat(command_string, " "); + BufferAppendChar(command_buffer, ' '); - Log(LOG_LEVEL_VERBOSE, "Command prefix '%s'", command_string); + Log(LOG_LEVEL_VERBOSE, "Command prefix '%s'", BufferData(command_buffer)); if (pm->policy == PACKAGE_ACTION_POLICY_INDIVIDUAL) { @@ -2723,15 +2691,14 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa const Promise *const ppi = pi->pp; Attributes a = GetPackageAttributes(ctx, ppi); - const size_t command_len = strlen(command_string); - char *offset = command_string + command_len; + const size_t offset = BufferSize(command_buffer); if ((a.packages.package_file_repositories) && ((action == PACKAGE_ACTION_ADD) || (action == PACKAGE_ACTION_UPDATE))) { const char *sp = PrefixLocalRepository(a.packages.package_file_repositories, pi->name); if (sp != NULL) { - strlcat(offset, sp, estimated_size - command_len); + BufferAppendString(command_buffer, sp); } else { @@ -2740,14 +2707,26 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa } else { - strcat(offset, pi->name); + if (a.packages.package_commands_useshell) + { + /* Put single quotes around package name and escape + * any pre-existing single quotes to prevent shell + * injection. */ + char *escaped = EscapeCharCopy(pi->name, '\'', '\\'); + BufferAppendF(command_buffer, "'%s'", escaped); + free(escaped); + } + else + { + BufferAppendString(command_buffer, pi->name); + } } PromiseResult result = PROMISE_RESULT_NOOP; EvalContextStackPushPromiseFrame(ctx, ppi); if (EvalContextStackPushPromiseIterationFrame(ctx, NULL)) { - bool ok = ExecPackageCommand(ctx, command_string, verify, true, &a, ppi, &result); + bool ok = ExecPackageCommand(ctx, BufferData(command_buffer), verify, true, &a, ppi, &result); if (StringEqual(pi->name, PACKAGE_IGNORED_CFE_INTERNAL)) { @@ -2770,7 +2749,7 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa EvalContextLogPromiseIterationOutcome(ctx, ppi, result); - *offset = '\0'; + BufferTrimToMaxLength(command_buffer, offset); } } else if (pm->policy == PACKAGE_ACTION_POLICY_BULK) @@ -2779,9 +2758,6 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa { if (pi->name) { - const size_t command_len = strlen(command_string); - char *offset = command_string + command_len; - if (a.packages.package_file_repositories && (action == PACKAGE_ACTION_ADD || action == PACKAGE_ACTION_UPDATE)) @@ -2789,7 +2765,7 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa const char *sp = PrefixLocalRepository(a.packages.package_file_repositories, pi->name); if (sp != NULL) { - strlcpy(offset, sp, estimated_size - command_len); + BufferAppendString(command_buffer, sp); } else { @@ -2798,10 +2774,21 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa } else { - strcpy(offset, pi->name); + if (a.packages.package_commands_useshell) + { + /* Put single quotes around package name and escape + * any pre-existing single quotes to prevent shell + * injection. */ + char *escaped = EscapeCharCopy(pi->name, '\'', '\\'); + BufferAppendF(command_buffer, "'%s'", escaped); + free(escaped); + } + else + { + BufferAppendString(command_buffer, pi->name); + } } - - strcat(command_string, " "); + BufferAppendChar(command_buffer, ' '); } } @@ -2809,7 +2796,7 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa EvalContextStackPushPromiseFrame(ctx, pp); if (EvalContextStackPushPromiseIterationFrame(ctx, NULL)) { - bool ok = ExecPackageCommand(ctx, command_string, verify, true, &a, pp, &result); + bool ok = ExecPackageCommand(ctx, BufferData(command_buffer), verify, true, &a, pp, &result); for (const PackageItem *pi = pm->pack_list; pi != NULL; pi = pi->next) { @@ -2837,10 +2824,7 @@ static bool ExecuteSchedule(EvalContext *ctx, const PackageManager *schedule, Pa } } - if (command_string) - { - free(command_string); - } + BufferDestroy(command_buffer); } /* We have performed some modification operation on packages, our cache is invalid */ @@ -3245,14 +3229,14 @@ const char *PrefixLocalRepository(const Rlist *repositories, const char *package return NULL; } -bool ExecPackageCommand(EvalContext *ctx, char *command, int verify, int setCmdClasses, const Attributes *a, +bool ExecPackageCommand(EvalContext *ctx, const char *command, int verify, int setCmdClasses, const Attributes *a, const Promise *pp, PromiseResult *result) { assert(a != NULL); assert(pp != NULL); // Dereferenced by cfPS macros bool retval = true; - char *cmd; + const char *cmd; FILE *pfp; int packmanRetval = 0; diff --git a/cf-agent/verify_users_pam.c b/cf-agent/verify_users_pam.c index 84da4ac217..53ffa692ca 100644 --- a/cf-agent/verify_users_pam.c +++ b/cf-agent/verify_users_pam.c @@ -413,7 +413,7 @@ static bool ChangePasswordHashUsingChpasswd(const char *puser, const char *passw int status; const char *cmd_str = CHPASSWD " -e"; Log(LOG_LEVEL_VERBOSE, "Changing password hash for user '%s'. (command: '%s')", puser, cmd_str); - FILE *cmd = cf_popen_sh(cmd_str, "w"); + FILE *cmd = cf_popen(cmd_str, "w", true); if (!cmd) { Log(LOG_LEVEL_ERR, "Could not launch password changing command '%s': %s.", cmd_str, GetErrorStr()); @@ -643,14 +643,22 @@ static bool ExecuteUserCommand(const char *puser, const char *cmd, size_t sizeof return false; } - Log(LOG_LEVEL_VERBOSE, "%s user '%s'. (command: '%s')", cap_action_msg, puser, cmd); + Log(LOG_LEVEL_VERBOSE, "ExecuteUserCommand: %s user '%s'.", cap_action_msg, puser); - int status = system(cmd); - if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) + FILE *fptr = cf_popen(cmd, "w", true); + if (!fptr) { - Log(LOG_LEVEL_ERR, "Command returned error while %s user '%s'. (Command line: '%s')", action_msg, puser, cmd); + Log(LOG_LEVEL_ERR, "ExecuteUserCommand: returned error while %s user '%s'.", action_msg, puser); return false; } + + int status = cf_pclose(fptr); + if (status) + { + Log(LOG_LEVEL_ERR, "ExecuteUserCommand: returned non-zero status: %i\n", status); + return false; + } + return true; } @@ -665,7 +673,7 @@ static bool ChangePasswordHashUsingChpass(const char *puser, const char *passwor StringAppend(cmd, "\' ", sizeof(cmd)); StringAppend(cmd, puser, sizeof(cmd)); - Log(LOG_LEVEL_VERBOSE, "Changing password hash for user '%s'. (command: '%s')", puser, cmd); + Log(LOG_LEVEL_VERBOSE, "Changing password hash for user '%s' using chpass.", puser); return ExecuteUserCommand(puser, cmd, sizeof(cmd), "changing", "Changing"); } @@ -993,13 +1001,13 @@ static bool EqualGid(const char *key, const struct group *entry) { assert(entry != NULL); - unsigned long gid; + unsigned long gid; int ret = StringToUlong(key, &gid); if (ret != 0) { LogStringToLongError(key, "EqualGid", ret); return false; - } + } return (gid == entry->gr_gid); } @@ -1146,16 +1154,16 @@ static void TransformGidsToGroups(StringSet **list) StringSetDestroy(old_list); } -static bool VerifyIfUserNeedsModifs(const char *puser, const User *u, +static bool VerifyIfUserNeedsModifs(const char *puser, const User *u, const struct passwd *passwd_info, - uint32_t *changemap, - StringSet *groups_to_set, + uint32_t *changemap, + StringSet *groups_to_set, StringSet *current_secondary_groups) { assert(u != NULL); assert(passwd_info != NULL); - if (u->description != NULL && + if (u->description != NULL && !StringEqual(u->description, passwd_info->pw_gecos)) { CFUSR_SETBIT(*changemap, i_comment); @@ -1205,17 +1213,17 @@ static bool VerifyIfUserNeedsModifs(const char *puser, const User *u, if (SafeStringLength(u->group_primary) != 0) { - bool group_could_be_gid = (strlen(u->group_primary) == + bool group_could_be_gid = (strlen(u->group_primary) == strspn(u->group_primary, "0123456789")); // We try name first, even if it looks like a gid. Only fall back to gid. errno = 0; - struct group *group_info = GetGrEntry(u->group_primary, + struct group *group_info = GetGrEntry(u->group_primary, &EqualGroupName); if (group_info == NULL && errno != 0) { - Log(LOG_LEVEL_ERR, - "Could not obtain information about group '%s': %s", + Log(LOG_LEVEL_ERR, + "Could not obtain information about group '%s': %s", u->group_primary, GetErrorStr()); CFUSR_SETBIT(*changemap, i_group); } @@ -1227,7 +1235,7 @@ static bool VerifyIfUserNeedsModifs(const char *puser, const User *u, int ret = StringToUlong(u->group_primary, &gid); if (ret != 0) { - LogStringToLongError(u->group_primary, + LogStringToLongError(u->group_primary, "VerifyIfUserNeedsModifs", ret); CFUSR_SETBIT(*changemap, i_group); } diff --git a/cf-check/backup.c b/cf-check/backup.c index f37936a57b..221ae9259a 100644 --- a/cf-check/backup.c +++ b/cf-check/backup.c @@ -70,8 +70,9 @@ const char *create_backup_dir() return NULL; } - const int n = - snprintf(backup_dir, PATH_MAX, "%s%jd/", backup_root, (intmax_t)ts); + int n = + snprintf(backup_dir, PATH_MAX - 1, // trailing slash for later + "%s%jd-XXXXXX", backup_root, (intmax_t)ts); if (n >= PATH_MAX) { Log(LOG_LEVEL_ERR, @@ -81,7 +82,7 @@ const char *create_backup_dir() return NULL; } - if (mkdir(backup_dir, 0700) != 0) + if (mkdtemp(backup_dir) == NULL) { Log(LOG_LEVEL_ERR, "Could not create directory '%s' (%s)", @@ -90,6 +91,10 @@ const char *create_backup_dir() return NULL; } + // Add trailing forward slash + backup_dir[n++] = FILE_SEPARATOR; + backup_dir[n] = '\0'; + return backup_dir; } @@ -102,6 +107,11 @@ int backup_files_copy(Seq *filenames) assert_or_return(length > 0, 1); const char *backup_dir = create_backup_dir(); + if (backup_dir == NULL) + { + // Error already logged + return -1; + } Log(LOG_LEVEL_INFO, "Backing up to '%s'", backup_dir); diff --git a/cf-check/db_structs.h b/cf-check/db_structs.h index 0ca3d23a08..17ba14e73b 100644 --- a/cf-check/db_structs.h +++ b/cf-check/db_structs.h @@ -17,6 +17,7 @@ // Struct used for quality entries in /var/cfengine/state/cf_lastseen.lmdb: typedef struct { + bool acknowledged; time_t lastseen; QPoint Q; } KeyHostSeen; // Keep in sync with lastseen.h diff --git a/cf-check/dump.c b/cf-check/dump.c index 6ddc89cad6..6ded3c8bbd 100644 --- a/cf-check/dump.c +++ b/cf-check/dump.c @@ -107,6 +107,7 @@ static void print_struct_lastseen_quality( memcpy(&quality, value.mv_data, sizeof(quality)); const time_t lastseen = quality.lastseen; const QPoint Q = quality.Q; + bool acknowledged = quality.acknowledged; JsonElement *q_json = JsonObjectCreate(4); JsonObjectAppendReal(q_json, "q", Q.q); @@ -115,6 +116,7 @@ static void print_struct_lastseen_quality( JsonObjectAppendReal(q_json, "dq", Q.dq); JsonElement *top_json = JsonObjectCreate(2); + JsonObjectAppendBool(top_json, "acknowledged", acknowledged); JsonObjectAppendInteger(top_json, "lastseen", lastseen); JsonObjectAppendObject(top_json, "Q", q_json); @@ -222,7 +224,7 @@ static void print_struct_persistent_class( /* Make a copy to ensure proper alignment. We cannot just copy data to a * local PersistentClassInfo variable because it contains a * variable-length string at the end (see the struct definition). */ - PersistentClassInfo *class_info = malloc(value.mv_size); + PersistentClassInfo *class_info = xmalloc(value.mv_size); memcpy(class_info, value.mv_data, value.mv_size); const unsigned int expires = class_info->expires; const PersistentClassPolicy policy = class_info->policy; diff --git a/cf-check/replicate_lmdb.c b/cf-check/replicate_lmdb.c index e8c6508adf..d88c561eb0 100644 --- a/cf-check/replicate_lmdb.c +++ b/cf-check/replicate_lmdb.c @@ -1,3 +1,4 @@ +#include // #define LMDB #include #include #include diff --git a/cf-runagent/cf-runagent.c b/cf-runagent/cf-runagent.c index 229300bcc3..5c29db2800 100644 --- a/cf-runagent/cf-runagent.c +++ b/cf-runagent/cf-runagent.c @@ -266,7 +266,7 @@ int main(int argc, char *argv[]) if (fork() == 0) /* child process */ { int remote_exit_code = HailServer(ctx, config, RlistScalarValue(rp)); - DoCleanupAndExit(remote_exit_code > 0 ? remote_exit_code : CF_RA_EXIT_CODE_OTHER_ERR); + DoCleanupAndExit(remote_exit_code >= 0 ? remote_exit_code : CF_RA_EXIT_CODE_OTHER_ERR); } else /* parent process */ { diff --git a/cf-secret/cf-secret.c b/cf-secret/cf-secret.c index 608389e265..e54a83f894 100644 --- a/cf-secret/cf-secret.c +++ b/cf-secret/cf-secret.c @@ -343,13 +343,13 @@ static bool RSAEncrypt(Seq *rsa_keys, const char *input_path, const char *output const EVP_CIPHER *cipher = EVP_aes_256_cbc(); EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); - const int key_size = EVP_PKEY_size((EVP_PKEY*) SeqAt(evp_keys, 0)); /* This sequence and the 'enc_key_sizes' array are both populated by the * EVP_SealInit() call below. */ Seq *enc_keys = SeqNew(n_keys, free); for (size_t i = 0; i < n_keys; i++) { + const int key_size = EVP_PKEY_size((EVP_PKEY*) SeqAt(evp_keys, i)); SeqAppend(enc_keys, xmalloc(key_size)); } int enc_key_sizes[n_keys]; @@ -951,6 +951,11 @@ int main(int argc, char *argv[]) if (print_headers) { + if (input_path == NULL) + { + Log(LOG_LEVEL_ERR, "No input file specified (Use -h for help)"); + DoCleanupAndExit(EXIT_FAILURE); + } FILE *input_file = OpenInputOutput(input_path, "r"); char key[MAX_HEADER_KEY_LEN + 1]; char value[MAX_HEADER_VAL_LEN + 1]; diff --git a/cf-serverd/server_common.c b/cf-serverd/server_common.c index 6322a1a9d2..09057687b1 100644 --- a/cf-serverd/server_common.c +++ b/cf-serverd/server_common.c @@ -704,6 +704,7 @@ int StatFile(ServerConnectionState *conn, char *sendbuffer, char *ofilename) /* the simplest way to transfer the data is to convert them into */ /* plain text and interpret them on the other side. */ { + assert(conn != NULL); Stat cfst; struct stat statbuf, statlinkbuf; char linkbuf[CF_BUFSIZE], filename[CF_BUFSIZE - 128]; @@ -846,10 +847,17 @@ int StatFile(ServerConnectionState *conn, char *sendbuffer, char *ofilename) memset(sendbuffer, 0, CF_MSGSIZE); + // +3 because we need to prepend 'OK:' to the path + if (strlen(linkbuf)+3 > CF_MSGSIZE) { + NDEBUG_UNUSED int ret = snprintf(sendbuffer, CF_MSGSIZE, "BAD: Symlink resolves to a path too long (%ld) to send over the protocol.", strlen(linkbuf)+3); + assert(ret > 0 && ret < CF_MSGSIZE); + SendTransaction(conn->conn_info, sendbuffer, 0, CF_DONE); + return -1; + } if (cfst.cf_readlink != NULL) { - strcpy(sendbuffer, "OK:"); - strcat(sendbuffer, cfst.cf_readlink); + NDEBUG_UNUSED int ret = snprintf(sendbuffer, CF_MSGSIZE, "OK:%s", linkbuf); + assert(ret > 0 && ret < CF_MSGSIZE); } else { diff --git a/cf-serverd/server_tls.c b/cf-serverd/server_tls.c index edc185237b..10f0794320 100644 --- a/cf-serverd/server_tls.c +++ b/cf-serverd/server_tls.c @@ -226,8 +226,8 @@ bool ServerTLSPeek(ConnectionInfo *conn_info) const int peek_size = CF_INBAND_OFFSET + sizeof("CAUTH"); - char buf[peek_size]; - ssize_t got = recv(ConnectionInfoSocket(conn_info), buf, sizeof(buf), MSG_PEEK); + char *buf = alloca(peek_size); + ssize_t got = recv(ConnectionInfoSocket(conn_info), buf, peek_size, MSG_PEEK); assert(got <= peek_size); if (got < 0) { diff --git a/configure.ac b/configure.ac index 96609095da..2672739018 100644 --- a/configure.ac +++ b/configure.ac @@ -123,6 +123,17 @@ AC_PROG_CC AC_PROG_MKDIR_P AC_EXEEXT +AS_CASE([${target_os}], +[darwin*], [ + AC_CHECK_PROG([BREW], [brew], [brew]) + AC_MSG_CHECKING([for OS X Homebrew]) + AS_IF([test "x$BREW" = "xbrew"], [ + have_brew=yes + AC_MSG_RESULT([OS X Homebrew detected]) + ], + [have_brew=]) +]) + dnl GCC specific flags m4_include([m4/cf3_gcc_flags.m4]) @@ -212,12 +223,12 @@ AS_IF([test x"$enable_fhs" = xyes], [ prefix=/var/cfengine case "$target_os" in mingw*) - WORKDIR=$(cmd /c "echo %PROGRAMFILES%\\Cfengine" | sed 's/\\/\\\\/g') + WORKDIR=$(wine cmd.exe /c "echo %PROGRAMFILES%\\Cfengine" 2>/dev/null | sed 's/\\/\\\\/g') MASTERDIR=default INPUTDIR=default DATADIR=default - LOGDIR=$(cmd /c "echo %PROGRAMFILES%\\Cfengine" | sed 's/\\/\\\\/g') - PIDDIR=$(cmd /c "echo %PROGRAMFILES%\\Cfengine" | sed 's/\\/\\\\/g') + LOGDIR=$(wine cmd.exe /c "echo %PROGRAMFILES%\\Cfengine" 2>/dev/null | sed 's/\\/\\\\/g') + PIDDIR=$(wine cmd.exe /c "echo %PROGRAMFILES%\\Cfengine" 2>/dev/null | sed 's/\\/\\\\/g') STATEDIR=default ;; *) @@ -374,6 +385,8 @@ then fi fi + AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix mysql)/], [with_mysql=$(brew --prefix mysql)]) + CF3_WITH_LIBRARY(mysql, [AC_CHECK_LIB(mysqlclient, mysql_real_connect, [], @@ -437,6 +450,8 @@ AC_ARG_WITH([lmdb], AS_IF([test $WITH_TOKYO -eq 0 && test $WITH_QDBM -eq 0 && (! test -n "$with_lmdb" || test "x$with_lmdb" != "xno")], [WITH_LMDB=1], [WITH_LMDB=0]) if test $WITH_LMDB = 1; then + AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix lmdb)/], [with_lmdb=$(brew --prefix lmdb)]) + CF3_WITH_LIBRARY(lmdb, [ AC_CHECK_LIB(lmdb, mdb_dbi_open, [], [AC_MSG_ERROR(Cannot find Lightning MDB)]) AC_CHECK_HEADERS(lmdb.h, [], [AC_MSG_ERROR(Cannot find Lightning MDB)]) @@ -460,13 +475,7 @@ if test x"$with_openssl" = xno ; then AC_MSG_ERROR([This release of CFEngine requires OpenSSL >= 0.9.7]) fi -if test -d /usr/local/Cellar/ && \ - test -d /usr/local/opt/openssl/ && \ - test "x$with_openssl" = "xyes" ; then - with_openssl=$(brew --prefix openssl) - echo "OS X Homebrew detected" - echo "Defaulting to: --with-openssl=$with_openssl" -fi +AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix openssl)/], [with_openssl=$(brew --prefix openssl)]) CF3_WITH_LIBRARY(openssl, [ AC_CHECK_LIB(crypto, RSA_generate_key_ex, [], []) @@ -505,12 +514,15 @@ CF3_WITH_LIBRARY(openssl, [ ]) dnl PCRE2 + AC_ARG_WITH([pcre2], [AS_HELP_STRING([--with-pcre2[[=PATH]]], [Specify PCRE2 path])], [], [with_pcre2=yes]) if test "x$with_pcre2" = "xno"; then AC_MSG_ERROR([PCRE2 is required]) fi +AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix pcre2)/], [with_pcre2=$(brew --prefix pcre2)]) + CF3_WITH_LIBRARY(pcre2, [ AC_CHECK_LIB(pcre2-8, pcre2_compile_8, [], [AC_MSG_ERROR(Cannot find PCRE2)]) AC_CHECK_HEADERS( @@ -534,6 +546,8 @@ AC_ARG_WITH([libvirt], if test "x$with_libvirt" != xno then + AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix libvirt)/], [with_libvirt=$(brew --prefix libvirt)]) + CF3_WITH_LIBRARY(libvirt, [ AC_CHECK_LIB(virt, virConnectOpen, [], [if test "x$with_libvirt" != xcheck; then AC_MSG_ERROR(Cannot find libvirt library); fi]) AC_CHECK_HEADERS(libvirt/libvirt.h, [], [if test "x$with_libvirt" != xcheck; then AC_MSG_ERROR(Cannot find libvirt library headers); fi]) @@ -573,6 +587,8 @@ AC_ARG_WITH([libcurl], if test "x$with_libcurl" != xno then + AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix curl)/], [with_libcurl=$(brew --prefix curl)]) + CF3_WITH_LIBRARY(libcurl, [ AC_CHECK_LIB(curl, curl_global_init, [], @@ -598,6 +614,8 @@ AC_ARG_WITH([libyaml], if test "x$with_libyaml" != xno then + AS_IF([test "x$have_brew" = "xyes" && test -d $(brew --prefix libyaml)/], [with_libyaml=$(brew --prefix libyaml)]) + CF3_WITH_LIBRARY(libyaml, [ AC_CHECK_LIB(yaml, yaml_parser_initialize, [], @@ -620,7 +638,13 @@ AC_ARG_WITH([libxml2], have_libxml2="no" if test "x$with_libxml2" != "xno"; then - if test -n "$PKG_CONFIG"; then + if test "x$have_brew" = "xyes" && \ + test -d $(brew --prefix libxml2)/; then + with_libxml2=$(brew --prefix libxml2) + echo "OS X Homebrew detected" + echo "Defaulting to: --with-libxml2=$with_libxml2" + have_libxml2="yes" + elif test -n "$PKG_CONFIG"; then AC_MSG_CHECKING([for libxml2 via pkg-config]) if `$PKG_CONFIG --exists libxml-2.0`; then LIBXML2_CFLAGS=`$PKG_CONFIG --cflags libxml-2.0` @@ -1128,7 +1152,7 @@ dnl dnl Various functions dnl -AC_SEARCH_LIBS(setsockopt, socket) +AC_SEARCH_LIBS(setsockopt, [socket ws2_32]) AC_SEARCH_LIBS(gethostent, nsl) AC_CHECK_FUNCS(socket) @@ -1158,7 +1182,16 @@ AC_CHECK_DECLS(getaddrinfo, [], [], [[ #endif ]]) -AC_CHECK_DECLS([[inet_ntop], [inet_pton]], [], [], [[#include ]]) +AC_CHECK_DECLS([[inet_ntop], [inet_pton]], [], [], [[ +#if HAVE_WINSOCK2_H + #include +#endif +#if HAVE_WS2TCPIP_H + #include +#else + #include +#endif +]]) AC_CHECK_FUNCS(getifaddrs) @@ -1759,6 +1792,8 @@ AC_MSG_RESULT([-> OpenSSL: $OPENSSL_PATH]) AC_MSG_RESULT([-> PCRE2: $PCRE2_PATH]) +AC_MSG_RESULT([-> Rsync: $LIBRSYNC_PATH]) + if test $WITH_TOKYO = 1; then AC_MSG_RESULT([-> DB: Tokyo Cabinet: $TOKYOCABINET_PATH]) elif test $WITH_QDBM = 1; then diff --git a/contrib/masterfiles-stage/README.org b/contrib/masterfiles-stage/README.org index 90afe93588..74108005e6 100644 --- a/contrib/masterfiles-stage/README.org +++ b/contrib/masterfiles-stage/README.org @@ -97,6 +97,16 @@ are pre-installed when using CFEngine Enterprise. Next, configure the default parameter set (=DEFAULT_PARAMS_FILE=). +*** Legacy behavior + +Before CFEngine 3.24.0 release the cfbs variant of this script would run cfbs build every update policy run. + +This could be used to run scripts to dynamically create files in the policy set but also broke one important feature of cfbs build which is to make deterministic builds that result in the same outputs given the same inputs. + +The new default behavior as of 3.24.0 is to not run cfbs build if the repository has not changed. + +As of release 3.24.4, 3.27.1 and 3.28.0 you can restore this legacy behavior by touching the file /var/cfengine/state/mpf_masterfiles_stage_build_always.flag. + *** Troubleshooting You may experience issues trying to use the old versions of various dependencies. Try these solutions to common issues. diff --git a/contrib/masterfiles-stage/common.sh b/contrib/masterfiles-stage/common.sh index 250bbae34c..3aa49a4568 100755 --- a/contrib/masterfiles-stage/common.sh +++ b/contrib/masterfiles-stage/common.sh @@ -212,7 +212,9 @@ git_cfbs_deploy_refspec() { # We don't mkdir $1 directly, just its parent dir if that doesn't exist. if git_check_is_in_sync "${local_mirrored_repo}" "$1" "$2"; then - return 0 + if [ ! -f /var/cfengine/state/mpf_masterfiles_stage_build_always.flag ]; then + return 0 + fi fi ########################## 1. CREATE EMPTY TEMP DIR diff --git a/examples/findfiles.cf b/examples/findfiles.cf index 723aea9d13..1ef73683de 100644 --- a/examples/findfiles.cf +++ b/examples/findfiles.cf @@ -40,6 +40,6 @@ bundle agent run ############################################################################### #+begin_src example_output #@ ``` -#@ R: All files that match '/[tT][mM][pP]' = /tmp +#@ R: All files that match '/[tT][mM][pP]' = /tmp/ #@ ``` #+end_src diff --git a/examples/nth-key.cf b/examples/nth-key.cf new file mode 100644 index 0000000000..e9363c9e17 --- /dev/null +++ b/examples/nth-key.cf @@ -0,0 +1,20 @@ +#+begin_src cfengine3 +bundle agent main +{ + vars: + "d" data => '{ "key1": "dvalue1", "key2": "dvalue2" }'; + "a[key1]" string => "value1"; + "a[key2]" string => "value2"; + + reports: + "$(with)" with => nth( a, "key1" ); + "$(with)" with => nth( d, "key1" ); +} +#+end_src +############################################################################### +#+begin_src example_output +#@ ``` +#@ R: value1 +#@ R: dvalue1 +#@ ``` +#+end_src diff --git a/examples/peerleader.cf b/examples/peerleader.cf index fdc4eb2a52..e2f5a4e184 100644 --- a/examples/peerleader.cf +++ b/examples/peerleader.cf @@ -25,7 +25,8 @@ #@ echo beta >> /tmp/cfe_hostlist #@ echo gamma >> /tmp/cfe_hostlist #@ echo "Set HOSTNAME appropriately beforehand" -#@ echo "$(hostname -f)" | tr 'A-Z' 'a-z' >> /tmp/cfe_hostlist +#@ touch $CFENGINE_TEST_OVERRIDE_WORKDIR/inputs/promises.cf # to enable cf-promises to run +#@ bash -c "${CF_PROMISES} --show-vars=sys.fqhost | grep fqhost | awk '{print \$2}' | tr 'A-Z' 'a-z' 2>&1 >> /tmp/cfe_hostlist" #@ echo "Delta Delta Delta may I help ya help ya help ya" #@ echo delta1 >> /tmp/cfe_hostlist #@ echo delta2 >> /tmp/cfe_hostlist diff --git a/examples/peerleaders.cf b/examples/peerleaders.cf index fdc4eb2a52..e2f5a4e184 100644 --- a/examples/peerleaders.cf +++ b/examples/peerleaders.cf @@ -25,7 +25,8 @@ #@ echo beta >> /tmp/cfe_hostlist #@ echo gamma >> /tmp/cfe_hostlist #@ echo "Set HOSTNAME appropriately beforehand" -#@ echo "$(hostname -f)" | tr 'A-Z' 'a-z' >> /tmp/cfe_hostlist +#@ touch $CFENGINE_TEST_OVERRIDE_WORKDIR/inputs/promises.cf # to enable cf-promises to run +#@ bash -c "${CF_PROMISES} --show-vars=sys.fqhost | grep fqhost | awk '{print \$2}' | tr 'A-Z' 'a-z' 2>&1 >> /tmp/cfe_hostlist" #@ echo "Delta Delta Delta may I help ya help ya help ya" #@ echo delta1 >> /tmp/cfe_hostlist #@ echo delta2 >> /tmp/cfe_hostlist diff --git a/examples/peers.cf b/examples/peers.cf index fdc4eb2a52..e2f5a4e184 100644 --- a/examples/peers.cf +++ b/examples/peers.cf @@ -25,7 +25,8 @@ #@ echo beta >> /tmp/cfe_hostlist #@ echo gamma >> /tmp/cfe_hostlist #@ echo "Set HOSTNAME appropriately beforehand" -#@ echo "$(hostname -f)" | tr 'A-Z' 'a-z' >> /tmp/cfe_hostlist +#@ touch $CFENGINE_TEST_OVERRIDE_WORKDIR/inputs/promises.cf # to enable cf-promises to run +#@ bash -c "${CF_PROMISES} --show-vars=sys.fqhost | grep fqhost | awk '{print \$2}' | tr 'A-Z' 'a-z' 2>&1 >> /tmp/cfe_hostlist" #@ echo "Delta Delta Delta may I help ya help ya help ya" #@ echo delta1 >> /tmp/cfe_hostlist #@ echo delta2 >> /tmp/cfe_hostlist diff --git a/examples/services_default_service_bundle.cf b/examples/services_default_service_bundle.cf index 7182d20f8d..2adeafc400 100644 --- a/examples/services_default_service_bundle.cf +++ b/examples/services_default_service_bundle.cf @@ -9,7 +9,7 @@ bundle agent main body service_method my_custom_service { - service_type => "generic"; + service_bundle => service_my_custom_service($(this.promiser), $(this.service_policy)); } bundle agent service_my_custom_service(service, state) @@ -25,5 +25,3 @@ bundle agent service_my_custom_service(service, state) #@ ``` #+end_src - - diff --git a/libcfnet/Makefile.am b/libcfnet/Makefile.am index 3e5cff8619..99d09431c9 100644 --- a/libcfnet/Makefile.am +++ b/libcfnet/Makefile.am @@ -27,6 +27,7 @@ AM_CPPFLAGS = -I$(top_srcdir)/libntech/libutils \ -I$(top_srcdir)/libpromises \ $(PCRE2_CPPFLAGS) \ $(SYSTEMD_SOCKET_CPPFLAGS) \ + $(LIBRSYNC_CPPFLAGS) \ $(OPENSSL_CPPFLAGS) libcfnet_la_SOURCES = \ diff --git a/libcfnet/client_code.c b/libcfnet/client_code.c index f31463c385..7dccb88324 100644 --- a/libcfnet/client_code.c +++ b/libcfnet/client_code.c @@ -750,7 +750,7 @@ static void FlushFileStream(int sd, int toget) /* TODO finalise socket or TLS session in all cases that this function fails * and the transaction protocol is out of sync. */ bool CopyRegularFileNet(const char *source, const char *dest, off_t size, - bool encrypt, AgentConnection *conn) + bool encrypt, AgentConnection *conn, mode_t mode) { char *buf, workbuf[CF_BUFSIZE], cfchangedstr[265]; const int buf_size = 2048; @@ -774,7 +774,7 @@ bool CopyRegularFileNet(const char *source, const char *dest, off_t size, unlink(dest); /* To avoid link attacks */ - int dd = safe_open_create_perms(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL | O_BINARY, CF_PERMS_DEFAULT); + int dd = safe_open_create_perms(dest, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL | O_BINARY, mode); if (dd == -1) { Log(LOG_LEVEL_ERR, diff --git a/libcfnet/client_code.h b/libcfnet/client_code.h index d926541721..4aaaa5ff4c 100644 --- a/libcfnet/client_code.h +++ b/libcfnet/client_code.h @@ -48,7 +48,7 @@ void DisconnectServer(AgentConnection *conn); bool CompareHashNet(const char *file1, const char *file2, bool encrypt, AgentConnection *conn); bool CopyRegularFileNet(const char *source, const char *dest, off_t size, - bool encrypt, AgentConnection *conn); + bool encrypt, AgentConnection *conn, mode_t mode); Item *RemoteDirList(const char *dirname, bool encrypt, AgentConnection *conn); int TLSConnectCallCollect(ConnectionInfo *conn_info, const char *username); diff --git a/libcfnet/protocol.c b/libcfnet/protocol.c index 3a6f9bcb37..5ae2648230 100644 --- a/libcfnet/protocol.c +++ b/libcfnet/protocol.c @@ -37,7 +37,7 @@ Seq *ProtocolOpenDir(AgentConnection *conn, const char *path) assert(conn != NULL); assert(path != NULL); - char buf[CF_MSGSIZE] = {0}; + char buf[CF_BUFSIZE] = {0}; int tosend = snprintf(buf, CF_MSGSIZE, "OPENDIR %s", path); if (tosend < 0 || tosend >= CF_MSGSIZE) { @@ -109,7 +109,7 @@ bool ProtocolGet(AgentConnection *conn, const char *remote_path, return false; } - char buf[CF_MSGSIZE] = {0}; + char buf[CF_BUFSIZE] = {0}; int to_send = snprintf(buf, CF_MSGSIZE, "GET %d %s", CF_MSGSIZE, remote_path); diff --git a/libenv/sysinfo.c b/libenv/sysinfo.c index 145ad7d927..2dc077ffac 100644 --- a/libenv/sysinfo.c +++ b/libenv/sysinfo.c @@ -1182,8 +1182,9 @@ static void OSReleaseParse(EvalContext *ctx, const char *file_path) { alias = "redhat"; } - else if (StringEqual(os_release_id, "opensuse") || - StringEqual(os_release_id, "sles")) + else if (StringEqual(os_release_id, "opensuse") || + StringEqual(os_release_id, "sles") || + StringEqual(os_release_id, "sled")) { alias = "suse"; } @@ -1376,7 +1377,12 @@ static void OSClasses(EvalContext *ctx) SetFlavor(ctx, "gentoo"); } - if (stat("/etc/arch-release", &statbuf) != -1) + if (stat("/etc/manjaro-release", &statbuf) != -1) + { + Log(LOG_LEVEL_VERBOSE, "This appears to be a Manjaro Linux system."); + SetFlavor(ctx, "manjaro"); + } + else if (stat("/etc/arch-release", &statbuf) != -1) { Log(LOG_LEVEL_VERBOSE, "This appears to be an Arch Linux system."); SetFlavor(ctx, "archlinux"); @@ -3508,6 +3514,12 @@ static void SysOSNameHuman(EvalContext *ctx) "Amazon", CF_DATA_TYPE_STRING, "source=agent,derived-from=amazon_linux"); } + else if (EvalContextClassGet(ctx, NULL, "manjaro") != NULL) + { + EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval, + "Manjaro", CF_DATA_TYPE_STRING, + "source=agent,derived-from=manjaro"); + } else if (EvalContextClassGet(ctx, NULL, "arch") != NULL) { EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, lval, @@ -3540,13 +3552,13 @@ static void SysOSNameHuman(EvalContext *ctx) /** * Find next integer from string in place. Leading zero's are included. - * + * * @param [in] str string to extract next integer from * @param [out] num pointer to start of next integer or %NULL if no integer * number was found - * + * * @return pointer to the remaining string in `str` or %NULL if no remainder - * + * * @note `str` will be mutated */ static char *FindNextInteger(char *str, char **num) @@ -3614,8 +3626,8 @@ static void SysOsVersionMajor(EvalContext *ctx) } else { - EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, - "os_version_major", major, + EvalContextVariablePutSpecial(ctx, SPECIAL_SCOPE_SYS, + "os_version_major", major, CF_DATA_TYPE_STRING, "source=agent,derived-from=flavor"); } diff --git a/libenv/unix_iface.c b/libenv/unix_iface.c index 06b2eb1d57..d9631ffe95 100644 --- a/libenv/unix_iface.c +++ b/libenv/unix_iface.c @@ -39,6 +39,7 @@ #include #include #include +#include /* GetRelocatedProcdirRoot() and GetProcdirPid() */ #ifdef HAVE_SYS_JAIL_H # include @@ -721,6 +722,11 @@ static void FindV6InterfacesInfo(EvalContext *ctx, Rlist **interfaces, Rlist **h } } + if (IgnoreInterface(current_interface)) + { + // Ignore interfaces listed in ignore_interfaces.rx + continue; + } const char *const stripped_ifconfig_line = TrimWhitespace(ifconfig_line); @@ -1278,6 +1284,10 @@ static JsonElement* GetNetworkingStatsInfo(const char *filename) fclose(fin); } + else + { + Log(LOG_LEVEL_VERBOSE, "netstat file not found at '%s'", filename); + } return stats; } @@ -1385,12 +1395,13 @@ JsonElement* GetProcFileInfo(EvalContext *ctx, const char* filename, const char* void GetNetworkingInfo(EvalContext *ctx) { const char *procdir_root = GetRelocatedProcdirRoot(); + int promiser_pid = GetProcdirPid(); Buffer *pbuf = BufferNew(); JsonElement *inet = JsonObjectCreate(2); - BufferPrintf(pbuf, "%s/proc/net/netstat", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/netstat", procdir_root, promiser_pid); JsonElement *inet_stats = GetNetworkingStatsInfo(BufferData(pbuf)); if (inet_stats != NULL) @@ -1398,7 +1409,7 @@ void GetNetworkingInfo(EvalContext *ctx) JsonObjectAppendElement(inet, "stats", inet_stats); } - BufferPrintf(pbuf, "%s/proc/net/route", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/route", procdir_root, promiser_pid); JsonElement *routes = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingRoutesPostProcessInfo, NULL, // format: Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT // eth0 00000000 0102A8C0 0003 0 0 1024 00000000 0 0 0 @@ -1446,7 +1457,7 @@ void GetNetworkingInfo(EvalContext *ctx) JsonElement *inet6 = JsonObjectCreate(3); - BufferPrintf(pbuf, "%s/proc/net/snmp6", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/snmp6", procdir_root, promiser_pid); JsonElement *inet6_stats = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, NULL, NULL, "^\\s*(?\\S+)\\s+(?\\d+)"); @@ -1472,7 +1483,7 @@ void GetNetworkingInfo(EvalContext *ctx) JsonDestroy(inet6_stats); } - BufferPrintf(pbuf, "%s/proc/net/ipv6_route", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/ipv6_route", procdir_root, promiser_pid); JsonElement *inet6_routes = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingIPv6RoutesPostProcessInfo, NULL, // format: dest dest_prefix source source_prefix next_hop metric refcnt use flags interface // fe800000000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000000 00000000 00000001 eth0 @@ -1487,7 +1498,7 @@ void GetNetworkingInfo(EvalContext *ctx) JsonObjectAppendElement(inet6, "routes", inet6_routes); } - BufferPrintf(pbuf, "%s/proc/net/if_inet6", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/if_inet6", procdir_root, promiser_pid); JsonElement *inet6_addresses = GetProcFileInfo(ctx, BufferData(pbuf), NULL, "interface", &NetworkingIPv6AddressesPostProcessInfo, &NetworkingIPv6AddressesTiebreaker, // format: address device_number prefix_length scope flags interface_name // 00000000000000000000000000000001 01 80 10 80 lo @@ -1510,7 +1521,7 @@ void GetNetworkingInfo(EvalContext *ctx) // face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed // eth0: 74850544807 75236137 0 0 0 0 0 1108775 63111535625 74696758 0 0 0 0 0 0 - BufferPrintf(pbuf, "%s/proc/net/dev", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/dev", procdir_root, promiser_pid); JsonElement *interfaces_data = GetProcFileInfo(ctx, BufferData(pbuf), "interfaces_data", "device", NULL, NULL, "^\\s*(?[^:]+)\\s*:\\s*" @@ -1538,34 +1549,35 @@ void GetNetworkingInfo(EvalContext *ctx) JsonElement* GetNetworkingConnections(EvalContext *ctx) { const char *procdir_root = GetRelocatedProcdirRoot(); + int promiser_pid = GetProcdirPid(); JsonElement *json = JsonObjectCreate(5); const char* ports_regex = "^\\s*\\d+:\\s+(?[0-9A-F:]+)\\s+(?[0-9A-F:]+)\\s+(?[0-9]+)"; JsonElement *data = NULL; Buffer *pbuf = BufferNew(); - BufferPrintf(pbuf, "%s/proc/net/tcp", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/tcp", procdir_root, promiser_pid); data = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingPortsPostProcessInfo, NULL, ports_regex); if (data != NULL) { JsonObjectAppendElement(json, "tcp", data); } - BufferPrintf(pbuf, "%s/proc/net/tcp6", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/tcp6", procdir_root, promiser_pid); data = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingPortsPostProcessInfo, NULL, ports_regex); if (data != NULL) { JsonObjectAppendElement(json, "tcp6", data); } - BufferPrintf(pbuf, "%s/proc/net/udp", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/udp", procdir_root, promiser_pid); data = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingPortsPostProcessInfo, NULL, ports_regex); if (data != NULL) { JsonObjectAppendElement(json, "udp", data); } - BufferPrintf(pbuf, "%s/proc/net/udp6", procdir_root); + BufferPrintf(pbuf, "%s/proc/%d/net/udp6", procdir_root, promiser_pid); data = GetProcFileInfo(ctx, BufferData(pbuf), NULL, NULL, &NetworkingPortsPostProcessInfo, NULL, ports_regex); if (data != NULL) { diff --git a/libntech b/libntech index 13a9e99350..d7bd160217 160000 --- a/libntech +++ b/libntech @@ -1 +1 @@ -Subproject commit 13a9e9935013948ebc9889e631fec0149ae87932 +Subproject commit d7bd16021768ea151493cd6e0873c66ddd0fed30 diff --git a/libpromises/attributes.c b/libpromises/attributes.c index b78ffdd998..810469b2e5 100644 --- a/libpromises/attributes.c +++ b/libpromises/attributes.c @@ -1113,6 +1113,26 @@ ContextConstraint GetContextConstraints(const EvalContext *ctx, const Promise *p a.expression = NULL; a.persistent = PromiseGetConstraintAsInt(ctx, "persistence", pp); + { + const char *tp = PromiseGetConstraintAsRval(pp, "timer_policy", RVAL_TYPE_SCALAR); + if (StringEqual(tp, "reset")) + { + a.timer = CONTEXT_STATE_POLICY_RESET; + } + else + { + /* Default to PRESERVE (absolute) for backward compatibility: + * classes: promises historically skip re-evaluation when the + * class is already defined, so the timer was never reset. + * + * NOTE: this default is planned to change to RESET in 3.28.0 + * (CFE-4681) to align with classes bodies, whose timer_policy + * already defaults to reset. The absolute default is retained on + * the 3.24 and 3.27 LTS backports. */ + a.timer = CONTEXT_STATE_POLICY_PRESERVE; + } + } + { const char *context_scope = PromiseGetConstraintAsRval(pp, "scope", RVAL_TYPE_SCALAR); a.scope = ContextScopeFromString(context_scope); @@ -1124,7 +1144,9 @@ ContextConstraint GetContextConstraints(const EvalContext *ctx, const Promise *p for (int k = 0; CF_CLASSBODY[k].lval != NULL; k++) { - if (strcmp(cp->lval, "persistence") == 0 || strcmp(cp->lval, "scope") == 0) + if (StringEqual(cp->lval, "persistence") || + StringEqual(cp->lval, "scope") || + StringEqual(cp->lval, "timer_policy")) { continue; } diff --git a/libpromises/cf3.defs.h b/libpromises/cf3.defs.h index 6294c92868..674c46a19a 100644 --- a/libpromises/cf3.defs.h +++ b/libpromises/cf3.defs.h @@ -1178,6 +1178,7 @@ typedef struct ContextScope scope; int nconstraints; int persistent; + PersistentClassPolicy timer; } ContextConstraint; /*************************************************************************/ diff --git a/libpromises/changes_chroot.c b/libpromises/changes_chroot.c index 0d27c0c239..062b387027 100644 --- a/libpromises/changes_chroot.c +++ b/libpromises/changes_chroot.c @@ -215,7 +215,7 @@ void PrepareChangesChroot(const char *path) continue; } char entry_path[PATH_MAX]; - strcpy(entry_path, path); + strlcpy(entry_path, path, sizeof(entry_path)); JoinPaths(entry_path, PATH_MAX, entry->d_name); PrepareChangesChroot(entry_path); } diff --git a/libpromises/conversion.c b/libpromises/conversion.c index 8de8ba5710..71c5f87312 100644 --- a/libpromises/conversion.c +++ b/libpromises/conversion.c @@ -957,7 +957,7 @@ static void AddSimpleUidItem(UidList ** uidlist, uid_t uid, char *uidname) ulp->uid = uid; - if (uid == CF_UNKNOWN_OWNER) /* unknown user */ + if (uid == CF_UNKNOWN_OWNER && uidname != NULL) /* unknown user */ { ulp->uidname = xstrdup(uidname); } @@ -988,7 +988,7 @@ UidList *Rlist2UidList(Rlist *uidnames, const Promise *pp) for (rp = uidnames; rp != NULL; rp = rp->next) { username[0] = '\0'; - uid = Str2Uid(RlistScalarValue(rp), username, pp); + uid = Str2Uid(RlistScalarValue(rp), username, sizeof(username), pp); AddSimpleUidItem(&uidlist, uid, username); } @@ -1019,7 +1019,7 @@ static void AddSimpleGidItem(GidList ** gidlist, gid_t gid, char *gidname) glp->gid = gid; - if (gid == CF_UNKNOWN_GROUP) /* unknown group */ + if (gid == CF_UNKNOWN_GROUP && gidname != NULL) /* unknown group */ { glp->gidname = xstrdup(gidname); } @@ -1049,7 +1049,7 @@ GidList *Rlist2GidList(Rlist *gidnames, const Promise *pp) for (rp = gidnames; rp != NULL; rp = rp->next) { groupname[0] = '\0'; - gid = Str2Gid(RlistScalarValue(rp), groupname, pp); + gid = Str2Gid(RlistScalarValue(rp), groupname, sizeof(groupname), pp); AddSimpleGidItem(&gidlist, gid, groupname); } @@ -1063,7 +1063,7 @@ GidList *Rlist2GidList(Rlist *gidnames, const Promise *pp) /*********************************************************************/ -uid_t Str2Uid(const char *uidbuff, char *usercopy, const Promise *pp) +uid_t Str2Uid(const char *uidbuff, char *usercopy, size_t copy_size, const Promise *pp) { if (StringEqual(uidbuff, "*")) { @@ -1126,7 +1126,7 @@ uid_t Str2Uid(const char *uidbuff, char *usercopy, const Promise *pp) { if (usercopy != NULL) { - strcpy(usercopy, uidbuff); + strlcpy(usercopy, uidbuff, copy_size); } } else @@ -1142,7 +1142,7 @@ uid_t Str2Uid(const char *uidbuff, char *usercopy, const Promise *pp) /*********************************************************************/ -gid_t Str2Gid(const char *gidbuff, char *groupcopy, const Promise *pp) +gid_t Str2Gid(const char *gidbuff, char *groupcopy, size_t copy_size, const Promise *pp) { if (StringEqual(gidbuff, "*")) { @@ -1169,7 +1169,7 @@ gid_t Str2Gid(const char *gidbuff, char *groupcopy, const Promise *pp) { if (groupcopy != NULL) { - strcpy(groupcopy, gidbuff); + strlcpy(groupcopy, gidbuff, copy_size); } } else diff --git a/libpromises/conversion.h b/libpromises/conversion.h index a8fbf1821c..d99cf1a525 100644 --- a/libpromises/conversion.h +++ b/libpromises/conversion.h @@ -83,8 +83,8 @@ void GidListDestroy(GidList *gids); UidList *Rlist2UidList(Rlist *uidnames, const Promise *pp); GidList *Rlist2GidList(Rlist *gidnames, const Promise *pp); #ifndef __MINGW32__ -uid_t Str2Uid(const char *uidbuff, char *copy, const Promise *pp); -gid_t Str2Gid(const char *gidbuff, char *copy, const Promise *pp); +uid_t Str2Uid(const char *uidbuff, char *copy, size_t copy_size, const Promise *pp); +gid_t Str2Gid(const char *gidbuff, char *copy, size_t copy_size, const Promise *pp); #endif /* !__MINGW32__ */ #endif diff --git a/libpromises/dbm_api.c b/libpromises/dbm_api.c index 168a7524ad..e757093e1e 100644 --- a/libpromises/dbm_api.c +++ b/libpromises/dbm_api.c @@ -426,17 +426,23 @@ bool OpenDBInstance(DBHandle **dbp, dbid id, DBHandle *handle) } } - DBPathUnLock(&lock); - } - - if (handle->priv) - { - if (!DBMigrate(handle, id)) + if (handle->priv != NULL) { - DBPrivCloseDB(handle->priv); - handle->priv = NULL; - handle->open_tstamp = -1; + if (!DBMigrate(handle, id)) + { + /* Migration failed. The best we can do is to move the + * broken DB to the side and start fresh. */ + DBPrivCloseDB(handle->priv); + DBPathMoveBroken(handle->filename); + handle->priv = DBPrivOpenDB(handle->filename, id); + if (handle->priv == DB_PRIV_DATABASE_BROKEN) + { + handle->priv = NULL; + } + } } + + DBPathUnLock(&lock); } } diff --git a/libpromises/dbm_lmdb.c b/libpromises/dbm_lmdb.c index 2b0cfcb847..b062774092 100644 --- a/libpromises/dbm_lmdb.c +++ b/libpromises/dbm_lmdb.c @@ -69,6 +69,7 @@ struct DBCursorPriv_ MDB_cursor *mc; MDB_val delkey; void *curkv; + size_t curks; bool pending_delete; }; @@ -1290,6 +1291,7 @@ bool DBPrivAdvanceCursor( } cursor->curkv = xmalloc(keybuf_size + data.mv_size); memcpy(cursor->curkv, mkey.mv_data, mkey.mv_size); + cursor->curks = mkey.mv_size; *key = cursor->curkv; *key_size = mkey.mv_size; *value_size = data.mv_size; @@ -1355,7 +1357,7 @@ bool DBPrivWriteCursorEntry( { MDB_val curkey; curkey.mv_data = cursor->curkv; - curkey.mv_size = sizeof(cursor->curkv); + curkey.mv_size = cursor->curks; rc = mdb_cursor_put(cursor->mc, &curkey, &data, MDB_CURRENT); CheckLMDBUsable(rc, cursor->db->env); diff --git a/libpromises/dbm_migration.c b/libpromises/dbm_migration.c index b5a54e3e7a..6066483533 100644 --- a/libpromises/dbm_migration.c +++ b/libpromises/dbm_migration.c @@ -26,11 +26,12 @@ #include #include +#include extern const DBMigrationFunction dbm_migration_plan_lastseen[]; -#ifdef LMDB +#ifndef LMDB bool DBMigrate(ARG_UNUSED DBHandle *db, ARG_UNUSED dbid id) { return true; @@ -64,6 +65,11 @@ bool DBMigrate(DBHandle *db, dbid id) { if (step_version == DBVersion(db)) { + Seq *seq = SeqNew(1, free); + SeqAppend(seq, DBIdToPath(id)); + backup_files_copy(seq); + SeqDestroy(seq); + if (!(*step)(db)) { return false; diff --git a/libpromises/dbm_migration_lastseen.c b/libpromises/dbm_migration_lastseen.c index 9590efea6d..fbcf6df9aa 100644 --- a/libpromises/dbm_migration_lastseen.c +++ b/libpromises/dbm_migration_lastseen.c @@ -26,6 +26,7 @@ #include #include +#include typedef struct { @@ -34,6 +35,12 @@ typedef struct double var; } QPoint0; +typedef struct +{ + time_t lastseen; + QPoint Q; // Average time between connections (rolling weighted average) +} KeyHostSeen1; + #define QPOINT0_OFFSET 128 /* @@ -48,142 +55,95 @@ typedef struct static bool LastseenMigrationVersion0(DBHandle *db) { - bool errors = false; - DBCursor *cursor; + /* For some reason DB migration for LMDB was disabled in 2014 (in commit + * 8611970bfa33be7b3cf0724eb684833e08582850). Unfortunately there is no + * mention as to why this was done. Maybe it was not working? + * + * However, we're re-enabling it now (10 years later). Since this + * migration function has not been active for the last 10 years, the + * safest thing is to remove the migration logic, and only update the + * version number. + * + * If you have not upgraded CFEngine in the last 10 years, this will be + * the least of your problems. + */ + return WriteDB(db, "version", "1", sizeof("1")); +} +static bool LastseenMigrationVersion1(DBHandle *db) +{ + DBCursor *cursor; if (!NewDBCursor(db, &cursor)) { + Log(LOG_LEVEL_ERR, + "Unable to create database cursor during lastseen migration"); return false; } char *key; void *value; - int ksize, vsize; + int key_size, value_size; - while (NextDB(cursor, &key, &ksize, &value, &vsize)) + // Iterate through all key-value pairs + while (NextDB(cursor, &key, &key_size, &value, &value_size)) { - if (ksize == 0) + if (key_size == 0) { - Log(LOG_LEVEL_INFO, "LastseenMigrationVersion0: Database structure error -- zero-length key."); + Log(LOG_LEVEL_WARNING, + "Found zero-length key during lastseen migration"); continue; } - /* Only look for old [+-]kH -> IP entries */ - if ((key[0] != '+') && (key[0] != '-')) + // Only look for old KeyHostSeen entries + if (key[0] != 'q') { - /* Warn about completely unexpected keys */ - - if ((key[0] != 'q') && (key[0] != 'k') && (key[0] != 'a')) + // Warn about completely unexpected keys + if ((key[0] != 'k') && (key[0] != 'a') && !StringEqualN(key, "version", key_size)) { - Log(LOG_LEVEL_INFO, "LastseenMigrationVersion0: Malformed key found '%s'", key); + Log(LOG_LEVEL_WARNING, + "Found unexpected key '%s' during lastseen migration. " + "Only expecting 'version' or 'k', 'a' and 'q[i|o]' prefixed keys.", + key); } - - continue; - } - - bool incoming = key[0] == '-'; - const char *hostkey = key + 1; - - /* Only migrate sane data */ - if (vsize != QPOINT0_OFFSET + sizeof(QPoint0)) - { - Log(LOG_LEVEL_INFO, - "LastseenMigrationVersion0: invalid value size for key '%s', entry is deleted", - key); - DBCursorDeleteEntry(cursor); - continue; - } - - /* Properly align the data */ - const char *old_data_address = (const char *) value; - QPoint0 old_data_q; - memcpy(&old_data_q, (const char *) value + QPOINT0_OFFSET, - sizeof(QPoint0)); - - char hostkey_key[CF_BUFSIZE]; - snprintf(hostkey_key, CF_BUFSIZE, "k%s", hostkey); - - if (!WriteDB(db, hostkey_key, old_data_address, strlen(old_data_address) + 1)) - { - Log(LOG_LEVEL_INFO, "Unable to write version 1 lastseen entry for '%s'", key); - errors = true; - continue; - } - - char address_key[CF_BUFSIZE]; - snprintf(address_key, CF_BUFSIZE, "a%s", old_data_address); - - if (!WriteDB(db, address_key, hostkey, strlen(hostkey) + 1)) - { - Log(LOG_LEVEL_INFO, "Unable to write version 1 reverse lastseen entry for '%s'", key); - errors = true; - continue; - } - - char quality_key[CF_BUFSIZE]; - snprintf(quality_key, CF_BUFSIZE, "q%c%s", incoming ? 'i' : 'o', hostkey); - - /* - Ignore malformed connection quality data - */ - - if ((!isfinite(old_data_q.q)) - || (old_data_q.q < 0) - || (!isfinite(old_data_q.expect)) - || (!isfinite(old_data_q.var))) - { - Log(LOG_LEVEL_INFO, "Ignoring malformed connection quality data for '%s'", key); - DBCursorDeleteEntry(cursor); continue; } - KeyHostSeen data = { - .lastseen = (time_t)old_data_q.q, - .Q = { - /* - Previously .q wasn't stored in database, but was calculated - every time as a difference between previous timestamp and a - new timestamp. Given we don't have this information during - the database upgrade, just assume that last reading is an - average one. - */ - .q = old_data_q.expect, - .dq = 0, - .expect = old_data_q.expect, - .var = old_data_q.var, - } + KeyHostSeen1 *old_value = value; + KeyHostSeen new_value = { + .acknowledged = true, // We don't know, assume yes + .lastseen = old_value->lastseen, + .Q = old_value->Q, }; - if (!WriteDB(db, quality_key, &data, sizeof(data))) - { - Log(LOG_LEVEL_INFO, "Unable to write version 1 connection quality key for '%s'", key); - errors = true; - continue; - } - - if (!DBCursorDeleteEntry(cursor)) + // This will overwrite the entry + if (!DBCursorWriteEntry(cursor, &new_value, sizeof(new_value))) { - Log(LOG_LEVEL_INFO, "Unable to delete version 0 lastseen entry for '%s'", key); - errors = true; + Log(LOG_LEVEL_ERR, + "Unable to write version 2 of entry for key '%s' during lastseen migration.", + key); + return false; } } - if (DeleteDBCursor(cursor) == false) + if (!DeleteDBCursor(cursor)) { - Log(LOG_LEVEL_ERR, "LastseenMigrationVersion0: Unable to close cursor"); - errors = true; + Log(LOG_LEVEL_ERR, "Unable to close cursor during lastseen migration"); + return false; } - if ((!errors) && (!WriteDB(db, "version", "1", sizeof("1")))) + if (!WriteDB(db, "version", "2", sizeof("2"))) { - errors = true; + Log(LOG_LEVEL_ERR, "Failed to update version number during lastseen migration"); + return false; } - return !errors; + Log(LOG_LEVEL_INFO, "Migrated lastseen database from version 1 to 2"); + return true; } const DBMigrationFunction dbm_migration_plan_lastseen[] = { LastseenMigrationVersion0, + LastseenMigrationVersion1, NULL }; diff --git a/libpromises/eval_context.c b/libpromises/eval_context.c index f13c502213..0319e9204f 100644 --- a/libpromises/eval_context.c +++ b/libpromises/eval_context.c @@ -710,7 +710,7 @@ void EvalContextHeapPersistentSave(EvalContext *ctx, const char *name, unsigned // first see if we have an existing record, and if we should bother to update { - int existing_info_size = ValueSizeDB(dbp, key, strlen(key)); + int existing_info_size = ValueSizeDB(dbp, key, strlen(key) + 1); if (existing_info_size > 0) { PersistentClassInfo *existing_info = xcalloc(existing_info_size, 1); @@ -723,24 +723,44 @@ void EvalContextHeapPersistentSave(EvalContext *ctx, const char *name, unsigned Log(LOG_LEVEL_VERBOSE, "Persistent class '%s' is already in a preserved state -- %jd minutes to go", key, (intmax_t)((existing_info->expires - now) / 60)); CloseDB(dbp); + free(existing_info); free(key); free(new_info); return; } + else if (policy == CONTEXT_STATE_POLICY_RESET) + { + Log(LOG_LEVEL_VERBOSE, + "Resetting persistent class '%s' timer to %u minutes (was %jd minutes remaining)", + key, ttl_minutes, (intmax_t)((existing_info->expires - now) / 60)); + } + else + { + Log(LOG_LEVEL_VERBOSE, + "Updating persistent class '%s' (%u minutes, policy preserve)", + key, ttl_minutes); + } } else { Log(LOG_LEVEL_ERR, "While persisting class '%s', error reading existing value", key); CloseDB(dbp); + free(existing_info); free(key); free(new_info); return; } + free(existing_info); + } + else + { + Log(LOG_LEVEL_VERBOSE, + "Creating persistent class '%s' (%u minutes, policy %s)", + key, ttl_minutes, + policy == CONTEXT_STATE_POLICY_PRESERVE ? "preserve" : "reset"); } } - Log(LOG_LEVEL_VERBOSE, "Updating persistent class '%s'", key); - WriteDB(dbp, key, new_info, new_info_size); CloseDB(dbp); diff --git a/libpromises/evalfunction.c b/libpromises/evalfunction.c index 2e925c03fa..d9030b1eda 100644 --- a/libpromises/evalfunction.c +++ b/libpromises/evalfunction.c @@ -1121,7 +1121,7 @@ static FnCallResult FnCallGetUserInfo(ARG_UNUSED EvalContext *ctx, ARG_UNUSED co char *arg = RlistScalarValue(finalargs); if (StringIsNumeric(arg)) { - uid_t uid = Str2Uid(arg, NULL, NULL); + uid_t uid = Str2Uid(arg, NULL, 0, NULL); if (uid == CF_SAME_OWNER) // user "*" { uid = getuid(); @@ -1811,7 +1811,7 @@ static bool GetLegacyPackagesMatching(Regex *matcher, JsonElement *json, const b "Cannot open the %s packages inventory '%s' - " "This is not necessarily an error. " "Either the inventory policy has not been included, " - "or it has not had time to have an effect yet or you are using" + "or it has not had time to have an effect yet or you are using " "new package promise and check for legacy promise is made." "A future call may still succeed. (fopen: %s)", installed_mode ? "installed" : "available", @@ -2742,9 +2742,9 @@ static FnCallResult FnCallUrlGet(ARG_UNUSED EvalContext *ctx, Buffer *content = BufferNew(); Buffer *headers = BufferNew(); curl_easy_setopt(curl, CURLOPT_URL, url); - curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); // do not use signals + curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L); // do not use signals curl_easy_setopt(curl, CURLOPT_TIMEOUT, 3L); // set default timeout - curl_easy_setopt(curl, CURLOPT_VERBOSE, 0); + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curl, CURLOPT_PROTOCOLS_STR, // Allowed protocols @@ -5730,6 +5730,14 @@ static FnCallResult FnCallFormat(EvalContext *ctx, ARG_UNUSED const Policy *poli static FnCallResult FnCallIPRange(EvalContext *ctx, ARG_UNUSED const Policy *policy, const FnCall *fp, const Rlist *finalargs) { + assert(fp != NULL); + + if (finalargs == NULL) + { + Log(LOG_LEVEL_ERR, "Function '%s' requires at least one argument", fp->name); + return FnFailure(); + } + const char *range = RlistScalarValue(finalargs); const Rlist *ifaces = finalargs->next; @@ -5794,6 +5802,14 @@ static FnCallResult FnCallIsIpInSubnet(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, const FnCall *fp, const Rlist *finalargs) { + assert(fp != NULL); + + if (finalargs == NULL) + { + Log(LOG_LEVEL_ERR, "Function '%s' requires at least one argument", fp->name); + return FnFailure(); + } + const char *range = RlistScalarValue(finalargs); const Rlist *ips = finalargs->next; @@ -6911,6 +6927,12 @@ static FnCallResult FnCallEval(EvalContext *ctx, ARG_UNUSED const Policy *policy static FnCallResult FnCallReadFile(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Policy *policy, ARG_UNUSED const FnCall *fp, const Rlist *finalargs) { + if (finalargs == NULL) + { + Log(LOG_LEVEL_ERR, "Function 'readfile' requires at least one argument"); + return FnFailure(); + } + char *filename = RlistScalarValue(finalargs); const Rlist *next = finalargs->next; // max_size argument, default to inf: long maxsize = next ? IntFromString(RlistScalarValue(next)) : IntFromString("inf"); @@ -7374,9 +7396,8 @@ static FnCallResult FnCallClassFilterCsv(EvalContext *ctx, } else { - size_t const key_len = PRINTSIZE(size_t); - char key[key_len]; - xsnprintf(key, key_len, "%zu", i); + char key[PRINTSIZE(size_t)]; + xsnprintf(key, PRINTSIZE(size_t), "%zu", i); JsonObjectAppendString(class_container, key, @@ -8107,7 +8128,7 @@ FnCallResult FnCallUserExists(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Poli if (StringIsNumeric(arg)) { - uid_t uid = Str2Uid(arg, NULL, NULL); + uid_t uid = Str2Uid(arg, NULL, 0, NULL); if (uid == CF_SAME_OWNER || uid == CF_UNKNOWN_OWNER) { return FnFailure(); @@ -8134,7 +8155,7 @@ FnCallResult FnCallGroupExists(ARG_UNUSED EvalContext *ctx, ARG_UNUSED const Pol if (StringIsNumeric(arg)) { - gid_t gid = Str2Gid(arg, NULL, NULL); + gid_t gid = Str2Gid(arg, NULL, 0, NULL); if (gid == CF_SAME_GROUP || gid == CF_UNKNOWN_GROUP) { return FnFailure(); @@ -8510,7 +8531,7 @@ struct IsReadableThreadData pthread_cond_t cond; pthread_mutex_t mutex; const char *path; - FnCallResult result; + bool success; }; static void *IsReadableThreadRoutine(void *data) @@ -8527,7 +8548,7 @@ static void *IsReadableThreadRoutine(void *data) GetErrorStrFromCode(ret)); } - thread_data->result = FnReturnContext(false); + thread_data->success = false; // Allow main thread to require lock on pthread_cond_timedwait(3) ret = pthread_mutex_unlock(&thread_data->mutex); @@ -8552,7 +8573,7 @@ static void *IsReadableThreadRoutine(void *data) else { close(fd); - thread_data->result = FnReturnContext(true); + thread_data->success = true; } ret = pthread_cond_signal(&(thread_data->cond)); @@ -8654,13 +8675,13 @@ static FnCallResult FnCallIsReadable(ARG_UNUSED EvalContext *const ctx, return FnFailure(); } - FnCallResult result; + bool success = false; // Wait on thread to finish or timeout ret = ThreadWait(&thread_data.cond, &thread_data.mutex, timeout); switch (ret) { case 0: // Thread finished in time - result = thread_data.result; + success = thread_data.success; break; case ETIMEDOUT: // Thread timed out @@ -8674,8 +8695,6 @@ static FnCallResult FnCallIsReadable(ARG_UNUSED EvalContext *const ctx, Log(LOG_LEVEL_ERR, "Failed to cancel thread"); return FnFailure(); } - - result = FnReturnContext(false); break; default: @@ -8705,7 +8724,7 @@ static FnCallResult FnCallIsReadable(ARG_UNUSED EvalContext *const ctx, Log(LOG_LEVEL_DEBUG, "Thread was canceled"); } - return result; + return FnReturnContext(success); } /*********************************************************************/ @@ -10289,6 +10308,9 @@ static const FnCallArg DATATYPE_ARGS[] = /* see fncall.h enum FnCallType */ +/* In evalfunction_test.c we both include this file and link with libpromises. + * This guard makes sure we don't get a duplicate definition of this symbol */ +#ifndef CFENGINE_EVALFUNCTION_TEST_C const FnCallType CF_FNCALL_TYPES[] = { FnCallTypeNew("accessedbefore", CF_DATA_TYPE_CONTEXT, ACCESSEDBEFORE_ARGS, &FnCallIsAccessedBefore, "True if arg1 was accessed before arg2 (atime)", @@ -10693,3 +10715,4 @@ const FnCallType CF_FNCALL_TYPES[] = FnCallTypeNewNull() }; +#endif // CFENGINE_EVALFUNCTION_TEST_C diff --git a/libpromises/generic_agent.c b/libpromises/generic_agent.c index 4b4b132fa7..c8da79370c 100644 --- a/libpromises/generic_agent.c +++ b/libpromises/generic_agent.c @@ -1470,7 +1470,15 @@ bool GenericAgentArePromisesValid(const GenericAgentConfig *config) if (!ShellCommandReturnsZero(cmd, true)) { - Log(LOG_LEVEL_ERR, "Policy failed validation with command '%s'", cmd); + if (IsPendingTermination()) + { + Log(LOG_LEVEL_VERBOSE, + "Policy validation aborted due to termination signal"); + } + else + { + Log(LOG_LEVEL_ERR, "Policy failed validation with command '%s'", cmd); + } return false; } diff --git a/libpromises/lastseen.c b/libpromises/lastseen.c index 0dc7bdc295..34f848e6cd 100644 --- a/libpromises/lastseen.c +++ b/libpromises/lastseen.c @@ -121,7 +121,10 @@ void UpdateLastSawHost(const char *hostkey, const char *address, char quality_key[CF_BUFSIZE]; snprintf(quality_key, CF_BUFSIZE, "q%c%s", incoming ? 'i' : 'o', hostkey); - KeyHostSeen newq = { .lastseen = timestamp }; + KeyHostSeen newq = { + .acknowledged = false, + .lastseen = timestamp, + }; KeyHostSeen q; if (ReadDB(db, quality_key, &q, sizeof(q))) @@ -763,3 +766,54 @@ int RemoveKeysFromLastSeen(const char *input, bool must_be_coherent, return 0; } + +static bool OnlyRewriteIfChanged(KeyHostSeen *entry, ARG_UNUSED size_t size, KeyHostSeen *new) +{ + assert(entry != NULL); + assert(new != NULL); + + if (entry->acknowledged) + { + return false; + } + + new->acknowledged = true; + new->lastseen = entry->lastseen; + new->Q = entry->Q; + + return true; +} + +bool LastSeenHostAcknowledge(const char *host_key, bool incoming) +{ + DBHandle *db = NULL; + if (!OpenDB(&db, dbid_lastseen)) + { + Log(LOG_LEVEL_ERR, "Unable to open lastseen DB"); + return false; + } + + // Update quality-of-connection entry + char key[CF_BUFSIZE]; + NDEBUG_UNUSED int ret = snprintf(key, CF_BUFSIZE, "q%c%s", incoming ? 'i' : 'o', host_key); + assert(ret > 0 && ret < CF_BUFSIZE); + + KeyHostSeen value; + value.lastseen = 0; /* To distinguish between entry not found and error */ + if (OverwriteDB(db, key, &value, sizeof(value), (OverwriteCondition)OnlyRewriteIfChanged, &value)) + { + Log(LOG_LEVEL_DEBUG, "Acknowledged observation of key '%s' to lastseen DB", key); + } + else if (value.lastseen != 0 /* was found */ && + !value.acknowledged /* should update */) + { + /* In this case, the entry was found and should have been updated. + * However, false was returned. Hence, this must be due to error. */ + Log(LOG_LEVEL_ERR, "Unable to overwrite key '%s' to lastseen DB", key); + CloseDB(db); + return false; + } + + CloseDB(db); + return true; +} diff --git a/libpromises/lastseen.h b/libpromises/lastseen.h index 7fb4878ba9..786c2cb5ed 100644 --- a/libpromises/lastseen.h +++ b/libpromises/lastseen.h @@ -29,6 +29,7 @@ typedef struct { + bool acknowledged; // True when acknowledged by cf-hub, false when updated time_t lastseen; QPoint Q; // Average time between connections (rolling weighted average) } KeyHostSeen; @@ -62,4 +63,12 @@ bool IsLastSeenCoherent(void); int RemoveKeysFromLastSeen(const char *input, bool must_be_coherent, char *equivalent, size_t equivalent_size); +/** + * @brief Acknowledge that lastseen host entry is observed. + * @param host_key The host key of the lastseen entry. + * @param incoming Whether it is an incoming or outgoing entry. + * @return true if host entry was successfully acknowledged, otherwise false. + */ +bool LastSeenHostAcknowledge(const char *host_key, bool incoming); + #endif diff --git a/libpromises/locks.c b/libpromises/locks.c index ae408fab21..fb0ff0392e 100644 --- a/libpromises/locks.c +++ b/libpromises/locks.c @@ -84,7 +84,7 @@ static CfLockStack *LOCK_STACK = NULL; static void PushLock(char *lock, char *last) { - CfLockStack *new_lock = malloc(sizeof(CfLockStack)); + CfLockStack *new_lock = xmalloc(sizeof(CfLockStack)); strlcpy(new_lock->lock, lock, CF_BUFSIZE); strlcpy(new_lock->last, last, CF_BUFSIZE); diff --git a/libpromises/matching.c b/libpromises/matching.c index 6351cc2608..6051e5d9f0 100644 --- a/libpromises/matching.c +++ b/libpromises/matching.c @@ -50,6 +50,16 @@ static char *FirstBackReference(Regex *regex, const char *teststring) * negative numbers are errors (incl. no match). */ if (result > 0) { + uint32_t num_pairs = pcre2_get_ovector_count(match_data); + if (num_pairs <= 1) + { + /* There was no match */ + strlcpy(backreference, "CF_NOMATCH", CF_MAXVARSIZE); + pcre2_match_data_free(match_data); + RegexDestroy(regex); + return backreference; + } + size_t *ovector = pcre2_get_ovector_pointer(match_data); /* ovector[0] and ovector[1] are for the start and end of the whole * match, the capture groups follow in [2] and [3], etc. */ diff --git a/libpromises/mod_common.c b/libpromises/mod_common.c index a923fb6f2b..9cb4363732 100644 --- a/libpromises/mod_common.c +++ b/libpromises/mod_common.c @@ -226,6 +226,7 @@ const ConstraintSyntax CF_CLASSBODY[] = ConstraintSyntaxNewContext("not", "Evaluate the negation of string expression in normal form", SYNTAX_STATUS_NORMAL), ConstraintSyntaxNewContextList("select_class", "Select one of the named list of classes to define based on host identity. Default value: random_selection", SYNTAX_STATUS_NORMAL), ConstraintSyntaxNewContextList("xor", "Combine class sources with XOR", SYNTAX_STATUS_NORMAL), + ConstraintSyntaxNewOption("timer_policy", "absolute,reset", "Whether a persistent class restarts its counter when rediscovered. Default value: absolute", SYNTAX_STATUS_NORMAL), ConstraintSyntaxNewNull() }; diff --git a/libpromises/mod_custom.c b/libpromises/mod_custom.c index 36ddc954a7..9f94b0e6d7 100644 --- a/libpromises/mod_custom.c +++ b/libpromises/mod_custom.c @@ -1199,6 +1199,11 @@ static void PromiseModule_Terminate_untyped(void *data) void TerminateCustomPromises(void) { + if (custom_modules == NULL) + { + return; + } + MapIterator iter = MapIteratorInit(custom_modules); for (const MapKeyValue *item = MapIteratorNext(&iter); item != NULL; item = MapIteratorNext(&iter)) diff --git a/libpromises/ornaments.c b/libpromises/ornaments.c index ca37e98d88..d43c7c56ff 100644 --- a/libpromises/ornaments.c +++ b/libpromises/ornaments.c @@ -156,7 +156,7 @@ void PromiseBanner(EvalContext *ctx, const Promise *pp) } const size_t n = 2*CF_MAXFRAGMENT + 3; - char pretty_promise_name[n+1]; + char *pretty_promise_name = alloca(n+1); pretty_promise_name[0] = '\0'; StringAppendAbbreviatedPromise(pretty_promise_name, pp->promiser, n, CF_MAXFRAGMENT); Log(LOG_LEVEL_VERBOSE, "P: Promiser/affected object: '%s'", pretty_promise_name); diff --git a/libpromises/policy.c b/libpromises/policy.c index 4a9b553d27..2e5754e999 100644 --- a/libpromises/policy.c +++ b/libpromises/policy.c @@ -2931,7 +2931,6 @@ uid_t PromiseGetConstraintAsUid(const EvalContext *ctx, const char *lval, const uid_t PromiseGetConstraintAsUid(const EvalContext *ctx, const char *lval, const Promise *pp) { int retval = CF_SAME_OWNER; - char buffer[CF_MAXVARSIZE]; const Constraint *cp = PromiseGetConstraint(pp, lval); if (cp) @@ -2945,7 +2944,7 @@ uid_t PromiseGetConstraintAsUid(const EvalContext *ctx, const char *lval, const FatalError(ctx, "Aborted"); } - retval = Str2Uid((char *) cp->rval.item, buffer, pp); + retval = Str2Uid((char *) cp->rval.item, NULL, 0, pp); } return retval; @@ -2973,7 +2972,6 @@ gid_t PromiseGetConstraintAsGid(const EvalContext *ctx, char *lval, const Promis gid_t PromiseGetConstraintAsGid(const EvalContext *ctx, char *lval, const Promise *pp) { int retval = CF_SAME_GROUP; - char buffer[CF_MAXVARSIZE]; const Constraint *cp = PromiseGetConstraint(pp, lval); if (cp) @@ -2987,7 +2985,7 @@ gid_t PromiseGetConstraintAsGid(const EvalContext *ctx, char *lval, const Promis FatalError(ctx, "Aborted"); } - retval = Str2Gid((char *) cp->rval.item, buffer, pp); + retval = Str2Gid((char *) cp->rval.item, NULL, 0, pp); } return retval; diff --git a/libpromises/processes_select.c b/libpromises/processes_select.c index 3f14114ca6..aa815bba2d 100644 --- a/libpromises/processes_select.c +++ b/libpromises/processes_select.c @@ -718,6 +718,17 @@ static bool SplitProcLine(const char *line, Take these two examples: +Windows: + User field can contain spaces. E.g.: + + USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND + NETWORK SERVICE 540 0.0 0.3 5092 11180 ? ? Apr28 00:00 C:\\Windows\\system32\\svchost.exe -k RPCSS -p + etc. + + There is really no good way to do this with the current parsing logic. We + know that the next field will be a PID, so we can parse until we find a + number. + AIX: USER PID PPID PGID %CPU %MEM VSZ NI S STIME TIME COMMAND root 1 0 0 0.0 0.0 784 20 A Nov 28 00:00:00 /etc/init @@ -831,6 +842,7 @@ Solaris 9: bool cmd = (strcmp(names[field], "CMD") == 0 || strcmp(names[field], "COMMAND") == 0); bool stime = !cmd && (strcmp(names[field], "STIME") == 0); + bool is_user_field = StringEqual(names[field], "USER"); // Equal boolean results, either both must be true, or both must be // false. IOW we must either both be at the last field, and it must be @@ -921,6 +933,41 @@ Solaris 9: last++; } } + else if (is_user_field) + { + bool done = false; + while (!done) + { + while (line[last] != '\0' && !isspace(line[last])) + { + last++; + } + + /* On windows the USER field can contain spaces. We know that + * the next field will be PID. Hence, we seek past the spaces + * to see if the next thing is a number. If this is not the + * case, we assume it is still the USER field. This is not + * bulletproof. However, this parser never was. */ + int seek_past = last; + while (line[seek_past] != '\0' && isspace(line[seek_past])) + { + seek_past++; + } + + if (line[seek_past] == '\0') + { + done = true; + } + else if (isdigit(line[seek_past])) + { + done = true; + } + else + { + last = seek_past; + } + } + } else { // Generic fields diff --git a/libpromises/promises.c b/libpromises/promises.c index 4c917ef581..9e955f5496 100644 --- a/libpromises/promises.c +++ b/libpromises/promises.c @@ -705,16 +705,31 @@ Promise *ExpandDeRefPromise(EvalContext *ctx, const Promise *pp, bool *excluded) pcopy->org_pp = pp->org_pp; // if this is a class promise, check if it is already set, if so, skip + // Exception: persistent classes with timer_policy => "reset" must not + // be skipped — the promise needs to fire so the timer gets reset. if (strcmp("classes", PromiseGetPromiseType(pp)) == 0) { if (IsDefinedClass(ctx, CanonifyName(pcopy->promiser))) { - Log(LOG_LEVEL_DEBUG, - "Skipping evaluation of classes promise as class '%s' is already set", - CanonifyName(pcopy->promiser)); + const char *tp = PromiseGetConstraintAsRval(pp, "timer_policy", RVAL_TYPE_SCALAR); + int persistence = PromiseGetConstraintAsInt(ctx, "persistence", pp); - *excluded = true; - return pcopy; + if (StringEqual(tp, "reset") && persistence > 0) + { + Log(LOG_LEVEL_DEBUG, + "Class '%s' is already set but timer_policy is reset" + " — allowing promise evaluation to reset persistence timer", + CanonifyName(pcopy->promiser)); + } + else + { + Log(LOG_LEVEL_DEBUG, + "Skipping evaluation of classes promise as class '%s' is already set", + CanonifyName(pcopy->promiser)); + + *excluded = true; + return pcopy; + } } } diff --git a/libpromises/storage_tools.c b/libpromises/storage_tools.c index db25598900..8849e305e2 100644 --- a/libpromises/storage_tools.c +++ b/libpromises/storage_tools.c @@ -22,6 +22,8 @@ included file COSL.txt. */ +#include + #include #ifdef HAVE_SYS_STATFS_H diff --git a/libpromises/syslog_client.c b/libpromises/syslog_client.c index 0b68048c56..0b55a0cc91 100644 --- a/libpromises/syslog_client.c +++ b/libpromises/syslog_client.c @@ -27,6 +27,8 @@ #include + +#define RFC3164_LENGTH 1024 /* * Set by cf-agent/cf-serverd from body agent/server control. */ @@ -112,8 +114,7 @@ void RemoteSysLog(int log_priority, const char *log_string) } else { - const size_t rfc3164_len = 1024; - char message[rfc3164_len]; + char message[RFC3164_LENGTH]; char timebuffer[26]; pid_t pid = getpid(); diff --git a/libpromises/unix.c b/libpromises/unix.c index bef9389df8..9fb882d643 100644 --- a/libpromises/unix.c +++ b/libpromises/unix.c @@ -25,6 +25,8 @@ #include #include #include +#include /* IsPendingTermination() */ +#include /* StringToInt64() */ #ifdef HAVE_SYS_UIO_H # include @@ -226,12 +228,48 @@ bool ShellCommandReturnsZero(const char *command, ShellType shell) { ALARM_PID = pid; - while (waitpid(pid, &status, 0) < 0) + /* Poll for the child instead of blocking in waitpid(). signal() on + * Linux/glibc installs handlers with SA_RESTART, so SIGTERM does not + * interrupt a blocking waitpid() and PENDING_TERMINATION is never + * observed until the child exits on its own. With WNOHANG we get + * control back between iterations and can react to a pending + * termination (e.g. a stuck cf-promises during policy validation + * keeping the daemon unresponsive to SIGTERM). nanosleep() is + * interruptible regardless of SA_RESTART, so SIGTERM wakes us up + * promptly. */ + while (true) { - if (errno != EINTR) + pid_t wait_result = waitpid(pid, &status, WNOHANG); + if (wait_result == pid) { + break; /* child exited and was reaped */ + } + if (wait_result < 0) + { + if (errno == EINTR) + { + continue; + } return false; } + /* wait_result == 0: child is still running */ + if (IsPendingTermination()) + { + Log(LOG_LEVEL_VERBOSE, + "Termination pending; aborting child '%s' (pid %jd)", + command, (intmax_t) pid); + ProcessSignalTerminate(pid); + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) + { + /* Child has been signalled; just reap it. */ + } + return false; + } + struct timespec poll_interval = { + .tv_sec = 0, + .tv_nsec = 100000000 /* 100 ms */ + }; + nanosleep(&poll_interval, NULL); } return (WEXITSTATUS(status) == 0); @@ -527,4 +565,45 @@ bool GetGroupID(const char *group_name, gid_t *gid, LogLevel error_log_level) return true; } +const char* GetRelocatedProcdirRoot() +{ + const char *procdir = getenv("CFENGINE_TEST_OVERRIDE_PROCDIR"); + if (procdir == NULL) + { + procdir = ""; + } + else + { + Log(LOG_LEVEL_VERBOSE, "Overriding /proc location to be %s", procdir); + } + + return procdir; +} + +/** + * With the addition of using the current PID when examining the proc filesystem for details + * we need a test-override option for acceptance tests. + */ +int GetProcdirPid() +{ + const char *procpid = getenv("CFENGINE_TEST_OVERRIDE_PROCPID"); + if (procpid != NULL) + { + int64_t pid_int; + int rc; + rc = StringToInt64(procpid, &pid_int); + if (rc != 0) + { + Log(LOG_LEVEL_ERR, "Could not parse CFENGINE_TEST_OVERRIDE_PROCPID '%s' as integer: '%s'", procpid, strerror(errno)); + } + else + { + Log(LOG_LEVEL_VERBOSE, "Overriding proc pid from env var CFENGINE_TEST_OVERRIDE_PROCPID with value %jd", (intmax_t) pid_int); + return (int) pid_int; + } + } + return (int) getpid(); +} + + #endif /* !__MINGW32__ */ diff --git a/libpromises/unix.h b/libpromises/unix.h index fbad097d14..0a10a83024 100644 --- a/libpromises/unix.h +++ b/libpromises/unix.h @@ -33,6 +33,17 @@ void ProcessSignalTerminate(pid_t pid); bool GetCurrentUserName(char *userName, int userNameLen); #ifndef __MINGW32__ +/** + * @brief For testing things against /proc, uses env var CFENGINE_TEST_OVERRIDE_PROCDIR + * @return the extra directory to add BEFORE /proc in the path + */ +const char* GetRelocatedProcdirRoot(); +/** + * @brief For testing things against /proc, use env var CFENGINE_TEST_OVERRIDE_PROCPID + * @return the fake pid to use in proc paths + */ +int GetProcdirPid(); + /** * Get user name for the user with UID #uid * diff --git a/libpromises/verify_classes.c b/libpromises/verify_classes.c index 7f903e2eb6..afb70fff9d 100644 --- a/libpromises/verify_classes.c +++ b/libpromises/verify_classes.c @@ -73,8 +73,48 @@ PromiseResult VerifyClassPromise(EvalContext *ctx, const Promise *pp, ARG_UNUSED return PROMISE_RESULT_FAIL; } - if (a.context.expression == NULL || - EvalClassExpression(ctx, a.context.expression, pp)) + /* timer_policy only governs the persistence timer, so it is meaningless + * without 'persistence'. Error rather than silently ignoring it. */ + if (a.context.persistent <= 0 && + PromiseGetConstraintAsRval(pp, "timer_policy", RVAL_TYPE_SCALAR) != NULL) + { + cfPS(ctx, LOG_LEVEL_ERR, PROMISE_RESULT_FAIL, pp, &a, + "Cannot use 'timer_policy' without 'persistence' in classes promise for '%s'", + pp->promiser); + return PROMISE_RESULT_FAIL; + } + + bool class_expression_true = + (a.context.expression == NULL || + EvalClassExpression(ctx, a.context.expression, pp)); + + /* When a persistent class is already defined (loaded from DB), + * EvalClassExpression short-circuits and returns false. If the + * timer_policy is "reset", we still need to reset the persistence + * timer in the DB even though the class is already in the context. */ + if (!class_expression_true && + a.context.persistent > 0 && + a.context.timer == CONTEXT_STATE_POLICY_RESET && + IsDefinedClass(ctx, pp->promiser)) + { + StringSet *tags = StringSetNew(); + StringSetAdd(tags, xstrdup("source=promise")); + for (const Rlist *rp = PromiseGetConstraintAsList(ctx, "meta", pp); rp; rp = rp->next) + { + StringSetAdd(tags, xstrdup(RlistScalarValue(rp))); + } + Log(LOG_LEVEL_VERBOSE, + "C: + Resetting persistent class timer: '%s' (%d minutes)", + pp->promiser, a.context.persistent); + Buffer *buf = StringSetToBuffer(tags, ','); + EvalContextHeapPersistentSave(ctx, pp->promiser, a.context.persistent, + CONTEXT_STATE_POLICY_RESET, BufferData(buf)); + BufferDestroy(buf); + StringSetDestroy(tags); + return PROMISE_RESULT_NOOP; + } + + if (class_expression_true) { if (a.context.expression == NULL) { @@ -131,7 +171,7 @@ PromiseResult VerifyClassPromise(EvalContext *ctx, const Promise *pp, ARG_UNUSED pp->promiser, a.context.persistent); Buffer *buf = StringSetToBuffer(tags, ','); EvalContextHeapPersistentSave(ctx, pp->promiser, a.context.persistent, - CONTEXT_STATE_POLICY_RESET, BufferData(buf)); + a.context.timer, BufferData(buf)); BufferDestroy(buf); } if (inserted && (comment != NULL)) diff --git a/m4/cf3_with_library.m4 b/m4/cf3_with_library.m4 index ee47d7d11d..dde7181dfb 100644 --- a/m4/cf3_with_library.m4 +++ b/m4/cf3_with_library.m4 @@ -84,7 +84,8 @@ AC_DEFUN([CF3_WITH_LIBRARY], if test "x$with_[$1]" != xyes && test "x$with_[$1]" != xcheck && test "x$with_[$1]" != x/usr && - test "x$with_[$1]" != x/ + test "x$with_[$1]" != x/ && + test -n "$with_[$1]" then ULN[]_LDFLAGS="$ULN[]_LDFLAGS -R$with_[$1]/lib" fi diff --git a/m4/snprintf.m4 b/m4/snprintf.m4 index eb16c7f8f9..85bd421965 100644 --- a/m4/snprintf.m4 +++ b/m4/snprintf.m4 @@ -135,7 +135,9 @@ AC_DEFUN([HW_FUNC_VSNPRINTF], return 1;]])], [hw_cv_func_vsnprintf_c99=yes], [hw_cv_func_vsnprintf_c99=no], - [hw_cv_func_vsnprintf_c99=no])])], + [AS_CASE([$host_os], + [mingw*], [hw_cv_func_vsnprintf_c99=yes], + [hw_cv_func_vsnprintf_c99=no])])])], [hw_cv_func_snprintf_c99=no]) AS_IF( [test "$hw_cv_func_vsnprintf_c99" = yes], @@ -178,7 +180,9 @@ AC_DEFUN([HW_FUNC_SNPRINTF], return 1;]])], [hw_cv_func_snprintf_c99=yes], [hw_cv_func_snprintf_c99=no], - [hw_cv_func_snprintf_c99=no])])], + [AS_CASE([$host_os], + [mingw*], [hw_cv_func_snprintf_c99=yes], + [hw_cv_func_snprintf_c99=no])])])], [hw_cv_func_snprintf_c99=no]) AS_IF( [test "$hw_cv_func_snprintf_c99" = yes], diff --git a/misc/cf-support b/misc/cf-support index 1d3ae96af3..a2270d31ca 100755 --- a/misc/cf-support +++ b/misc/cf-support @@ -120,7 +120,7 @@ make_temp_dir() else # shellcheck disable=SC2021 # ^^ legacy/POSIX requires square brackets - _tmp="/tmp/`tr -dc "[A-Z][a-z][0-9]" /dev/null`" mkdir "$_tmp" echo "$_tmp" fi @@ -150,11 +150,18 @@ mkdir -p "$tmpdir" echo "Analyzing CFEngine core dumps" _core_log="$tmpdir"/core-dump.log -_sysctl_kernel_core_pattern="$(sysctl -n kernel.core_pattern)" +if command -v sysctl >/dev/null; then + _sysctl_kernel_core_pattern="$(sysctl -n kernel.core_pattern)" +else + _sysctl_kernel_core_pattern="" +fi if expr "$_sysctl_kernel_core_pattern" : ".*/systemd-coredump.*" > /dev/null 2>&1; then echo "Found systemd-coredump used in sysctl kernel.core_pattern \"$_sysctl_kernel_core_pattern\"" echo "Using coredumpctl to analyze CFEngine core dumps" - coredumpctl info /var/cfengine/bin/cf-* 2>/dev/null >> "$_core_log" || true + find /var/cfengine -type f -executable | while IFS='' read -r line + do + coredumpctl info "$line" 2>/dev/null >> "$_core_log" || true + done elif command -v apport-unpack >/dev/null; then echo "Using apport-unpack to analyze CFEngine core dumps" # each crash report has a line with ExecutablePath: which tells us if it is a CFEngine core dump @@ -190,17 +197,20 @@ else if [ "$OS" != "solaris" ]; then if ! command -v gdb >/dev/null; then echo "Please install gdb. This is required in order to analyze core dumps." - exit 1 + echo "Core dumps needing to be analyzed will be listed below:" fi fi for core_file in $cf_core_files; do file "$core_file" >> "$_core_log" if [ "$OS" = "solaris" ]; then pstack "$core_file" >> "$_core_log" 2>&1 - else + elif command -v gdb >/dev/null; then execfn=`file "$core_file" | sed 's/,/\n/g' | grep execfn | cut -d: -f2 | sed "s/[' ]//g"` exe="`realpath "$execfn"`" gdb "$exe" --core="$core_file" -batch -ex "thread apply all bt full" >> "$_core_log" 2>&1 + else + # shellcheck disable=SC2012 + ls -l "$core_file" | tee "$_core_log" fi done fi @@ -380,10 +390,30 @@ else fi echo "Captured output of $syslog_cmd filtered for cf-|CFEngine" +# cf- component related SELinux denials +if command -v ausearch >/dev/null; then + ausearch -m avc -su cfengine > "$tmpdir"/ausearch-cfengine-avcs.log +fi + gzip_add $WORKDIR/outputs/previous gzip_add $WORKDIR/outputs/dc-scripts.log # masterfiles-stage log +# Collect up to the two most recent standalone_self_upgrade logs (separate cf-agent process) +su_logs=$(find $WORKDIR/outputs/ -name 'standalone_self_upgrade*' -type f -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -2 | cut -d' ' -f2-) +for f in $su_logs; do + gzip_add "$f" +done file_add $WORKDIR/policy_server.dat +# Collect client-side report dumps from /var/cfengine/diagnostics +if [ -d "$WORKDIR/diagnostics" ]; then + echo "Collecting diagnostics directory (includes report_dumps)..." + mkdir -p "$tmpdir/diagnostics" + cp -a "$WORKDIR/diagnostics/." "$tmpdir/diagnostics/" + echo "Added diagnostics directory (includes report_dumps)" +else + echo "diagnostics directory not found, skipping" +fi + if [ -f $WORKDIR/share/cf-support-nova-hub.sh ]; then # shellcheck source=/dev/null . $WORKDIR/share/cf-support-nova-hub.sh diff --git a/misc/changelog-generator/changelog-generator b/misc/changelog-generator/changelog-generator index cef3137f79..8e5f310740 100755 --- a/misc/changelog-generator/changelog-generator +++ b/misc/changelog-generator/changelog-generator @@ -189,7 +189,7 @@ for repo in repos: del ENTRIES[linked_sha] continue - match = re.match("^\(cherry picked from commit ([0-9a-f]+)\)", line, re.IGNORECASE) + match = re.match(r"^\(cherry picked from commit ([0-9a-f]+)\)", line, re.IGNORECASE) if match: if log_entry: add_entry(sha, log_entry) @@ -254,12 +254,12 @@ for sha_entry in ENTRIES: if SORT_CHANGELOG: entry_list.sort() for entry in entry_list: - entry = "\t- " + entry + entry = "- " + entry # Blank lines look bad in changelog because entries don't have blank lines # between them, so remove that from commit messages. entry = re.sub("\n\n+", "\n", entry) - # Indent all lines. - entry = entry.replace("\n", "\n\t ") + # Indent continuation lines to align with the bullet text. + entry = entry.replace("\n", "\n ") print(entry) for missed in POSSIBLE_MISSED_TICKETS: diff --git a/misc/init.d/cf-php-fpm.in b/misc/init.d/cf-php-fpm.in new file mode 100644 index 0000000000..7d217655a2 --- /dev/null +++ b/misc/init.d/cf-php-fpm.in @@ -0,0 +1,35 @@ +#! /bin/sh +# copied from /etc/init.d/procps written by Elrond +# kFreeBSD do not accept scripts as interpreters, using #!/bin/sh and sourcing. +if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then + set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script +fi +### BEGIN INIT INFO +# Provides: cf-php-fpm +# Required-Start: +# Required-Stop: +# Should-Start: +# X-Start-Before: +# Default-Start: S +# Default-Stop: +# Short-Description: Start CFEngine Mission Portal php-fpm service +# Description: CFEngine Enterprise PHP FastCGI Process Manager +### END INIT INFO + +# shellcheck disable=SC2034 +DESC=cf-php-fpm +PREFIX=${CFTEST_PREFIX:-@workdir@} +DAEMON=$PREFIX/httpd/php/sbin/php-fpm +PIDFILE=$PREFIX/httpd/php-fpm.pid + +do_start_cmd() { + STATUS=0 + "$DAEMON" --pid "$PIDFILE" --force-stderr || STATUS="$?" + return $STATUS +} + +do_stop_cmd() { + if [ -f "$PIDFILE" ]; then + kill -9 "-$(cat "$PIDFILE")" + fi +} diff --git a/misc/init.d/cfengine3.in b/misc/init.d/cfengine3.in index 6017e7e212..bb320630a8 100644 --- a/misc/init.d/cfengine3.in +++ b/misc/init.d/cfengine3.in @@ -150,7 +150,7 @@ fi CURRENT_PS_UID=__none__ INSIDE_CONTAINER=-1 -if ps --help 2>/dev/null | egrep -e '--cols\b' > /dev/null || ps --help output 2>/dev/null | egrep -e '--cols\b'; then +if ps --help 2>/dev/null | egrep -e '--cols\b' > /dev/null || ps --help output 2>/dev/null | egrep -e '--cols\b' > /dev/null; then # There is a bug in SUSE which means that ps output will be truncated even # when piped to grep, if the terminal size is small. However using --cols # will override it. NOTE: On Suse 12 and 15, `ps` mentions `--cols` only diff --git a/misc/selinux/Makefile.am b/misc/selinux/Makefile.am index 870b866b30..6345683163 100644 --- a/misc/selinux/Makefile.am +++ b/misc/selinux/Makefile.am @@ -18,5 +18,6 @@ endif # tarball even without running './configure --with-selinux-policy' DISTFILES = Makefile.in Makefile.am cfengine-enterprise.fc cfengine-enterprise.te.all DISTFILES += cfengine-enterprise.te.el9 +DISTFILES += cfengine-enterprise.te.el10 CLEANFILES = cfengine-enterprise.pp cfengine-enterprise.if cfengine-enterprise.te diff --git a/misc/selinux/cfengine-enterprise.te.all b/misc/selinux/cfengine-enterprise.te.all index 228c4537f7..ad17112be5 100644 --- a/misc/selinux/cfengine-enterprise.te.all +++ b/misc/selinux/cfengine-enterprise.te.all @@ -91,87 +91,9 @@ require { type ssh_exec_t; type ssh_home_t; type rpm_script_t; - class lockdown { confidentiality integrity }; - class tcp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown name_connect accept listen name_bind node_bind }; - class mctp_socket { ioctl read write create getattr setattr lock relabelfrom relabelto append map bind connect listen accept getopt setopt shutdown recvfrom sendto recv_msg send_msg name_bind }; - class udp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown node_bind }; - class sock_file { create write getattr setattr unlink }; - class rawip_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class packet_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class unix_stream_socket { create ioctl read getattr lock write setattr append bind connect connectto getopt setopt shutdown }; - class unix_dgram_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown sendto }; - class appletalk_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_route_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown nlmsg_read getopt }; - class netlink_firewall_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_tcpdiag_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_nflog_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_xfrm_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_selinux_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_audit_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_ip6fw_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_dnrt_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_kobject_uevent_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class tun_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_iscsi_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_fib_lookup_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_connector_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_netfilter_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_generic_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_scsitransport_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_rdma_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netlink_crypto_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class sctp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class icmp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class ax25_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class ipx_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class netrom_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class atmpvc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class x25_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class xdp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class rose_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class decnet_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class atmsvc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class rds_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class irda_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class pppox_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class llc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class can_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class tipc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class bluetooth_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class iucv_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class rxrpc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class isdn_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class phonet_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class ieee802154_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class caif_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class alg_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class nfc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class vsock_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class kcm_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class qipcrtr_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class smc_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class bridge_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class dccp_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class ib_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class mpls_socket { create ioctl read getattr lock write setattr append bind connect getopt setopt shutdown }; - class process { setrlimit transition dyntransition execstack execheap execmem signull siginh getattr sigchld }; - class fd use; - class file { execute execute_no_trans getattr ioctl map open read unlink write entrypoint lock link rename append setattr create relabelfrom relabelto watch watch_reads }; - class fifo_file { create open getattr setattr read write append rename link unlink ioctl lock relabelfrom relabelto }; - class dir { getattr read search open write add_name remove_name lock ioctl create setattr rmdir }; - class filesystem getattr; - class lnk_file { create getattr read unlink }; - class capability { dac_read_search sys_module chown dac_read_search dac_override fowner fsetid sys_admin mknod net_raw net_admin sys_nice sys_rawio sys_resource setuid setgid sys_nice sys_ptrace kill net_bind_service }; - class cap_userns sys_ptrace; - class capability2 { mac_admin mac_override block_suspend syslog wake_alarm }; - class association { sendto recvfrom setcontext polmatch }; - class security setsecparam; - class service { start stop status reload enable disable }; - class system { module_request }; - class memprotect mmap_zero; - class peer recv; - class chr_file { getattr }; + type fsadm_exec_t; + type lvm_exec_t; + all_kernel_class_perms } @@ -212,6 +134,10 @@ allow cfengine_execd_t cfengine_var_lib_t:file execute; # allow cf-execd to execute cf-promises allow cfengine_execd_t cfengine_var_lib_t:file execute_no_trans; +# allow cf-promises run by cf-execd to getattr everywhere and read symlinks +files_getattr_all_dirs(cfengine_execd_t) +files_getattr_all_files(cfengine_execd_t) +files_read_all_symlinks(cfengine_execd_t) # TODO: this should not be needed allow cfengine_execd_t ssh_port_t:tcp_socket name_connect; @@ -229,6 +155,7 @@ allow cfengine_execd_t cfengine_reactor_exec_t:file getattr; allow cfengine_execd_t cfengine_var_lib_t:sock_file { create unlink getattr setattr }; allow cfengine_execd_t self:capability sys_ptrace; +allow cfengine_execd_t self:cap_userns sys_ptrace; allow cfengine_execd_t crontab_exec_t:file getattr; allow cfengine_execd_t dmidecode_exec_t:file getattr; @@ -269,6 +196,10 @@ allow cfengine_monitord_t cfengine_var_lib_t:file execute; # allow cf-monitord to execute cf-promises allow cfengine_monitord_t cfengine_var_lib_t:file execute_no_trans; +# allow cf-promises run by cf-monitord to getattr everywhere and read symlinks +files_getattr_all_dirs(cfengine_monitord_t) +files_getattr_all_files(cfengine_monitord_t) +files_read_all_symlinks(cfengine_monitord_t) allow cfengine_monitord_t cfengine_execd_exec_t:file getattr; allow cfengine_monitord_t cfengine_serverd_exec_t:file getattr; @@ -277,6 +208,9 @@ allow cfengine_monitord_t cfengine_hub_exec_t:file getattr; allow cfengine_monitord_t cfengine_reactor_exec_t:file getattr; allow cfengine_monitord_t var_log_t:file { open read }; +# cf-monitord collects arbitrary system data so needs complete access to filesystems and files +fs_unconfined(cfengine_monitord_t) +files_unconfined(cfengine_monitord_t) allow cfengine_monitord_t self:capability { dac_override dac_read_search sys_ptrace }; allow cfengine_monitord_t self:cap_userns sys_ptrace; @@ -318,13 +252,20 @@ allow cfengine_serverd_t cfengine_var_lib_t:file execute; # allow cf-serverd to execute cf-promises allow cfengine_serverd_t cfengine_var_lib_t:file execute_no_trans; +# allow cf-promises run by cf-serverd to getattr everywhere and read symlinks +files_getattr_all_dirs(cfengine_serverd_t) +files_getattr_all_files(cfengine_serverd_t) +files_read_all_symlinks(cfengine_serverd_t) # allow cf-serverd to connect to the CFEngine port and to write into a local socket (in case of # call-collect on hosts and the hub itself, respectively) allow cfengine_serverd_t unreserved_port_t:tcp_socket name_connect; -allow cfengine_serverd_t cfengine_var_lib_t:sock_file write; +allow cfengine_serverd_t cfengine_var_lib_t:sock_file { getattr write }; allow cfengine_serverd_t cfengine_hub_t:unix_stream_socket connectto; +# allow cf-serverd to set its own limits, e.g. def.control_server_maxconnections +allow cfengine_serverd_t self:capability sys_resource; + # TODO: this should not be needed allow cfengine_serverd_t ssh_port_t:tcp_socket name_connect; allow cfengine_serverd_t proc_xen_t:dir search; @@ -382,6 +323,10 @@ allow init_t cfengine_hub_t:process siginh; allow cfengine_hub_t cfengine_hub_exec_t:file entrypoint; allow cfengine_hub_t cfengine_hub_exec_t:file { ioctl read getattr lock map execute open }; +# the following file permissions for cf-hub are not needed if masterfiles includes fixes from ENT-12954 making inventory and paths standard library bundles agent instead of common. +allow cfengine_hub_t fsadm_exec_t:file getattr; +allow cfengine_hub_t lvm_exec_t:file getattr; + # allow cf-hub to use/execute libpromises.so allow cfengine_hub_t cfengine_var_lib_t:file map; allow cfengine_hub_t cfengine_var_lib_t:file execute; @@ -401,14 +346,14 @@ allow cfengine_hub_t cfengine_postgres_t:unix_stream_socket connectto; allow cfengine_hub_t unreserved_port_t:tcp_socket name_connect; allow cfengine_hub_t cfengine_log_t:dir getattr; -allow cfengine_hub_t cfengine_var_lib_t:dir { add_name getattr open read search write remove_name }; +allow cfengine_hub_t cfengine_var_lib_t:dir { add_name create getattr open read search write remove_name }; allow cfengine_hub_t cfengine_var_lib_t:file { create ioctl lock write unlink }; allow cfengine_hub_t cfengine_var_lib_t:lnk_file { getattr read }; allow cfengine_hub_t cfengine_var_lib_t:sock_file { create unlink }; allow cfengine_hub_t bin_t:file map; allow cfengine_hub_t bin_t:file { execute execute_no_trans }; -allow cfengine_hub_t cert_t:dir search; +allow cfengine_hub_t cert_t:dir { getattr open read search }; allow cfengine_hub_t cert_t:file { getattr open read }; allow cfengine_hub_t crontab_exec_t:file getattr; allow cfengine_hub_t devlog_t:lnk_file read; @@ -497,7 +442,7 @@ allow cfengine_postgres_t cfengine_var_lib_t:dir { add_name getattr open create allow cfengine_postgres_t postgresql_port_t:tcp_socket name_bind; -allow cfengine_postgres_t cert_t:dir search; +allow cfengine_postgres_t cert_t:dir { getattr open read search }; allow cfengine_postgres_t cert_t:file { getattr open read }; allow cfengine_postgres_t hugetlbfs_t:file map; allow cfengine_postgres_t hugetlbfs_t:file { read write }; @@ -559,7 +504,7 @@ allow init_t cfengine_httpd_t:process siginh; allow cfengine_httpd_t cfengine_httpd_exec_t:file entrypoint; allow cfengine_httpd_t cfengine_httpd_exec_t:file { ioctl read getattr lock map execute open }; -allow cfengine_httpd_t cert_t:dir search; +allow cfengine_httpd_t cert_t:dir { getattr open read search }; allow cfengine_httpd_t cert_t:file { getattr open read }; allow cfengine_httpd_t cert_t:lnk_file read; allow cfengine_httpd_t cfengine_httpd_exec_t:file execute_no_trans; @@ -695,6 +640,8 @@ allow cfengine_apachectl_t proc_t:file { open read }; # this is a macro invocation, the file has to be processed with # make -f /usr/share/selinux/devel/Makefile ps_process_pattern(cfengine_apachectl_t, domain) +# ps_process_pattern() above doesn't include needed sys_ptrace capability for apachectl to run 'ps' +allow cfengine_apachectl_t self:cap_userns sys_ptrace; #============= cfengine_reactor_t ============== type cfengine_reactor_t; @@ -763,7 +710,7 @@ allow cfengine_reactor_t fs_t:filesystem getattr; allow cfengine_reactor_t shell_exec_t:file map; allow cfengine_reactor_t shell_exec_t:file { execute execute_no_trans }; -allow cfengine_reactor_t cert_t:dir search; +allow cfengine_reactor_t cert_t:dir { getattr open read search }; allow cfengine_reactor_t cert_t:file { getattr open read }; allow cfengine_reactor_t cert_t:lnk_file read; @@ -791,6 +738,7 @@ allow cfengine_reactor_t postfix_spool_t:dir { add_name remove_name search write allow cfengine_reactor_t postfix_spool_t:file { create getattr open read rename setattr write }; allow cfengine_reactor_t sendmail_exec_t:file map; allow cfengine_reactor_t sendmail_exec_t:file { execute execute_no_trans open read }; +allow cfengine_reactor_t smtp_port_t:tcp_socket name_connect; #============= cfengine_action_script_t ============== @@ -857,7 +805,7 @@ allow cfengine_cfbs_t bin_t:file { map execute }; allow cfengine_cfbs_t shell_exec_t:file map; allow cfengine_cfbs_t shell_exec_t:file { execute execute_no_trans }; -allow cfengine_cfbs_t cert_t:dir search; +allow cfengine_cfbs_t cert_t:dir { getattr open read search }; allow cfengine_cfbs_t cert_t:file { getattr open read }; allow cfengine_cfbs_t cert_t:lnk_file read; allow cfengine_cfbs_t http_port_t:tcp_socket name_connect; diff --git a/misc/selinux/cfengine-enterprise.te.el10 b/misc/selinux/cfengine-enterprise.te.el10 new file mode 100644 index 0000000000..a2e5273094 --- /dev/null +++ b/misc/selinux/cfengine-enterprise.te.el10 @@ -0,0 +1,48 @@ +require { + type devpts_t; + type systemd_userdbd_runtime_t; + type systemd_userdbd_t; +} + +#============= cfengine_apachectl_t ============== +allow cfengine_apachectl_t devpts_t:dir { getattr search }; +allow cfengine_apachectl_t proc_t:file getattr; +allow cfengine_apachectl_t self:capability { dac_override dac_read_search sys_ptrace }; +allow cfengine_apachectl_t sysfs_t:dir read; +allow cfengine_apachectl_t sysfs_t:file { open read }; +allow cfengine_apachectl_t tty_device_t:chr_file getattr; +allow cfengine_apachectl_t user_devpts_t:chr_file getattr; + +# selinux-policy requires the following http_port permissions whereas 3.14.3 does not. +# these permissions are not be needed if changes from ENT-12954 to masterfiles policy move inventory from common to an agent bundle are in place. +#============= cfengine_execd_t ============== +allow cfengine_execd_t http_port_t:tcp_socket name_connect; + +#============= cfengine_httpd_t ============== +allow cfengine_httpd_t hugetlbfs_t:file { read write }; +allow cfengine_httpd_t systemd_userdbd_runtime_t:dir { open read getattr search }; +allow cfengine_httpd_t systemd_userdbd_runtime_t:lnk_file read; +allow cfengine_httpd_t systemd_userdbd_runtime_t:sock_file write; +allow cfengine_httpd_t systemd_userdbd_t:unix_stream_socket connectto; +allow cfengine_httpd_t kernel_t:unix_stream_socket connectto; + +#============= cfengine_hub_t ============== +allow cfengine_hub_t cfengine_httpd_exec_t:file getattr; +allow cfengine_hub_t sysfs_t:lnk_file read; + +#============= cfengine_postgres_t ============== +allow cfengine_postgres_t systemd_userdbd_runtime_t:dir { open read getattr search }; +allow cfengine_postgres_t systemd_userdbd_runtime_t:lnk_file read; +allow cfengine_postgres_t systemd_userdbd_runtime_t:sock_file write; +allow cfengine_postgres_t systemd_userdbd_t:unix_stream_socket connectto; +allow cfengine_postgres_t kernel_t:unix_stream_socket connectto; + +#============= cfengine_reactor_t ============== +allow cfengine_reactor_t systemd_userdbd_runtime_t:dir { open read getattr search }; +allow cfengine_reactor_t systemd_userdbd_runtime_t:lnk_file read; +allow cfengine_reactor_t systemd_userdbd_runtime_t:sock_file write; +allow cfengine_reactor_t systemd_userdbd_t:unix_stream_socket connectto; +allow cfengine_reactor_t kernel_t:unix_stream_socket connectto; + +#============= cfengine_serverd_t ============== +allow cfengine_serverd_t http_port_t:tcp_socket name_connect; diff --git a/misc/selinux/cfengine-enterprise.te.el9 b/misc/selinux/cfengine-enterprise.te.el9 index e5641ede37..14fe34b0ca 100644 --- a/misc/selinux/cfengine-enterprise.te.el9 +++ b/misc/selinux/cfengine-enterprise.te.el9 @@ -1,5 +1,6 @@ require { type systemd_userdbd_runtime_t; + type http_port_t; } # PAM module for dynamic users @@ -8,3 +9,8 @@ allow cfengine_httpd_t systemd_userdbd_runtime_t:sock_file write; allow cfengine_httpd_t kernel_t:unix_stream_socket connectto; allow cfengine_reactor_t systemd_userdbd_runtime_t:dir { getattr open read search }; allow cfengine_reactor_t systemd_userdbd_runtime_t:sock_file write; + +# selinux-policy 38.1.45 requires the following http_port permissions whereas 3.14.3 does not. +# these permissions are not be needed if changes from ENT-12954 to masterfiles policy move inventory from common to an agent bundle are in place. +allow cfengine_serverd_t http_port_t:tcp_socket name_connect; +allow cfengine_execd_t http_port_t:tcp_socket name_connect; diff --git a/misc/systemd/cf-execd.service.in b/misc/systemd/cf-execd.service.in index 66f1e235e3..6ffb1c8bba 100644 --- a/misc/systemd/cf-execd.service.in +++ b/misc/systemd/cf-execd.service.in @@ -12,5 +12,14 @@ Restart=always RestartSec=10 KillMode=process +# Drain in-flight cf-agent, so it does not pull dependencies back in after the +# stop is reported successful (as seen in ENT-14108). +ExecStopPost=/bin/sh -c 't=60; \ + while [ $$t -gt 0 ] && pgrep -x cf-agent >/dev/null 2>&1; do \ + sleep 1; \ + t=$$((t - 1)); \ + done; \ + pkill -KILL -x cf-agent >/dev/null 2>&1 || true' + [Install] WantedBy=multi-user.target diff --git a/tests/acceptance/00_basics/environment/proc-net-functions.cf b/tests/acceptance/00_basics/environment/proc-net-functions.cf index dba5dda097..6d4833d8e4 100644 --- a/tests/acceptance/00_basics/environment/proc-net-functions.cf +++ b/tests/acceptance/00_basics/environment/proc-net-functions.cf @@ -7,11 +7,35 @@ body common control ########################################################### +bundle agent init +{ + vars: + "pid_for_testing" int => "11"; + + methods: + "" usebundle => dir_sync( + "$(this.promise_dirname)/proc", + "$(G.testdir)/proc" + ); + + commands: + " +cd $(G.testdir)/proc/proc +mkdir $(pid_for_testing) +mv net $(pid_for_testing)/ +ln -s $(pid_for_testing) self +ln -s self/net net +" + comment => "Create a semi-real structure with symlinks and a pid dir", + contain => in_shell; +} + + bundle agent test { meta: "test_skip_unsupported" string => "!linux"; commands: - "$(G.env) CFENGINE_TEST_OVERRIDE_PROCDIR=$(this.promise_dirname)/proc $(sys.cf_agent) -DAUTO -f $(this.promise_filename).sub"; + "$(G.env) CFENGINE_TEST_OVERRIDE_PROCPID=$(init.pid_for_testing) CFENGINE_TEST_OVERRIDE_PROCDIR=$(G.testdir)/proc $(sys.cf_agent) -DAUTO -f $(this.promise_filename).sub"; } diff --git a/tests/acceptance/00_basics/environment/proc-net.cf b/tests/acceptance/00_basics/environment/proc-net.cf index dba5dda097..733153c5d7 100644 --- a/tests/acceptance/00_basics/environment/proc-net.cf +++ b/tests/acceptance/00_basics/environment/proc-net.cf @@ -7,11 +7,34 @@ body common control ########################################################### +bundle agent init +{ + vars: + "pid_for_testing" int => "11"; + + methods: + "" usebundle => dir_sync( + "$(this.promise_dirname)/proc", + "$(G.testdir)/proc" + ); + + commands: + " +cd $(G.testdir)/proc/proc +mkdir $(pid_for_testing) +mv net $(pid_for_testing)/ +ln -s $(pid_for_testing) self +ln -s self/net net +" + comment => "Create a semi-real structure with symlinks and a pid dir", + contain => in_shell; +} + bundle agent test { meta: "test_skip_unsupported" string => "!linux"; commands: - "$(G.env) CFENGINE_TEST_OVERRIDE_PROCDIR=$(this.promise_dirname)/proc $(sys.cf_agent) -DAUTO -f $(this.promise_filename).sub"; + "$(G.env) CFENGINE_TEST_OVERRIDE_PROCPID=$(init.pid_for_testing) CFENGINE_TEST_OVERRIDE_PROCDIR=$(G.testdir)/proc $(sys.cf_agent) -DAUTO -f $(this.promise_filename).sub"; } diff --git a/tests/acceptance/01_vars/02_functions/001.cf b/tests/acceptance/01_vars/02_functions/001.cf index 58ddb48c1c..69994df3f6 100644 --- a/tests/acceptance/01_vars/02_functions/001.cf +++ b/tests/acceptance/01_vars/02_functions/001.cf @@ -34,11 +34,11 @@ bundle agent test !darwin:: "uid_bin" int => getuid("bin"); - (linux.!archlinux.!SuSE.!redhat.!gentoo)|solaris|hpux|aix:: + (linux.!manjaro.!archlinux.!SuSE.!redhat.!gentoo)|solaris|hpux|aix:: "num_root" int => "0"; "num_daemon" int => "1"; "num_bin" int => "2"; - archlinux|SuSE|redhat|gentoo:: + manjaro|archlinux|SuSE|redhat|gentoo:: "num_root" int => "0"; "num_daemon" int => "2"; "num_bin" int => "1"; diff --git a/tests/acceptance/01_vars/02_functions/002.cf b/tests/acceptance/01_vars/02_functions/002.cf index 22edc1a952..40e360abd5 100644 --- a/tests/acceptance/01_vars/02_functions/002.cf +++ b/tests/acceptance/01_vars/02_functions/002.cf @@ -47,9 +47,9 @@ bundle agent test !linux.!freebsd.!solaris.!darwin.!openbsd.!hpux.!aix:: "gid_0" string => "fixme"; - archlinux|SuSE|redhat|gentoo:: + manjaro|archlinux|SuSE|redhat|gentoo:: "num_daemon" int => "2"; - (linux.!archlinux.!SuSE.!redhat.!gentoo)|freebsd|darwin|openbsd:: + (linux.!manjaro.!archlinux.!SuSE.!redhat.!gentoo)|freebsd|darwin|openbsd:: "num_daemon" int => "1"; solaris:: "num_daemon" int => "12"; diff --git a/tests/acceptance/01_vars/02_functions/findfiles.cf b/tests/acceptance/01_vars/02_functions/findfiles.cf index 978e2ea591..2827d45871 100644 --- a/tests/acceptance/01_vars/02_functions/findfiles.cf +++ b/tests/acceptance/01_vars/02_functions/findfiles.cf @@ -74,15 +74,15 @@ bundle agent check { vars: !windows:: - "expected[a]" string => "$(G.testdir)/a,$(G.testdir)/d,$(G.testdir)/g"; - "expected[b]" string => "$(G.testdir)/a,$(G.testdir)/bc,$(G.testdir)/d,$(G.testdir)/g,$(G.testdir)/klm,$(G.testdir)/tu"; + "expected[a]" string => "$(G.testdir)/a,$(G.testdir)/d/,$(G.testdir)/g/"; + "expected[b]" string => "$(G.testdir)/a,$(G.testdir)/bc,$(G.testdir)/d/,$(G.testdir)/g/,$(G.testdir)/klm/,$(G.testdir)/tu/"; - "expected[c]" string => "$(G.testdir)/d/e,$(G.testdir)/g/h"; + "expected[c]" string => "$(G.testdir)/d/e/,$(G.testdir)/g/h/"; "expected[d]" string => "$(G.testdir)/a,$(G.testdir)/bc"; "expected[e]" string => ""; "expected[f]" string => "$(G.testdir)/tu/*"; - "expected[g]" string => "$(G.testdir)/a,$(G.testdir)/bc,$(G.testdir)/d,$(G.testdir)/g,$(G.testdir)/klm,$(G.testdir)/tu,$(G.testdir)/d/e,$(G.testdir)/g/h,$(G.testdir)/klm/nop,$(G.testdir)/tu/*,$(G.testdir)/d/e/f,$(G.testdir)/g/h/i,$(G.testdir)/klm/nop/qrs,$(G.testdir)/g/h/i/j"; + "expected[g]" string => "$(G.testdir)/a,$(G.testdir)/bc,$(G.testdir)/d/,$(G.testdir)/g/,$(G.testdir)/klm/,$(G.testdir)/tu/,$(G.testdir)/d/e/,$(G.testdir)/g/h/,$(G.testdir)/klm/nop/,$(G.testdir)/tu/*,$(G.testdir)/d/e/f,$(G.testdir)/g/h/i/,$(G.testdir)/klm/nop/qrs,$(G.testdir)/g/h/i/j"; "expected[h]" string => "$(G.testdir)/g/h/i/j"; windows:: "expected[a]" string => "$(G.testdir)\\a,$(G.testdir)\\d,$(G.testdir)\\g"; diff --git a/tests/acceptance/01_vars/02_functions/findfiles_up.cf b/tests/acceptance/01_vars/02_functions/findfiles_up.cf index f05fcc72cc..98c2a564bd 100755 --- a/tests/acceptance/01_vars/02_functions/findfiles_up.cf +++ b/tests/acceptance/01_vars/02_functions/findfiles_up.cf @@ -74,12 +74,12 @@ bundle agent check ); "c3" expression => and( - strcmp("$(G.testdir)\\core\\libntech\\.git", "$(test.t3[0])"), - strcmp("$(G.testdir)\\core\\.git", "$(test.t3[1])") + strcmp("$(G.testdir)\\core\\libntech\\.git\\", "$(test.t3[0])"), + strcmp("$(G.testdir)\\core\\.git\\", "$(test.t3[1])") ); "c4" expression => and( - strcmp("$(G.testdir)\\core\\libntech\\.git", "$(test.t4[0])"), + strcmp("$(G.testdir)\\core\\libntech\\.git\\", "$(test.t4[0])"), not(isvariable("test.t4[1]")) ); "c5" @@ -106,12 +106,12 @@ bundle agent check ); "c3" expression => and( - strcmp("$(G.testdir)/core/libntech/.git", "$(test.t3[0])"), - strcmp("$(G.testdir)/core/.git", "$(test.t3[1])") + strcmp("$(G.testdir)/core/libntech/.git/", "$(test.t3[0])"), + strcmp("$(G.testdir)/core/.git/", "$(test.t3[1])") ); "c4" expression => and( - strcmp("$(G.testdir)/core/libntech/.git", "$(test.t4[0])"), + strcmp("$(G.testdir)/core/libntech/.git/", "$(test.t4[0])"), not(isvariable("test.t4[1]")) ); "c5" diff --git a/tests/acceptance/01_vars/02_functions/getindices_returns_expected_list_from_datacontainer.cf b/tests/acceptance/01_vars/02_functions/getindices_returns_expected_list_from_datacontainer.cf index 6fc8f93606..d675ebd424 100644 --- a/tests/acceptance/01_vars/02_functions/getindices_returns_expected_list_from_datacontainer.cf +++ b/tests/acceptance/01_vars/02_functions/getindices_returns_expected_list_from_datacontainer.cf @@ -22,7 +22,10 @@ bundle agent init "alpha", "bravo" ], - "bar": { "one": "1" "two": "2" } + "bar": { + "one": "1", + "two": "2" + } }'); } diff --git a/tests/acceptance/01_vars/02_functions/maparray.cf.expected.json b/tests/acceptance/01_vars/02_functions/maparray.cf.expected.json index 4beadbc9e5..4a08d755b7 100644 --- a/tests/acceptance/01_vars/02_functions/maparray.cf.expected.json +++ b/tests/acceptance/01_vars/02_functions/maparray.cf.expected.json @@ -29,7 +29,7 @@ "element3" ], "load3": { - "x"x": "y\"y" + "x\"x": "y\"y" }, "load4": [], "load5[anotherkey]": "anothervalue", @@ -149,6 +149,6 @@ "static[anotherkey]": "anothervalue", "static[lastkey!]": "lastvalue", "static[mykey]": "myvalue", - "static[x"x]": "xxvalue", + "static[x\"x]": "xxvalue", "static[x]": "xvalue" } diff --git a/tests/acceptance/02_classes/01_basic/expected_os_classes.cf b/tests/acceptance/02_classes/01_basic/expected_os_classes.cf index 020f4a189b..bda5118bf7 100644 --- a/tests/acceptance/02_classes/01_basic/expected_os_classes.cf +++ b/tests/acceptance/02_classes/01_basic/expected_os_classes.cf @@ -26,6 +26,7 @@ bundle agent check "hpux", "suse", "opensuse", + "manjaro", "archlinux", "windows", "freebsd", diff --git a/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf b/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf new file mode 100644 index 0000000000..d887e0a3a6 --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf @@ -0,0 +1,92 @@ +####################################################### +# +# CFE-4681: classes: promises with timer_policy => "absolute" (default) +# +# Verify that timer_policy => "absolute" (the default) on a classes: +# promise preserves the persistence timer across agent runs. +# +# This is the counterpart to persistent_timer_policy_reset.cf and +# directly demonstrates the "promise is not evaluated" behaviour: +# once the persistent class is loaded from the DB on a subsequent +# run, the classes: promise is skipped in ExpandDeRefPromise (it is +# never handed to VerifyClassPromise), so the timer is left untouched. +# +# First run: expect "Creating persistent class ... policy preserve" +# Second run: expect "Skipping evaluation of classes promise ... is +# already set" and NO "Resetting persistent class". +# +# Note: the skip message is logged at LOG_LEVEL_DEBUG, so the second +# run uses -d. Both sub-agent runs happen in the test bundle so that +# the check bundle only evaluates assertions -- this avoids a spurious +# FAIL report during the agent's convergence passes. +# +####################################################### + +body common control +{ + inputs => { "../../default.cf.sub" }; + bundlesequence => { default("$(this.promise_filename)") }; + version => "1.0"; +} + +bundle agent init +{ + # Remove the persistent class DB to ensure a clean state. + files: + "$(sys.workdir)/state/cf_state.lmdb" + delete => tidy; + "$(sys.workdir)/state/cf_state.lmdb-lock" + delete => tidy; + "$(sys.workdir)/state/cf_state.lmdb.lock" + delete => tidy; +} + +bundle agent test +{ + meta: + "description" -> { "CFE-4681" } + string => "timer_policy => absolute (default) on classes: promises preserves the timer; the promise is skipped (not evaluated) when the class is already defined"; + + commands: + # First run: define the persistent class with timer_policy => "absolute". + !first_done:: + "$(sys.cf_agent) -Kv -f $(this.promise_filename).sub > $(G.testdir)/timer_policy_run1.log 2>&1" + contain => in_shell, + classes => always("first_done"); + + # Second run: the class is already loaded from the persistent DB, so with + # timer_policy => absolute the classes: promise must be skipped (not + # evaluated) and the timer must not be reset. Run with -d so the + # DEBUG-level skip message is captured. + first_done.!second_done:: + "$(sys.cf_agent) -Kd -f $(this.promise_filename).sub > $(G.testdir)/timer_policy_run2.log 2>&1" + contain => in_shell, + classes => always("second_done"); +} + +bundle agent check +{ + classes: + # Run 1 creates the persistent class with the preserve (absolute) policy. + "create_ok" expression => regline(".*Creating persistent class.*timer_policy_test_class.*policy preserve.*", + "$(G.testdir)/timer_policy_run1.log"); + # Run 2 must skip the promise because the class is already defined. + "skip_ok" expression => regline(".*Skipping evaluation of classes promise as class.*timer_policy_test_class.*is already set.*", + "$(G.testdir)/timer_policy_run2.log"); + # Run 2 must NOT reset the timer (no EvalContextHeapPersistentSave call). + "reset_seen" expression => regline(".*Resetting persistent class.*timer_policy_test_class.*", + "$(G.testdir)/timer_policy_run2.log"); + "ok" expression => "create_ok.skip_ok.!reset_seen"; + + reports: + DEBUG.!create_ok:: + "FAIL: first run did not log 'Creating persistent class ... policy preserve'"; + DEBUG.!skip_ok:: + "FAIL: second run did not skip the classes promise (expected 'Skipping evaluation of classes promise ... is already set')"; + DEBUG.reset_seen:: + "FAIL: second run reset the timer despite timer_policy => absolute"; + ok:: + "$(this.promise_filename) Pass"; + !ok:: + "$(this.promise_filename) FAIL"; +} diff --git a/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf.sub b/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf.sub new file mode 100644 index 0000000000..ca6dbb9c87 --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/persistent_timer_policy.cf.sub @@ -0,0 +1,15 @@ +body common control +{ + bundlesequence => { run }; +} + +bundle agent run +{ + classes: + # Define persistent class with timer_policy => "absolute" + # This stores CONTEXT_STATE_POLICY_PRESERVE in the DB + "timer_policy_test_class" + expression => "any", + persistence => "120", + timer_policy => "absolute"; +} diff --git a/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf b/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf new file mode 100644 index 0000000000..0a9278396d --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf @@ -0,0 +1,83 @@ +####################################################### +# +# CFE-4681: classes: promises with timer_policy => "reset" +# +# Verify that timer_policy => "reset" on a classes: promise +# causes the persistence timer to be reset on subsequent +# agent runs, even though the class is already defined +# (loaded from the persistent DB). +# +# First run: expect "Creating persistent class" +# Second run: expect "Resetting persistent class" (not skipped) +# +# Both sub-agent runs happen in the test bundle so that the check +# bundle only evaluates assertions -- this avoids a spurious FAIL +# report during the agent's convergence passes. +# +####################################################### + +body common control +{ + inputs => { "../../default.cf.sub" }; + bundlesequence => { default("$(this.promise_filename)") }; + version => "1.0"; +} + +bundle agent init +{ + # Remove the persistent class DB to ensure a clean state. + files: + "$(sys.workdir)/state/cf_state.lmdb" + delete => tidy; + "$(sys.workdir)/state/cf_state.lmdb-lock" + delete => tidy; + "$(sys.workdir)/state/cf_state.lmdb.lock" + delete => tidy; +} + +bundle agent test +{ + meta: + "description" -> { "CFE-4681" } + string => "timer_policy => reset on classes: promises resets the persistence timer on subsequent runs"; + + commands: + # First run: define the persistent class. + !first_done:: + "$(sys.cf_agent) -Kv -f $(this.promise_filename).sub > $(G.testdir)/timer_reset_run1.log 2>&1" + contain => in_shell, + classes => always("first_done"); + + # Second run: the class already exists in the DB; timer_policy => reset + # must cause the promise to be evaluated and the timer to be reset. + first_done.!second_done:: + "$(sys.cf_agent) -Kv -f $(this.promise_filename).sub > $(G.testdir)/timer_reset_run2.log 2>&1" + contain => in_shell, + classes => always("second_done"); +} + +bundle agent check +{ + classes: + "first_ok" expression => regline(".*Creating persistent class.*timer_reset_test_class.*", + "$(G.testdir)/timer_reset_run1.log"); + # Match the EvalContextHeapPersistentSave message specifically (it + # reports "... timer to N minutes (was M remaining)"). This only + # appears when the existing DB record is actually found, so it would + # NOT match the "C: + Resetting persistent class timer: ..." progress + # line that VerifyClassPromise logs regardless. This distinction is + # what makes the test catch a broken existing-record lookup. + "second_ok" expression => regline(".*Resetting persistent class 'timer_reset_test_class' timer to.*", + "$(G.testdir)/timer_reset_run2.log"); + "ok" expression => "first_ok.second_ok"; + + reports: + DEBUG.!first_ok:: + "FAIL: first run did not log 'Creating persistent class'"; + DEBUG.!second_ok:: + "FAIL: second run did not log 'Resetting persistent class' (short-circuit not bypassed)"; + ok:: + "$(this.promise_filename) Pass"; + !ok:: + "$(this.promise_filename) FAIL"; +} diff --git a/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf.sub b/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf.sub new file mode 100644 index 0000000000..a5624056a7 --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/persistent_timer_policy_reset.cf.sub @@ -0,0 +1,16 @@ +body common control +{ + bundlesequence => { run }; +} + +bundle agent run +{ + classes: + # Define persistent class with timer_policy => "reset" + # On second run, the timer should be reset even though + # the class is already defined from the persistent DB. + "timer_reset_test_class" + expression => "any", + persistence => "120", + timer_policy => "reset"; +} diff --git a/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf b/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf new file mode 100644 index 0000000000..bc44610631 --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf @@ -0,0 +1,49 @@ +####################################################### +# +# CFE-4681: classes: promises reject timer_policy without persistence +# +# timer_policy only governs the persistence timer, so using it on a +# classes: promise that has no 'persistence' attribute has no meaning. +# Verify that doing so is an error (PROMISE_RESULT_FAIL) rather than +# being silently ignored. +# +# The offending policy is run in a sub-agent so the check bundle only +# evaluates assertions against its captured output. +# +####################################################### + +body common control +{ + inputs => { "../../default.cf.sub" }; + bundlesequence => { default("$(this.promise_filename)") }; + version => "1.0"; +} + +bundle agent test +{ + meta: + "description" -> { "CFE-4681" } + string => "Using timer_policy without persistence on a classes: promise is an error"; + + commands: + !done:: + "$(sys.cf_agent) -Kv -f $(this.promise_filename).sub > $(G.testdir)/timer_policy_no_persistence.log 2>&1" + contain => in_shell, + classes => always("done"); +} + +bundle agent check +{ + classes: + "error_ok" expression => regline(".*Cannot use 'timer_policy' without 'persistence'.*timer_policy_no_persistence_class.*", + "$(G.testdir)/timer_policy_no_persistence.log"); + "ok" expression => "error_ok"; + + reports: + DEBUG.!error_ok:: + "FAIL: did not log the expected 'timer_policy without persistence' error"; + ok:: + "$(this.promise_filename) Pass"; + !ok:: + "$(this.promise_filename) FAIL"; +} diff --git a/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf.sub b/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf.sub new file mode 100644 index 0000000000..4487729528 --- /dev/null +++ b/tests/acceptance/02_classes/01_basic/timer_policy_requires_persistence.cf.sub @@ -0,0 +1,14 @@ +body common control +{ + bundlesequence => { run }; +} + +bundle agent run +{ + classes: + # timer_policy only governs the persistence timer, so using it + # without 'persistence' is an error (PROMISE_RESULT_FAIL). + "timer_policy_no_persistence_class" + expression => "any", + timer_policy => "reset"; +} diff --git a/tests/acceptance/07_packages/packages_command.cf b/tests/acceptance/07_packages/packages_command.cf new file mode 100644 index 0000000000..4bece4865f --- /dev/null +++ b/tests/acceptance/07_packages/packages_command.cf @@ -0,0 +1,92 @@ +####################################################### +# +# See ticket ENT-13536 for info +# +####################################################### + +body common control +{ + inputs => { "../default.cf.sub" }; + bundlesequence => { "G", "g", default("$(this.promise_filename)") }; + version => "1.0"; + cache_system_functions => "false"; +} + +body package_method mock +{ + package_changes => "individual"; + package_list_command => "$(g.pm) --list-installed"; + + package_list_name_regex => "^[^:]*"; + package_list_version_regex => ":(?<=:).*(?=:)"; + package_list_arch_regex => "[^:]\w+$"; + package_installed_regex => "^[^:]*"; + + package_add_command => "$(g.pm) --add "; + package_update_command => "$(g.pm) --update "; + package_delete_command => "$(g.pm) --delete "; + package_verify_command => "$(g.pm) --verify "; +} + +bundle common g +{ + classes: + "mpm_declared" not => strcmp(getenv("MOCK_PACKAGE_MANAGER", "65535"), ""); + + vars: + mpm_declared:: + "pm" string => getenv("MOCK_PACKAGE_MANAGER", "65535"); + + !mpm_declared:: + "pm" string => "$(G.mock_package_manager)"; +} + +####################################################### + +bundle agent init +{ + commands: + "$(g.pm) --clear-installed"; + "$(g.pm) --clear-available"; + "$(g.pm) --populate-available imagisoft:1.0i:teapot"; + + files: + "$(G.testfile)" + delete => tidy; +} + +####################################################### + +bundle agent test +{ + meta: + "test_skip_unsupported" string => "windows", + meta => { "ENT-10215" }; + + vars: + "name" string => "imagisoft"; + "version" string => "1.0i"; + "arch" string => "teapot"; + + packages: + "imagisoft; echo 'Hello CFEngine' > '$(G.testfile)';" + package_policy => "add", + package_method => mock; +} + +####################################################### + +bundle agent check +{ + reports: + "$(this.promise_filename) $(with)" + with => ifelse(fileexists("$(G.testfile)"), "FAIL", "Pass"); +} + +####################################################### + +bundle agent clean +{ + methods: + "init"; +} diff --git a/tests/acceptance/07_packages/repositories.cf b/tests/acceptance/07_packages/repositories.cf index 0691813510..13f6802c12 100644 --- a/tests/acceptance/07_packages/repositories.cf +++ b/tests/acceptance/07_packages/repositories.cf @@ -15,16 +15,18 @@ bundle agent init # Due to shell rules, windows includes certain characters on certain commands, # while Unix does not. windows:: + "single_quote" string => "'"; "q" string => '"'; "s" string => ' '; !windows:: + "single_quote" string => ''; "q" string => ''; "s" string => ''; methods: "make" usebundle => file_make("$(G.testfile).expected", " -$(s)filerepo DELETE delete-exact-version-2.2.3.i386.rpm +$(s)filerepo DELETE $(single_quote)delete-exact-version-2.2.3.i386.rpm$(single_quote) $(s)filerepo ADD $(q)$(G.cwd)$(d).$(d)07_packages$(d)test_repository$(d)install-greaterthan-version-2.2.3.i386.rpm$(q) $(s)filerepo ADD $(q)$(G.cwd)$(d).$(d)07_packages$(d)test_repository$(d)install-greaterorequal-version-2.2.3.i386.rpm$(q) $(s)filerepo ADD $(q)$(G.cwd)$(d).$(d)07_packages$(d)test_repository$(d)install-lessthan-version-2.2.3.i386.rpm$(q) diff --git a/tests/acceptance/10_files/01_create/013.cf b/tests/acceptance/10_files/01_create/013.cf new file mode 100644 index 0000000000..a10dd3295a --- /dev/null +++ b/tests/acceptance/10_files/01_create/013.cf @@ -0,0 +1,76 @@ +####################################################### +# +# Create a file with content attribute and owner via perms, +# but witout create attribute, check owner +# +####################################################### + +body common control +{ + inputs => { "../../default.cf.sub" }; + bundlesequence => { default("$(this.promise_filename)") }; + version => "1.0"; +} + +####################################################### + +bundle agent init +{ + files: + "$(G.testfile)" + delete => init_delete; +} + +body delete init_delete +{ + dirlinks => "delete"; + rmdirs => "true"; +} + +####################################################### + +bundle agent test +{ + meta: + "test_skip_needs_work" -> { "ENT-13658" } + string => "hpux|aix"; + + vars: + "owner" string => "nobody"; + + files: + "$(G.testfile)" + content => "", + perms => test_perms($(owner)); +} + +body perms test_perms(o) +{ + rxdirs => "false"; + mode => "644"; + owners => { "$(o)" }; + groups => { "0" }; +} + +####################################################### + +bundle agent check +{ + vars: + "ui" data => getuserinfo(filestat($(G.testfile), "uid")); + + classes: + "not_ok" not => strcmp($(test.owner), $(ui[username])); + + reports: + DEBUG:: + "expected: username = '$(test.owner)'"; + "got: username = '$(ui[username])'"; + !not_ok:: + "$(this.promise_filename) Pass"; + not_ok:: + "$(this.promise_filename) FAIL"; +} + +### PROJECT_ID: core +### CATEGORY_ID: 27 diff --git a/tests/acceptance/10_files/file_select_attrs_consistent_behavior/rules.json b/tests/acceptance/10_files/file_select_attrs_consistent_behavior/rules.json index 352beedf05..be311e4319 100644 --- a/tests/acceptance/10_files/file_select_attrs_consistent_behavior/rules.json +++ b/tests/acceptance/10_files/file_select_attrs_consistent_behavior/rules.json @@ -1,6 +1,6 @@ [ { -"location": "/tmp/logs/tidy" +"location": "/tmp/logs/tidy", "context": "any", "action": "TIDY", "frequency": "10", diff --git a/tests/acceptance/10_files/move_obstructions-promiser-is-symlink.cf b/tests/acceptance/10_files/move_obstructions-promiser-is-symlink.cf new file mode 100644 index 0000000000..8e07372895 --- /dev/null +++ b/tests/acceptance/10_files/move_obstructions-promiser-is-symlink.cf @@ -0,0 +1,206 @@ + +############################################################################## +# +# Test that move_obstructions works consistently for various types of files +# promises targeting a specific file where the promiser is a symlink +# - copy_from +# +############################################################################## + +body file control +{ + inputs => { "../default.cf.sub" }; +} + +############################################################################## +bundle agent __main__ +{ + methods: + "init"; + "test"; + "check"; + "cleanup"; +} + +bundle agent cleanup +{ + vars: + "potential_files_to_delete" + slist => { + # The files we tested + "@(init.test_files)", + "$(init.orig_ln_target_filename)", + # .cfsaved files get created as copy_from replaces files + maplist( "$(this).cfsaved", @(init.test_files) ), + # The special case source file to copy from + maplist( "$(this).source", @(init.test_files) ), + }; + + files: + "$(potential_files_to_delete)" + delete => tidy, + if => fileexists( "$(this.promiser)" ); +} + +bundle agent init +{ + vars: + # Create test files that will serve as obstructions + "test_files" slist => { + "$(G.testdir)/copy_from", + "$(G.testdir)/content", + "$(G.testdir)/edit_template_string_inline_mustache", + "$(G.testdir)/edit_template_cfengine", + "$(G.testdir)/edit_template_mustache", + #"$(G.testdir)/edit_line", + }; + + "orig_ln_target_filename" + string => "$(G.testdir)/orig_ln_target"; + + "orig_ln_target_content" + string => "This content originally lived in a symlink target"; + + files: + # Here we initialize a file which will be a symlinks target + "$(orig_ln_target_filename)" + create => "true", + content => "$(orig_ln_target_content)"; + + # Here we have a symlink that we will be targeting with a content files promise + "$(test_files)" + create => "true", + move_obstructions => "true", + link_from => ln_s( "$(G.testdir)/orig_ln_target" ); + + reports: + DEBUG:: + "$(test_files) initalized" + if => and( fileexists( "$(test_files)" ), + islink( $(test_files) ) ); +} + +body link_from ln_s(x) +{ + link_type => "symlink"; + source => "$(x)"; + when_no_source => "force"; +} +############################################################################## + +bundle agent test +{ + meta: + "description" + string => concat( + "Test move_obstructions with content, edit_template,", + " and edit_template_string" + ); + + files: + # Test move_obstructions with copy_from + # This isn't in init because it's specific to copy_from needing to have a source file. + "$(G.testdir)/copy_from.source" + content => "$(check.expected_content)", + if => fileexists( "$(G.testdir)/copy_from" ); + + "$(G.testdir)/copy_from" + move_obstructions => "true", + copy_from => local_dcp("$(G.testdir)/copy_from.source"), + if => fileexists( "$(this.promiser)" ); + + "$(G.testdir)/edit_template_cfengine" + move_obstructions => "true", + template_method => "cfengine", + edit_template => "$(G.testdir)/copy_from.source", + if => fileexists( "$(this.promiser)" ); + + "$(G.testdir)/edit_template_mustache" + move_obstructions => "true", + template_method => "mustache", + edit_template => "$(G.testdir)/copy_from.source", + if => fileexists( "$(this.promiser)" ); + + # Test move_obstructions with content attribute + "$(G.testdir)/content" + move_obstructions => "true", + content => "$(check.expected_content)", + if => fileexists( "$(this.promiser)" ); + + # Test move_obstructions with template_method inline_mustache + "$(G.testdir)/edit_template_string_inline_mustache" + move_obstructions => "true", + template_method => "inline_mustache", + edit_template_string => "$(check.expected_content)", + if => fileexists( "$(this.promiser)" ); + + # # Test move_obstructions with edit_line + # "$(G.testdir)/edit_line" + # move_obstructions => "true", + # edit_line => insert_lines("$(check.expected_content)"), + # if => fileexists( "$(this.promiser)" ); + +} + +############################################################################## + +bundle agent check +{ + vars: + "expected_content" string => "This is content promised targeting a symlink."; + "num_test_files" int => length( @(init.test_files) ); + + # We check the promised: + # - for each test file + # - content + # - type + + "num_expected_test_ok_classes" + int => int( eval( "$(num_test_files)*2", math, infix) ); + + classes: + "DEBUG" expression => "any"; + "all_test_files_exist" + expression => filesexist( @(init.test_files) ); + + all_test_files_exist:: + # Once we verified that all the test files exist we can check all the expectations + + # These class strings will be canonified as classes, they are tagged for easy identification + + "$(init.test_files) type as expected" + meta => { "test_ok_class" }, + if => isplain( "$(init.test_files)" ); + + "$(init.test_files) content as expected" + meta => { "test_ok_class" }, + if => strcmp( readfile("$(init.test_files)"), + "$(expected_content)"); + + "overall_success" + expression => strcmp( length( classesmatching( ".*", "test_ok_class" ) ), + "$(num_expected_test_ok_classes)" ); + + reports: + !all_test_files_exist:: + "The test does not appear to have been initialized, the expected test files are missing $(with)" + with => concat( "(", join( ",", @(init.test_files) ), ")" ); + + DEBUG:: + + "Number of test files: $(num_test_files)"; + + "Number of expected test ok classes to pass: $(num_expected_test_ok_classes)"; + + "$(with) test_ok_classes:" + with => length( classesmatching( ".*", "test_ok_class" ) ); + + "$(with)" + with => join( "$(const.n)", classesmatching( ".*", "test_ok_class" ) ); + + overall_success:: + "$(this.promise_filename) Pass"; + + !overall_success:: + "$(this.promise_filename) FAIL"; +} diff --git a/tests/acceptance/10_files/no_error_archiving_previous_backup_using_copy_from_without_create_true.cf.sub b/tests/acceptance/10_files/no_error_archiving_previous_backup_using_copy_from_without_create_true.cf.sub index 304fd40013..acc778ac50 100644 --- a/tests/acceptance/10_files/no_error_archiving_previous_backup_using_copy_from_without_create_true.cf.sub +++ b/tests/acceptance/10_files/no_error_archiving_previous_backup_using_copy_from_without_create_true.cf.sub @@ -95,11 +95,3 @@ body classes outcomes(p) repair_timeout => { '$(p)_timeout', '$(p)_reached', '$(p)_error' }; scope => 'bundle'; } -bundle edit_line lines_present(lines) -{ - insert_lines: - - "$(lines)" - comment => "Append lines if they don't exist"; -} - diff --git a/tests/acceptance/10_files/templating/edit_template_string/mustache_edit_template_string_vs_string_mustache.cf b/tests/acceptance/10_files/templating/edit_template_string/mustache_edit_template_string_vs_string_mustache.cf index 510a706865..571424eb95 100644 --- a/tests/acceptance/10_files/templating/edit_template_string/mustache_edit_template_string_vs_string_mustache.cf +++ b/tests/acceptance/10_files/templating/edit_template_string/mustache_edit_template_string_vs_string_mustache.cf @@ -102,26 +102,3 @@ body printfile cat(file) file_to_print => "$(file)"; number_of_lines => "inf"; } -bundle edit_line lines_present(lines) -# @brief Ensure `lines` are present in the file. Lines that do not exist are appended to the file -# @param List or string that should be present in the file -# -# **Example:** -# -# ```cf3 -# bundle agent example -# { -# vars: -# "nameservers" slist => { "8.8.8.8", "8.8.4.4" }; -# -# files: -# "/etc/resolv.conf" edit_line => lines_present( @(nameservers) ); -# "/etc/ssh/sshd_config" edit_line => lines_present( "PermitRootLogin no" ); -# } -# ``` -{ - insert_lines: - - "$(lines)" - comment => "Append lines if they don't exist"; -} diff --git a/tests/acceptance/16_cf-serverd/serial/copy_from_ciphers_success.cf b/tests/acceptance/16_cf-serverd/serial/copy_from_ciphers_success.cf index 9585f5cbd1..0928558dce 100644 --- a/tests/acceptance/16_cf-serverd/serial/copy_from_ciphers_success.cf +++ b/tests/acceptance/16_cf-serverd/serial/copy_from_ciphers_success.cf @@ -8,8 +8,8 @@ body common control bundle agent test { meta: - "test_soft_fail" string => "windows", - meta => { "ENT-10401" }; + "test_soft_fail" string => "windows|redhat_10", + meta => { "ENT-10401", "ENT-13494" }; methods: # source file diff --git a/tests/acceptance/17_users/unsafe/user_command.cf b/tests/acceptance/17_users/unsafe/user_command.cf new file mode 100644 index 0000000000..946f20ce35 --- /dev/null +++ b/tests/acceptance/17_users/unsafe/user_command.cf @@ -0,0 +1,61 @@ +############################################################################## +# +# See ticket ENT-13535 for info. +# +############################################################################## + +body common control +{ + bundlesequence => { "init", "test", "check", "clean" }; +} + +body delete tidy +{ + dirlinks => "delete"; + rmdirs => "true"; +} + +############################################################################## + +bundle agent init +{ + users: + "test_user" + policy => "absent"; + + files: + "/tmp/some-random-file.txt" + delete => tidy; +} + +############################################################################## + +bundle agent test +{ + meta: + "description" -> { "ENT-13535" } + string => "See ticket ENT-13535 for info"; + "test_skip_unsupported" + string => "windows", + comment => "Not applicable for Windows since it uses a C API"; + + users: + linux:: + "test_user; echo 'Hello CFEngine' > /tmp/some-random-file.txt" + policy => "present"; +} + +############################################################################## + +bundle agent check +{ + reports: + "$(this.promise_filename) $(with)" + with => ifelse(fileexists("/tmp/some-random-file.txt"), "FAIL", "Pass"); +} + +bundle agent clean +{ + methods: + "init"; +} diff --git a/tests/acceptance/28_inform_testing/01_files/copy_from01.cf b/tests/acceptance/28_inform_testing/01_files/copy_from01.cf index 32ee890b36..3b979d7c23 100644 --- a/tests/acceptance/28_inform_testing/01_files/copy_from01.cf +++ b/tests/acceptance/28_inform_testing/01_files/copy_from01.cf @@ -17,11 +17,18 @@ bundle agent setup files: "$(G.testroot)/TEST.source" depth_search => recurse("inf"), - perms => system_owned("0644"), + perms => agent_owned("0644"), copy_from => example("$(this.promise_dirname)/test_files"); } +body perms agent_owned(mode) +{ + mode => "$(mode)"; + owners => { "$(sys.user_data[username])" }; + groups => { "$(sys.user_data[gid])" }; +} + bundle agent main { files: diff --git a/tests/acceptance/28_inform_testing/01_files/copy_from03.cf b/tests/acceptance/28_inform_testing/01_files/copy_from03.cf index 7e7f43035c..e03d8c3479 100644 --- a/tests/acceptance/28_inform_testing/01_files/copy_from03.cf +++ b/tests/acceptance/28_inform_testing/01_files/copy_from03.cf @@ -17,11 +17,18 @@ bundle agent setup files: "$(G.testroot)/TEST.source" depth_search => recurse("inf"), - perms => system_owned("0644"), + perms => agent_owned("0644"), copy_from => example("$(this.promise_dirname)/test_files"); } +body perms agent_owned(mode) +{ + mode => "$(mode)"; + owners => { "$(sys.user_data[username])" }; + groups => { "$(sys.user_data[gid])" }; +} + bundle agent main { files: diff --git a/tests/acceptance/31_tickets/CFE-2663/test.cf b/tests/acceptance/31_tickets/CFE-2663/test.cf new file mode 100644 index 0000000000..61e05984e0 --- /dev/null +++ b/tests/acceptance/31_tickets/CFE-2663/test.cf @@ -0,0 +1,80 @@ +body file control +{ + inputs => { "../../default.cf.sub" }; +} + +bundle agent __main__ +{ + methods: + "bundlesequence" usebundle => default("$(this.promise_filename)"); +} + +bundle agent init +{ + vars: + # No trailing newline in the strings, so the "[section2]" header is + # genuinely the last line of the "actual" file. The region selected for + # section2 is therefore empty and sits at the end of the file. + "actual" string => "[section] +keyone=valueone +[section2]"; + "expected" string => "[section] +keyone=valueone +[section2] +keytwo=valuetwo"; + "files" slist => { "actual", "expected" }; + + files: + "$(G.testfile).$(files)" + create => "true", + edit_line => init_insert("$(init.$(files))"), + edit_defaults => init_empty; +} + +bundle edit_line init_insert(str) +{ + insert_lines: + "$(str)"; +} + +body edit_defaults init_empty +{ + empty_file_before_editing => "true"; +} + +bundle agent test +{ + meta: + "description" + string => "Insertion into an empty trailing region (the select_start delimiter is the last line of the file) must succeed when select_end_match_eof is true", + meta => { "CFE-2663" }; + + files: + "$(G.testfile).actual" edit_line => insert_into_trailing_section; +} + +bundle edit_line insert_into_trailing_section +{ + insert_lines: + "keytwo=valuetwo" select_region => ini_section("section2"); +} + +body select_region ini_section(x) +# @brief Restrict the edit to the lines in section [x], matching to EOF when +# [x] is the final section in the file. +{ + select_start => "\[$(x)\]\s*"; + select_end => "\[.*\]\s*"; + select_end_match_eof => "true"; +} + +bundle agent check +{ + methods: + "any" + usebundle => dcs_check_diff( + "$(G.testfile).actual", + "$(G.testfile).expected", + "$(this.promise_filename)" + ); +} diff --git a/tests/acceptance/31_tickets/CFE-3866/test.cf b/tests/acceptance/31_tickets/CFE-3866/test.cf new file mode 100644 index 0000000000..513a941f44 --- /dev/null +++ b/tests/acceptance/31_tickets/CFE-3866/test.cf @@ -0,0 +1,93 @@ +body file control +{ + inputs => { + "../../default.cf.sub", + }; +} + +bundle agent __main__ +{ + methods: + "bundlesequence" usebundle => default("$(this.promise_filename)"); +} + +bundle agent init +{ + files: + "$(G.testfile)" + delete => init_delete; +} + +body delete init_delete +{ + dirlinks => "delete"; + rmdirs => "true"; +} + +bundle agent test +{ + meta: + "description" + string => "Test that select_region converges across multiple edit_line passes when the region is created in an earlier pass", + meta => { "CFE-3866" }; + + files: + "$(G.testfile)" + create => "true", + edit_line => insert_section_then_add_content; +} + +bundle edit_line insert_section_then_add_content +{ + # First promise: Create the section header + insert_lines: + "[section]" + location => start; + + # Second promise: Add content within the section using select_region + # This should converge even though the section didn't exist when + # select_region was first evaluated (pass 1) + + insert_lines: + "key=value" + location => append, + select_region => section_region; +} + +body location append +{ + before_after => "after"; +} + +body select_region section_region +{ + select_start => "^\[section\]"; + include_start_delimiter => "true"; + select_end => "^\[.*\]"; + select_end_match_eof => "true"; +} + +bundle agent check +{ + vars: + "expected" + string => "[section] +key=value +"; + + "actual" + string => readfile("$(G.testfile)", "1000"); + + classes: + "ok" expression => strcmp("$(expected)", "$(actual)"); + + reports: + DEBUG:: + "Expected: '$(expected)'"; + "Actual: '$(actual)'"; + + ok:: + "$(this.promise_filename) Pass"; + !ok:: + "$(this.promise_filename) FAIL"; +} diff --git a/tests/acceptance/Makefile.am b/tests/acceptance/Makefile.am index cc77519761..4e76f8df8e 100644 --- a/tests/acceptance/Makefile.am +++ b/tests/acceptance/Makefile.am @@ -64,9 +64,9 @@ xml_c14nize_CPPFLAGS = \ -I$(srcdir)/../../libntech/libutils \ $(LIBXML2_CPPFLAGS) -xml_c14nize_CFLAGS = $(LIBXML2_CFLAGS) -xml_c14nize_LDFLAGS = $(LIBXML2_LDFLAGS) -xml_c14nize_LDADD = ../../libntech/libutils/libutils.la $(LIBXML2_LIBS) +xml_c14nize_CFLAGS = $(LIBXML2_CFLAGS) $(LMDB_CFLAGS) $(LIBRSYNC_CFLAGS) +xml_c14nize_LDFLAGS = $(LIBXML2_LDFLAGS) $(LMDB_LDFLAGS) $(LIBRSYNC_LDFLAGS) +xml_c14nize_LDADD = ../../libntech/libutils/libutils.la $(LIBXML2_LIBS) $(LMDB_LIBS) $(LIBRSYNC_LIBS) endif TESTS = diff --git a/tests/acceptance/mock_package_manager.c b/tests/acceptance/mock_package_manager.c index 70ac0d2cd8..dea326bad1 100644 --- a/tests/acceptance/mock_package_manager.c +++ b/tests/acceptance/mock_package_manager.c @@ -8,7 +8,7 @@ static char AVAILABLE_PACKAGES_FILE_NAME[PATH_MAX]; static char INSTALLED_PACKAGES_FILE_NAME[PATH_MAX]; -static const int MAX_PACKAGE_ENTRY_LENGTH = 256; +#define MAX_PACKAGE_ENTRY_LENGTH 256 #define DEFAULT_ARCHITECTURE "x666" diff --git a/tests/acceptance/plucked.cf.sub b/tests/acceptance/plucked.cf.sub index 297b6715a3..1d13802d9b 100644 --- a/tests/acceptance/plucked.cf.sub +++ b/tests/acceptance/plucked.cf.sub @@ -24,14 +24,33 @@ bundle agent run_ifdefined(namespace, mybundle) methods: "any" - usebundle => $(bundlesfound), - ifvarclass => strcmp(1, $(count)); + usebundle => $(bundlesfound), + if => strcmp(1, $(count)); reports: verbose_mode:: "$(this.bundle): found matching bundles $(bundlesfound) for namespace '$(namespace)' and bundle '$(mybundle)'"; } +body contain powershell +# @brief Run command with powershell (windows only) +# +# **Example:** +# +# ```cf3 +# commands: +# windows:: +# 'schtasks /DELETE /TN "$(_taskname)" /F' +# contain => powershell; +# ``` +# +# **History:** +# +# * Introduced in 3.17.0 +{ + useshell => "powershell"; +} + body contain in_dir_shell(dir) # @brief run command after switching to directory "dir" with full shell # @param dir directory to change into @@ -115,7 +134,7 @@ body action if_elapsed(x) } body action if_elapsed_day -# @brief Evalute the promise once every 24 hours +# @brief Evaluate the promise once every 24 hours { ifelapsed => "1440"; # 60 x 24 expireafter => "1400"; @@ -143,7 +162,7 @@ body classes if_repaired(x) promise_repaired => { "$(x)" }; } -body classes if_else(yes,no) +body classes if_else(yes, no) # @brief Define the classes `yes` or `no` depending on promise outcome # @param yes The name of the class that should be defined if the promise is kept or repaired # @param no The name of the class that should be defined if the promise could not be repaired @@ -165,7 +184,7 @@ body classes if_notkept(x) } body classes if_ok(x) -# @brief Define the class `x` if the promise is kept or could be repaired +# @brief Define the class `x` if the promise is kept or repaired # @param x The name of the class that should be defined { promise_repaired => { "$(x)" }; @@ -173,7 +192,7 @@ body classes if_ok(x) } body classes if_ok_cancel(x) -# @brief Cancel the class `x` if the promise ks kept or repaired +# @brief Cancel the class `x` if the promise is kept or repaired # @param x The name of the class that should be cancelled { cancel_repaired => { "$(x)" }; @@ -193,8 +212,8 @@ body classes classes_generic(x) body classes results(scope, class_prefix) # @brief Define classes prefixed with `class_prefix` and suffixed with -# appropriate outcomes: _kept, _repaired, _not_kept, _error, _failed, -# _denied, _timeout, _reached +# appropriate outcomes: `_kept`, `_repaired`, `_not_kept`, `_error`, `_failed`, +# `_denied`, `_timeout`, `_reached` # # @param scope The scope in which the class should be defined (`bundle` or `namespace`) # @param class_prefix The prefix for the classes defined @@ -214,7 +233,7 @@ body classes results(scope, class_prefix) # This body is a simpler, more consistent version of the body # `scoped_classes_generic`, which see. The key difference is that # fewer classes are defined, and only for outcomes that we can know. -# For example this body does not define "OK/not OK" outcome classes, +# For example this body does not define "OK"/"not OK" outcome classes, # since a promise can be both kept and failed at the same time. # # It's important to understand that promises may do multiple things, @@ -287,6 +306,42 @@ body classes results(scope, class_prefix) "$(class_prefix)_timeout" }; } +body classes diff_results(scope, x) +# @brief Define `x` prefixed/suffixed with promise outcome with command return codes adjusted to align with `diff`. +# @param scope The scope the class should be defined with (`bundle` or `namespace`). +# @param x The unique part of the classes to be defined. +# +# From man diff: +# Exit status is 0 if inputs are the same, 1 if +# different, 2 if trouble. +# +# **Example:** +# +# ```cf3 +# bundle agent example +# { +# commands: +# "/usr/bin/diff" +# args => "/tmp/file1 /tmp/file2", +# classes => diff_results("diff"); +# +# vars: +# "c" slist => classesmatching("diff_.*"); +# +# reports: +# "Found class '$(c)'"; +# "Files Differ!" +# if => "diff_failed|diff_error|diff_not_kept"; +# "Files are the same." +# if => "diff_kept"; +# } +# ``` +{ + inherit_from => results( $(scope), $(x) ); + kept_returncodes => { "0" }; + failed_returncodes => { "1", "2" }; +} + body classes scoped_classes_generic(scope, x) # @brief Define `x` prefixed/suffixed with promise outcome # **See also:** `scope` @@ -332,19 +387,6 @@ bundle edit_line insert_before_if_no_line(before, string) comment => "Prepend a line to the file if it doesn't already exist"; } -bundle edit_line insert_lines(lines) -# @brief Append `lines` if they don't exist in the file -# @param lines The lines to be appended -# -# **See also:** [`insert_lines`][insert_lines] in -# [`edit_line`][bundle edit_line] -{ - insert_lines: - - "$(lines)" - comment => "Append lines if they don't exist"; -} - bundle edit_line insert_file(templatefile) # @brief Reads the lines from `templatefile` and inserts those into the # file being edited. @@ -357,6 +399,60 @@ bundle edit_line insert_file(templatefile) insert_type => "file"; } +bundle edit_line lines_present(lines) +# @brief Ensure `lines` are present in the file. Lines that do not exist are appended to the file +# @param lines List or string that should be present in the file +# +# **Example:** +# +# ```cf3 +# bundle agent example +# { +# vars: +# "nameservers" slist => { "8.8.8.8", "8.8.4.4" }; +# +# files: +# "/etc/resolv.conf" edit_line => lines_present( @(nameservers) ); +# "/etc/ssh/sshd_config" edit_line => lines_present( "PermitRootLogin no" ); +# } +# ``` +{ + insert_lines: + + "$(lines)" + comment => "Append lines if they don't exist"; +} + +bundle edit_line insert_lines(lines) +# @brief Alias for `lines_present` +# @param lines List or string that should be present in the file +{ + insert_lines: + + "$(lines)" + comment => "Append lines if they don't exist"; +} + +bundle edit_line append_if_no_line(lines) +# @brief Alias for `lines_present` +# @param lines List or string that should be present in the file +{ + insert_lines: + + "$(lines)" + comment => "Append lines if they don't exist"; +} + +bundle edit_line append_if_no_lines(lines) +# @brief Alias for `lines_present` +# @param lines List or string that should be present in the file +{ + insert_lines: + + "$(lines)" + comment => "Append lines if they don't exist"; +} + bundle edit_line comment_lines_matching(regex,comment) # @brief Comment lines in the file that matching an [anchored] regex # @param regex Anchored regex that the entire line needs to match @@ -370,6 +466,21 @@ bundle edit_line comment_lines_matching(regex,comment) comment => "Search and replace string"; } +bundle edit_line contains_literal_string(string) +# @brief Ensure the literal string is present in the promised file +# @description If the string is not found in the file it is inserted according +# to CFEngine defaults. +# @param string The string (potentially multiline) to ensure exists in the +# promised file. +{ + + insert_lines: + "$(string)" + insert_type => "preserve_block", + expand_scalars => "false", + whitespace_policy => { "exact_match" }; +} + bundle edit_line uncomment_lines_matching(regex,comment) # @brief Uncomment lines of the file where the regex matches # the entire text after the comment string @@ -438,8 +549,10 @@ bundle edit_line prepend_if_no_line(string) # @brief Prepend `string` if it doesn't exist in the file # @param string The string to be prepended # -# **See also:** [`insert_lines`][insert_lines] in -# [`edit_line`][bundle edit_line] +# **See also:** +# +# * [`insert_lines` promise type][insert_lines] +# * [`edit_line` bundles][edit_line] { insert_lines: "$(string)" @@ -447,28 +560,6 @@ bundle edit_line prepend_if_no_line(string) comment => "Prepend a line to the file if it doesn't already exist"; } -bundle edit_line append_if_no_line(str) -# @ignore -# This duplicates the insert_lines bundle -{ - insert_lines: - - "$(str)" - - comment => "Append a line to the file if it doesn't already exist"; -} - -bundle edit_line append_if_no_lines(list) -# @ignore -# This duplicates the insert_lines bundle -{ - insert_lines: - - "$(list)" - - comment => "Append lines to the file if they don't already exist"; -} - bundle edit_line replace_line_end(start,end) # @brief Give lines starting with `start` the ending given in `end` # @@ -491,6 +582,41 @@ bundle edit_line replace_line_end(start,end) edit_field => line("(^|\s)$(start)\s*", "2", "$(end)","set"); } +bundle edit_line replace_uncommented_substrings( _comment, _find, _replace ) +# @brief Replace all occurrences of `_find` with `_replace` on lines that do not follow a `_comment` +# @param _comment Sequence of characters, each indicating the start of a comment. +# @param _find String matching substring to replace +# @param _replace String to substitute `_find` with +# +# **Example:** +# +# ```cf3 +# bundle agent example_replace_uncommented_substrings +# { +# files: +# "/tmp/file.txt" +# edit_line => replace_uncommented_substrings( "#", "ME", "YOU"); +# } +# ``` +# +# **Notes:** +# +# * Only single character comments are supported as `_comment` is used in the PCRE character group (`[^...]`). +# * `-` in `_comment` is interpreted as a range unless it's used as the first or last character. For example, setting `_comment` to `0-9` means any digit starts a comment. +# +# **History:** +# +# * Introduced 3.17.0, 3.15.3 +{ + vars: + "_reg_match_uncommented_lines_containing_find" + string => "^([^$(_comment)]*)\Q$(_find)\E(.*$)"; + + replace_patterns: + "$(_reg_match_uncommented_lines_containing_find)" + replace_with => text_between_match1_and_match2( $(_replace) ); +} + bundle edit_line append_to_line_end(start,end) # @brief Append `end` to any lines beginning with `start` # @@ -601,28 +727,6 @@ bundle edit_line manage_variable_values_ini(tab, sectionName) vars: "index" slist => getindices("$(tab)[$(sectionName)]"); - # Be careful if the index string contains funny chars - "cindex[$(index)]" string => canonify("$(index)"); - - classes: - "edit_$(cindex[$(index)])" not => strcmp("$($(tab)[$(sectionName)][$(index)])","dontchange"), - comment => "Create conditions to make changes"; - - field_edits: - - # If the line is there, but commented out, first uncomment it - "#+\s*$(index)\s*=.*" - select_region => INI_section(escape("$(sectionName)")), - edit_field => col("=","1","$(index)","set"), - ifvarclass => "edit_$(cindex[$(index)])"; - - # match a line starting like the key something - "$(index)\s*=.*" - edit_field => col("=","2","$($(tab)[$(sectionName)][$(index)])","set"), - select_region => INI_section(escape("$(sectionName)")), - classes => results("bundle", "manage_variable_values_ini_not_$(cindex[$(index)])"), - ifvarclass => "edit_$(cindex[$(index)])"; - delete_lines: ".*" select_region => INI_section(escape("$(sectionName)")), @@ -634,9 +738,7 @@ bundle edit_line manage_variable_values_ini(tab, sectionName) comment => "Insert lines"; "$(index)=$($(tab)[$(sectionName)][$(index)])" - select_region => INI_section(escape("$(sectionName)")), - ifvarclass => "!(manage_variable_values_ini_not_$(cindex[$(index)])_kept|manage_variable_values_ini_not_$(cindex[$(index)])_repaired).edit_$(cindex[$(index)])"; - + select_region => INI_section(escape("$(sectionName)")); } bundle edit_line set_variable_values_ini(tab, sectionName) @@ -667,16 +769,16 @@ bundle edit_line set_variable_values_ini(tab, sectionName) # If the line is there, but commented out, first uncomment it "#+\s*$(index)\s*=.*" - select_region => INI_section("$(sectionName)"), - edit_field => col("=","1","$(index)","set"), - ifvarclass => "edit_$(cindex[$(index)])"; + select_region => INI_section(escape("$(sectionName)")), + edit_field => col("\s*=\s*","1","$(index)","set"), + if => "edit_$(cindex[$(index)])"; # match a line starting like the key something - "$(index)\s*=.*" - edit_field => col("=","2","$($(tab)[$(sectionName)][$(index)])","set"), - select_region => INI_section("$(sectionName)"), + "\s*$(index)\s*=.*" + edit_field => col("\s*=\s*","2","$($(tab)[$(sectionName)][$(index)])","set"), + select_region => INI_section(escape("$(sectionName)")), classes => results("bundle", "set_variable_values_ini_not_$(cindex[$(index)])"), - ifvarclass => "edit_$(cindex[$(index)])"; + if => "edit_$(cindex[$(index)])"; insert_lines: "[$(sectionName)]" @@ -684,8 +786,8 @@ bundle edit_line set_variable_values_ini(tab, sectionName) comment => "Insert lines"; "$(index)=$($(tab)[$(sectionName)][$(index)])" - select_region => INI_section("$(sectionName)"), - ifvarclass => "!(set_variable_values_ini_not_$(cindex[$(index)])_kept|set_variable_values_ini_not_$(cindex[$(index)])_repaired).edit_$(cindex[$(index)])"; + select_region => INI_section(escape("$(sectionName)")), + if => "!(set_variable_values_ini_not_$(cindex[$(index)])_kept|set_variable_values_ini_not_$(cindex[$(index)])_repaired).edit_$(cindex[$(index)])"; } @@ -695,7 +797,7 @@ bundle edit_line insert_ini_section(name, config) # ``` # # given an array "barray" # files: -# "myfile.ini" edit_line => insert_innit_section("foo", "barray"); +# "myfile.ini" edit_line => insert_ini_section("foo", "barray"); # ``` # # Inserts a section in an INI file with the given configuration @@ -705,14 +807,17 @@ bundle edit_line insert_ini_section(name, config) # @param config The fully-qualified name of an associative array containing `v[LHS]="rhs"` { vars: - "k" slist => getindices($(config)); + # TODO: refactor once 3.7.x is EOL + "indices" slist => getindices($(config)); + "k" slist => sort("indices", lex); insert_lines: "[$(name)]" location => start, - comment => "Prepend a line to the file if it doesn't already exist"; + comment => "Insert an ini section with values if not present"; - "$(k)=$($(config)[$(k)])"; + "$(k)=$($(config)[$(k)])" + location => after("[$(name)]"); } bundle edit_line set_quoted_values(v) @@ -770,7 +875,7 @@ bundle edit_line set_quoted_values(v) insert_lines: '$(index)="$($(v)[$(index)])"' comment => "Insert a variable definition", - ifvarclass => "!($(cindex[$(index)])_in_file_kept|$(cindex[$(index)])_in_file_repaired)"; + if => "!($(cindex[$(index)])_in_file_kept|$(cindex[$(index)])_in_file_repaired)"; } bundle edit_line set_variable_values(v) @@ -832,7 +937,7 @@ bundle edit_line set_variable_values(v) "$(index)=$($(v)[$(index)])" comment => "Insert a variable definition", - ifvarclass => "!($(cv)_$(cindex[$(index)])_in_file_kept|$(cv)_$(cindex[$(index)])_in_file_repaired)"; + if => "!($(cv)_$(cindex[$(index)])_in_file_kept|$(cv)_$(cindex[$(index)])_in_file_repaired)"; } bundle edit_line set_config_values(v) @@ -893,7 +998,7 @@ bundle edit_line set_config_values(v) commented occurrence of $(index).", handle => "set_config_values_replace_commented_line", replace_with => value("$(index) $($(v)[$(index)])"), - ifvarclass => "!line_exists_$(cindex[$(index)]).!replace_attempted_$(cindex[$(index)])_reached.!multiple_comments_$(cindex[$(index)])", + if => "!line_exists_$(cindex[$(index)]).!replace_attempted_$(cindex[$(index)])_reached.!multiple_comments_$(cindex[$(index)])", classes => results("bundle", "uncommented_$(cindex[$(index)])"); # If the line is there with the wrong value, replace with @@ -910,13 +1015,13 @@ bundle edit_line set_config_values(v) "$(index) $($(v)[$(index)])" comment => "Insert the value, marker exists $(index)", location => after("^\s*#\s*($(index)\s+.*|$(index))$"), - ifvarclass => "replace_attempted_$(cindex[$(index)])_reached.multiple_comments_$(cindex[$(index)])"; + if => "replace_attempted_$(cindex[$(index)])_reached.multiple_comments_$(cindex[$(index)])"; # If the line doesn't exist and there are no occurrences # of the LHS commented out, insert a new line at the eof "$(index) $($(v)[$(index)])" comment => "Insert the value, marker doesn't exist $(index)", - ifvarclass => "replace_attempted_$(cindex[$(index)])_reached.!multiple_comments_$(cindex[$(index)])"; + if => "replace_attempted_$(cindex[$(index)])_reached.!multiple_comments_$(cindex[$(index)])"; } @@ -946,9 +1051,12 @@ bundle edit_line set_line_based(v, sep, bp, kp, cp) # Adds a new line if none exists or if more than one commented-out # possible matches exist. # +# +# **Note:** If the data structure being used for the first parameter is in the current bundle, you can use `$(this.bundle).variable`. +# # Originally `set_config_values` by Ed King. # -# @param v The fully-qualified name of an associative array containing `v[LHS]="rhs"` +# @param v The fully-qualified name (`bundlename.variable`) of an associative array containing `v[LHS]="rhs"` # @param sep The separator to insert, e.g. ` ` for space-separated # @param bp The key-value separation regex, e.g. `\s+` for space-separated # @param kp The keys to select from v, use `.*` for all @@ -982,10 +1090,33 @@ bundle edit_line set_line_based(v, sep, bp, kp, cp) classes: + # 3.21.0 and greater know about a file being emptied before editing and + # skip this check since it does not make sense. +@if minimum_version(3.21) # Check to see if this line exists "exists_$(ci[$(i)])" expression => regline("^\s*($(i)$(bp).*|$(i))$", - $(edit.filename)); + $(edit.filename)), + unless => strcmp( "true", $(edit.empty_before_use) ); +@endif + +@if minimum_version(3.18) + !(cfengine_3_18_0|cfengine_3_18_1|cfengine_3_18_2):: + "exists_$(ci[$(i)])" + expression => regline("^\s*($(i)$(bp).*|$(i))$", + $(edit.filename)), + unless => strcmp( "true", $(edit.empty_before_use) ); +@endif + + (cfengine_3_15|cfengine_3_16|cfengine_3_17|cfengine_3_18_0|cfengine_3_18_1|cfengine_3_18_2|cfengine_3_19|cfengine_3_20):: + # Version 3.15.0 does not know about the before_version macro, so we keep the same behavior + # TODO Remove after 3.21 is no longer supported. (3.15.0 was supported when 3.21 was released) + # Check to see if this line exists + "exists_$(ci[$(i)])" + expression => regline("^\s*($(i)$(bp).*|$(i))$", + $(edit.filename)); + + any:: # if there's more than one comment, just add new (don't know who to use) "multiple_comments_$(ci[$(i)])" @@ -999,7 +1130,7 @@ bundle edit_line set_line_based(v, sep, bp, kp, cp) "^$(cp)($(i)$(bp).*|$(i))$" comment => "Uncommented the value '$(i)'", replace_with => value("$(i)$(sep)$($(v)[$(i)])"), - ifvarclass => "!exists_$(ci[$(i)]).!replace_attempted_$(ci[$(i)])_reached.!multiple_comments_$(ci[$(i)])", + if => "!exists_$(ci[$(i)]).!replace_attempted_$(ci[$(i)])_reached.!multiple_comments_$(ci[$(i)])", classes => results("bundle", "uncommented_$(ci[$(i)])"); # If the line is there with the wrong value, replace with @@ -1016,18 +1147,18 @@ bundle edit_line set_line_based(v, sep, bp, kp, cp) "$(i)$(sep)$($(v)[$(i)])" comment => "Insert the value, marker '$(i)' exists", location => after("^$(cp)($(i)$(bp).*|$(i))$"), - ifvarclass => "replace_attempted_$(ci[$(i)])_reached.multiple_comments_$(ci[$(i)])"; + if => "replace_attempted_$(ci[$(i)])_reached.multiple_comments_$(ci[$(i)])"; # If the line doesn't exist and there are no occurrences # of the LHS commented out, insert a new line at the eof "$(i)$(sep)$($(v)[$(i)])" comment => "Insert the value, marker '$(i)' doesn't exist", - ifvarclass => "replace_attempted_$(ci[$(i)])_reached.!multiple_comments_$(ci[$(i)]).!exists_$(ci[$(i)])"; + if => "replace_attempted_$(ci[$(i)])_reached.!multiple_comments_$(ci[$(i)]).!exists_$(ci[$(i)])"; reports: verbose_mode|EXTRA:: - "$(this.bundle): Line for '$(i)' exists" ifvarclass => "exists_$(ci[$(i)])"; - "$(this.bundle): Line for '$(i)' does not exist" ifvarclass => "!exists_$(ci[$(i)])"; + "$(this.bundle): Line for '$(i)' exists" if => "exists_$(ci[$(i)])"; + "$(this.bundle): Line for '$(i)' does not exist" if => "!exists_$(ci[$(i)])"; } bundle edit_line set_config_values_matching(v,pat) @@ -1069,12 +1200,11 @@ bundle edit_line set_config_values_matching(v,pat) insert_lines: "$(index) $($(v)[$(index)])" - ifvarclass => "replace_attempted_$(cindex[$(index)])_reached"; + if => "replace_attempted_$(cindex[$(index)])_reached"; } bundle edit_line maintain_key_values(v,sep) -# @ignore # @brief Sets the RHS of configuration items with an giving separator # # Contributed by David Lee @@ -1113,7 +1243,7 @@ bundle edit_line maintain_key_values(v,sep) insert_lines: "$(index)$(sep)$($(v)[$(index)])" comment => "Insert definition of $(index)", - ifvarclass => "!$(cindex[$(index)])_key_in_file"; + if => "!$(cindex[$(index)])_key_in_file"; } bundle edit_line append_users_starting(v) @@ -1137,7 +1267,7 @@ bundle edit_line append_users_starting(v) "$($(v)[$(index)])" comment => "Append users into a password file format", - ifvarclass => "add_$(index)"; + if => "add_$(index)"; } bundle edit_line append_groups_starting(v) @@ -1161,7 +1291,7 @@ bundle edit_line append_groups_starting(v) "$($(v)[$(index)])" comment => "Append users into a group file format", - ifvarclass => "add_$(index)"; + if => "add_$(index)"; } @@ -1183,19 +1313,51 @@ bundle edit_line set_colon_field(key,field,val) bundle edit_line set_user_field(user,field,val) # @brief Set the value of field number "field" in a `:-field` # formatted file like `/etc/passwd` -# @param user The user to be modified +# @param user A regular expression matching the user(s) to be modified # @param field The field that should be modified # @param val The value for `field` # # **Note:** To manage local users with CFEngine 3.6 and later, # consider making `users` promises instead of modifying system files. +# +# **See also:** +# +# * [bundle edit_line set_escaped_user_field][lib/files.cf#set_escaped_user_field] +# * [edit_line field_edits][field_edits] { field_edits: "$(user):.*" - comment => "Edit a user attribute in the password file", - edit_field => col(":","$(field)","$(val)","set"); + comment => "Edit a user attribute in the password file", + edit_field => col(":","$(field)","$(val)","set"); +} + +bundle edit_line set_escaped_user_field(user,field,val) +# @brief Set the value of field number "field" in a `:-field` +# formatted file like `/etc/passwd` +# @param user The user to be modified +# @param field The field that should be modified +# @param val The value for `field` +# +# **Note:** To manage local users with CFEngine 3.6 and later, +# consider making `users` promises instead of modifying system files. +# +# **See also:** +# +# * [bundle edit_line set_user_field][lib/files.cf#set_user_field] +# * [edit_line field_edits][field_edits] +{ + vars: + "escaped_user" + string => escape( "$(user)" ); + + field_edits: + + "$(escaped_user):.*" + + comment => "Edit a user attribute in the password file", + edit_field => col(":","$(field)","$(val)","set"); } bundle edit_line append_user_field(group,field,allusers) @@ -1208,16 +1370,12 @@ bundle edit_line append_user_field(group,field,allusers) # **Note:** To manage local users with CFEngine 3.6 and later, # consider making `users` promises instead of modifying system files. { - vars: - - "val" slist => { @(allusers) }; - field_edits: "$(group):.*" comment => "Append users into a password file format", - edit_field => col(":","$(field)","$(val)","alphanum"); + edit_field => col(":","$(field)","$(allusers)","alphanum"); } bundle edit_line expand_template(templatefile) @@ -1256,7 +1414,7 @@ bundle edit_line replace_or_add(pattern,line) insert_lines: "$(line)" - ifvarclass => "replace_$(cline)_reached"; + if => "replace_$(cline)_reached"; } bundle edit_line converge(marker, lines) @@ -1267,16 +1425,72 @@ bundle edit_line converge(marker, lines) # # @param marker The marker (not a regular expression; will be escaped) # @param lines The lines to insert; all must contain `marker` +# +# **Example:** +# +# ```cf3 +# bundle agent pam_d_su_include +# #@brief Ensure /etc/pam.d/su has includes configured properly +# { +# files: +# ubuntu:: +# "/etc/pam.d/su" +# edit_line => converge( "@include", "@include common-auth +# @include common-account +# @include common-session"); +# } +# ``` +# +# **History:** +# +# * Introduced in 3.6.0 { vars: "regex" string => escape($(marker)); delete_lines: - "$(regex)" comment => "Delete lines matching the marker"; + ".*$(regex).*" comment => "Delete lines matching the marker"; insert_lines: "$(lines)" comment => "Insert the given lines"; } +bundle edit_line converge_prepend(marker, lines) +# @brief Converge `lines` marked with `marker` to start of content +# +# Any content marked with `marker` is removed, then `lines` are +# inserted at *start* of content. Every `line` should contain `marker`. +# +# @param marker The marker (not a regular expression; will be escaped) +# @param lines The lines to insert; all must contain `marker` +# +# **Example:** +# +# ```cf3 +# bundle agent pam_d_su_session +# #@brief Ensure /etc/pam.d/su has session configured properly +# { +# files: +# ubuntu:: +# "/etc/pam.d/su" +# edit_line => converge_prepend( "session", "session required pam_env.so readenv=1 envfile=/etc/default/locale +# session optional pam_mail.so nopen +# session required pam_limits.so" ); +# } +# ``` +# +# **History:** +# +# * Introduced in 3.17.0, 3.15.3, 3.12.6 +{ + vars: + "regex" string => escape($(marker)); + + delete_lines: + ".*$(regex).*" comment => "Delete lines matching the marker"; + insert_lines: + "$(lines)" location => start, comment => "Insert the given lines"; +} + bundle edit_line fstab_option_editor(method, mount, option) # @brief Add or remove `/etc/fstab` options for a mount # @@ -1329,7 +1543,8 @@ body edit_field fstab_options(newval, method) body edit_field quoted_var(newval,method) # @brief Edit the quoted value of the matching line # @param newval The new value -# @param method The method by which to edit the field +# @param method The method by which to edit the field (append|prepend|alphanum|set|delete) +# Ref https://docs.cfengine.com/latest/reference-promise-types-files-edit_line-field_edits.html#field_operation { field_separator => "\""; select_field => "2"; @@ -1372,6 +1587,14 @@ body edit_field line(split,col,newval,method) allow_blank_fields => "true"; } +body replace_with text_between_match1_and_match2( _text ) +# @brief Replace matched line with substituted string +# @param _text String to substitute between first and second match +{ + replace_value => "$(match.1)$(_text)$(match.2)"; + occurrences => "all"; +} + body replace_with value(x) # @brief Replace matching lines # @param x The replacement string @@ -1472,6 +1695,8 @@ body copy_from remote_dcp(from,server) # # @param from The location of the file on the remote server # @param server The hostname or IP of the server from which to download +# +# **See Also:** `local_dcp()` { servers => { "$(server)" }; source => "$(from)"; @@ -1479,17 +1704,42 @@ body copy_from remote_dcp(from,server) } body copy_from local_cp(from) -# @brief Copy a local file. -# +# @brief Copy a file if the modification time or creation time of the source +# file is newer (the default comparison mechanism). # @param from The path to the source file. +# +# **Example:** +# +# ```cf3 +# bundle agent example +# { +# files: +# "/tmp/file.bak" +# copy_from => local_cp("/tmp/file"); +# } +# ``` +# +# **See Also:** `local_dcp()` { source => "$(from)"; } body copy_from local_dcp(from) -# @brief Copy a local file if it is different from the existing copy. -# +# @brief Copy a local file if the hash on the source file differs. # @param from The path to the source file. +# +# **Example:** +# +# ```cf3 +# bundle agent example +# { +# files: +# "/tmp/file.bak" +# copy_from => local_dcp("/tmp/file"); +# } +# ``` +# +# **See Also:** `local_cp()`, `remote_dcp()` { source => "$(from)"; compare => "digest"; @@ -1525,19 +1775,52 @@ body copy_from backup_local_cp(from) } body copy_from seed_cp(from) -# @brief Copy a local file if the file does not already exist, i.e. seed the placement -# +# @brief Copy a local file if the file does not already exist, i.e. seed the +# placement # @param from The path to the source file. +# +# **Example:** +# +# ```cf3 +# bundle agent home_dir_init +# { +# files: +# "/home/mark.burgess/." +# copy_from => seed_cp("/etc/skel"), +# depth_search => recurse(inf), +# file_select => all, +# comment => "We want to be sure that the home directory has files that are +# present in the skeleton."; +# } +# ``` { source => "$(from)"; compare => "exists"; } body copy_from sync_cp(from,server) -# @brief Download a file if the local copy does not already exist, i.e. seed the placement +# @brief Synchronize a file with a remote server. +# +# * If the file does not exist on the remote server then it should be purged. +# * Allow types to change (directories to files and vice versa). +# * The mode of the remote file should be preserved. +# * Files are compared using the default comparison (mtime or ctime). # # @param from The location of the file on the remote server # @param server The hostname or IP of the server from which to download +# +# **Example**: +# +# ```cf3 +# files: +# "/tmp/masterfiles/." +# copy_from => sync_cp( "/var/cfengine/masterfiles", $(sys.policy_server) ), +# depth_search => recurse(inf), +# file_select => all, +# comment => "Mirror masterfiles from the hub to a temporary directory"; +# ``` +# +# **See Also:** `dir_sync()`, `copyfrom_sync()` { servers => { "$(server)" }; source => "$(from)"; @@ -1555,6 +1838,17 @@ body copy_from no_backup_cp(from) copy_backup => "false"; } +body copy_from no_backup_cp_compare(from, comparison) +# @brief Copy a local file (`from`) based on comparison (`comparison`) and don't make any backup of the previous version +# +# @param from The path to the source file. +# @param comparison The comparison to use. (mtime|ctime|atime|exists|binary|hash|digest) +{ + source => "$(from)"; + copy_backup => "false"; + compare => "$(comparison)"; +} + body copy_from no_backup_dcp(from) # @brief Copy a local file if contents have changed, and don't make any backup # of the previous version @@ -1580,7 +1874,14 @@ body perms m(mode) # @param mode The new mode { mode => "$(mode)"; - rxdirs => "true"; + +#+begin_ENT-951 +# Remove after 3.20 is not supported + rxdirs => "true"; +@if minimum_version(3.20) + rxdirs => "false"; +@endif +#+end } body perms mo(mode,user) @@ -1590,7 +1891,14 @@ body perms mo(mode,user) { owners => { "$(user)" }; mode => "$(mode)"; - rxdirs => "true"; + +#+begin_ENT-951 +# Remove after 3.20 is not supported + rxdirs => "true"; +@if minimum_version(3.20) + rxdirs => "false"; +@endif +#+end } body perms mog(mode,user,group) @@ -1602,7 +1910,14 @@ body perms mog(mode,user,group) owners => { "$(user)" }; groups => { "$(group)" }; mode => "$(mode)"; - rxdirs => "true"; + +#+begin_ENT-951 +# Remove after 3.20 is not supported + rxdirs => "true"; +@if minimum_version(3.20) + rxdirs => "false"; +@endif +#+end } body perms og(u,g) @@ -1633,15 +1948,44 @@ body perms system_owned(mode) # ``` { mode => "$(mode)"; - owners => { "root" }; - groups => { "$(sys.user_data[gid])" }; - rxdirs => "true"; -} +#+begin_ENT-951 +# Remove after 3.20 is not supported + rxdirs => "true"; +@if minimum_version(3.20) + rxdirs => "false"; +@endif +#+end + + !windows:: + owners => { "root" }; + + windows:: + + # NOTE: Setting owners will generate an error if the policy is not being + # executed as the user who's ownership is being targeted. While it seems + # that should typically be Administrator or SYSTEM, both are reported to + # result in errors by users, thus owners is currently omitted for Windows. + + # ENT-9778 + groups => { "Administrators" }; + + freebsd|openbsd|netbsd|darwin:: + groups => { "wheel" }; + + linux:: + groups => { "root" }; + + solaris:: + groups => { "sys" }; + + aix:: + groups => { "system" }; +} body depth_search recurse(d) # @brief Search files and direcories recursively, up to the specified depth -# Directories on different devices are included. +# Directories on different devices are excluded. # # @param d The maximum search depth { @@ -1662,7 +2006,7 @@ body depth_search recurse_ignore(d,list) body depth_search recurse_with_base(d) # @brief Search files and directories recursively up to the specified -# depth, starting from the base directory and including directories on +# depth, starting from the base directory excluding directories on # other devices. # # @param d The maximum search depth @@ -1844,10 +2188,10 @@ bundle agent file_make(file, str) reports: "DEBUG|DEBUG_$(this.bundle)":: "DEBUG $(this.bundle): creating $(file) with contents '$(str)'" - ifvarclass => "!summarize"; + if => "!summarize"; "DEBUG $(this.bundle): creating $(file) with contents '$(summary)'" - ifvarclass => "summarize"; + if => "summarize"; } bundle agent file_make_mog(file, str, mode, owner, group) @@ -1885,10 +2229,71 @@ bundle agent file_make_mog(file, str, mode, owner, group) reports: "DEBUG|DEBUG_$(this.bundle)":: "DEBUG $(this.bundle): creating $(file) with contents '$(str)', mode '$(mode)', owner '$(owner)' and group '$(group)'" - ifvarclass => "!summarize"; + if => "!summarize"; "DEBUG $(this.bundle): creating $(file) with contents '$(summary)', mode '$(mode)', owner '$(owner)' and group '$(group)'" - ifvarclass => "summarize"; + if => "summarize"; +} + +bundle agent file_make_mustache(file, template, data) +# @brief Make a file from a mustache template +# @param file Target file to render +# @param template Path to mustache template +# @param data Data container to use +# +# **Example:** +# +# ```cf3 +# vars: +# "state" data => datastate(); +# +# methods: +# "" usebundle => file_make_mustache( "/tmp/z.txt", "/tmp/z.mustache", @(state) ); +# ``` +{ + files: + "$(file)" + create => "true", + edit_template => "$(template)", + template_method => "mustache", + template_data => @(data); + + reports: + "DEBUG|DEBUG_$(this.bundle)":: + "DEBUG $(this.bundle): rendering $(file) with template '$(template)'"; +} + +bundle agent file_make_mustache_with_perms(file, template, data, mode, owner, group) +# @brief Make a file from a mustache template +# @param file Target file to render +# @param template Path to mustache template +# @param data Data container to use +# @param mode File permissions +# @param owner Target file owner +# @param group Target file group +# +# **Example:** +# +# ```cf3 +# vars: +# "state" data => datastate(); +# +# methods: +# "" usebundle => file_make_mustache( "/tmp/z.txt", "/tmp/z.mustache", @(state), +# 600, "root", "root" ); +# ``` +{ + files: + "$(file)" + create => "true", + edit_template => "$(template)", + template_method => "mustache", + perms => mog( $(mode), $(owner), $(group) ), + template_data => @(data); + + reports: + "DEBUG|DEBUG_$(this.bundle)":: + "DEBUG $(this.bundle): rendering $(file) with template '$(template)'"; } bundle agent file_empty(file) diff --git a/tests/load/run_lastseen_threaded_load.sh b/tests/load/run_lastseen_threaded_load.sh index aebcf21a91..64293cbb9a 100755 --- a/tests/load/run_lastseen_threaded_load.sh +++ b/tests/load/run_lastseen_threaded_load.sh @@ -1,10 +1,11 @@ #!/bin/sh -if [ "x$label" = "xPACKAGES_x86_64_solaris_10" ] ; -then - echo "Skipping lastseen_threaded_load on $label" +for skip_label in PACKAGES_x86_64_solaris_10 PACKAGES_ia64_hpux_11.23; do + if [ "$label" = "$skip_label" ]; then + echo "Skipping $0 on label $skip_label" exit 0; -fi + fi +done echo "Starting run_lastseen_threaded_load.sh test" diff --git a/tests/static-check/run_checks.sh b/tests/static-check/run_checks.sh index c5cd3120d5..b7e7c39325 100755 --- a/tests/static-check/run_checks.sh +++ b/tests/static-check/run_checks.sh @@ -3,32 +3,47 @@ set -x n_procs="$(getconf _NPROCESSORS_ONLN)" +use_procs=$((n_procs/2)) +if [ "$use_procs" -lt "0" ]; then + use_procs=1 +fi function check_with_gcc() { + # previous runs may have cached configuration based on a different CC rm -f config.cache make clean - ./configure -C --enable-debug CC=gcc + # here --config-cache enables lots of checks in subdir libntech to re-use checks made in core + ./configure --config-cache --enable-debug CC=gcc local gcc_exceptions="-Wno-sign-compare -Wno-enum-int-mismatch" - make -j -l${n_procs} --keep-going CFLAGS="-Werror -Wall -Wextra $gcc_exceptions" + make -j -l${use_procs} --keep-going CFLAGS="-Werror -Wall -Wextra $gcc_exceptions" } function check_with_clang() { + # previous runs may have cached configuration based on a different CC rm -f config.cache make clean - ./configure -C --enable-debug CC=clang - make -j -l${n_procs} --keep-going CFLAGS="-Werror -Wall -Wextra -Wno-sign-compare" + # here --config-cache enables lots of checks in subdir libntech to re-use checks made in core + ./configure --config-cache --enable-debug CC=clang + make -j -l${use_procs} --keep-going CFLAGS="-Werror -Wall -Wextra -Wno-sign-compare" } function check_with_cppcheck() { + # previous runs may have cached configuration based on a different CC rm -f config.cache - ./configure -C --enable-debug + make clean + # here --config-cache enables lots of checks in subdir libntech to re-use checks made in core + ./configure --config-cache --enable-debug + make -C libpromises/ bootstrap.inc # needed by libpromises/bootstrap.c + + # print out cppcheck version for comparisons over time in case of regressions due to newer versions + cppcheck --version # cppcheck options: # -I -- include paths # -i -- ignored files/folders # --include= -- force including a file, e.g. config.h # Identified issues are printed to stderr - cppcheck --quiet -j${n_procs} --error-exitcode=1 ./ \ + cppcheck --quiet -j${use_procs} --error-exitcode=1 ./ \ --suppressions-list=tests/static-check/cppcheck_suppressions.txt \ --check-level=exhaustive \ --include=config.h \ @@ -41,6 +56,13 @@ cd "$(dirname $0)"/../../ failure=0 failures="" + +# in jenkins the workdir is already autogen'd +# in github it is not, so do that work here +if [ ! -f configure ]; then + NO_CONFIGURE=1 ./autogen.sh --enable-debug +fi + check_with_gcc || { failures="${failures}FAIL: GCC check failed\n"; failure=1; } check_with_clang || { failures="${failures}FAIL: Clang check failed\n"; failure=1; } check_with_cppcheck || { failures="${failures}FAIL: cppcheck failed\n"; failure=1; } diff --git a/tests/unit/Makefile.am b/tests/unit/Makefile.am index 26c3b4c28c..88a7db4d72 100644 --- a/tests/unit/Makefile.am +++ b/tests/unit/Makefile.am @@ -52,15 +52,7 @@ AM_CFLAGS = $(PTHREAD_CFLAGS) check_LTLIBRARIES = libtest.la -libtest_la_SOURCES = cmockery.c cmockery.h schema.h test.c test.h \ - ../../libntech/libutils/alloc.c \ - ../../libpromises/patches.c \ - ../../libpromises/constants.c \ - ../../libntech/libutils/known_dirs.c \ - ../../libntech/libutils/map.c \ - ../../libntech/libutils/array_map.c \ - ../../libntech/libutils/hash.c \ - ../../libntech/libutils/hash_map.c +libtest_la_SOURCES = cmockery.c cmockery.h schema.h test.c test.h libtest_la_LIBADD = ../../libntech/libcompat/libcompat.la @@ -106,6 +98,7 @@ libdb_la_LIBADD = libstr.la ../../libntech/libutils/libutils.la libdb_la_CFLAGS = $(AM_CFLAGS) check_PROGRAMS = \ + processes_select_test \ arg_split_test \ assoc_test \ getopt_test \ @@ -164,7 +157,8 @@ check_PROGRAMS = \ policy_server_test \ split_process_line_test \ new_packages_promise_test \ - iteration_test + iteration_test \ + protocol_recv_overflow_test if HAVE_AVAHI_CLIENT if HAVE_AVAHI_COMMON @@ -196,12 +190,21 @@ if MACOSX XFAIL_TESTS = set_domainname_test XFAIL_TESTS += process_test XFAIL_TESTS += mon_processes_test +XFAIL_TESTS += rlist_test +endif + +if AIX +XFAIL_TESTS = rlist_test endif if HPUX XFAIL_TESTS = mon_load_test # Redmine #3569 endif + +processes_select_test_SOURCES = processes_select_test.c +processes_select_test_LDADD = libtest.la ../../libpromises/libpromises.la + # # OS X uses real system calls instead of our stubs unless this option is used # @@ -269,18 +272,13 @@ db_concurrent_test_SOURCES = db_concurrent_test.c db_concurrent_test_LDADD = libdb.la lastseen_test_SOURCES = lastseen_test.c \ - ../../libpromises/item_lib.c \ - ../../libpromises/lastseen.c \ ../../libntech/libutils/statistics.c #lastseen_test_CPPFLAGS = $(libdb_la_CPPFLAGS) -lastseen_test_LDADD = libdb.la ../../libpromises/libpromises.la +lastseen_test_LDADD = libtest.la ../../libpromises/libpromises.la -lastseen_migration_test_SOURCES = lastseen_migration_test.c \ - ../../libpromises/lastseen.c \ - ../../libntech/libutils/statistics.c \ - ../../libpromises/item_lib.c +lastseen_migration_test_SOURCES = lastseen_migration_test.c #lastseen_migration_test_CPPFLAGS = $(libdb_la_CPPFLAGS) -lastseen_migration_test_LDADD = libdb.la ../../libpromises/libpromises.la +lastseen_migration_test_LDADD = ../../libpromises/libpromises.la CLEANFILES = *.gcno *.gcda cfengine-enterprise.so @@ -303,7 +301,10 @@ files_copy_test_LDADD = libtest.la ../../libpromises/libpromises.la sort_test_SOURCES = sort_test.c sort_test_LDADD = libtest.la ../../libpromises/libpromises.la -logging_test_SOURCES = logging_test.c ../../libpromises/syslog_client.c +logging_test_SOURCES = logging_test.c \ + ../../libpromises/syslog_client.c \ + ../../libpromises/patches.c \ + ../../libpromises/constants.c logging_test_LDADD = libtest.la ../../libntech/libutils/libutils.la connection_management_test_SOURCES = connection_management_test.c \ @@ -313,8 +314,7 @@ connection_management_test_LDADD = ../../libpromises/libpromises.la \ libtest.la \ ../../cf-serverd/libcf-serverd.la -rlist_test_SOURCES = rlist_test.c \ - ../../libpromises/rlist.c +rlist_test_SOURCES = rlist_test.c rlist_test_LDADD = libtest.la ../../libpromises/libpromises.la # Workaround for object file basename conflicts, search the web for # "automake created with both libtool and without" diff --git a/tests/unit/eval_context_test.c b/tests/unit/eval_context_test.c index 7eee8318d8..09e2533e66 100644 --- a/tests/unit/eval_context_test.c +++ b/tests/unit/eval_context_test.c @@ -149,6 +149,51 @@ void test_eval_with_token_from_list(void) StringSetDestroy(time_classes); } +static void test_persistent_class_timer_policy(void) +{ + EvalContext *ctx = EvalContextNew(); + + /* Save a persistent class with PRESERVE policy, 60 minute TTL */ + EvalContextHeapPersistentSave(ctx, "timer_test", 60, + CONTEXT_STATE_POLICY_PRESERVE, "tag1"); + + /* Verify the class loads correctly after PRESERVE save */ + EvalContextHeapPersistentLoadAll(ctx); + + { + const Class *cls = EvalContextClassGet(ctx, "default", "timer_test"); + assert_true(cls != NULL); + assert_string_equal("timer_test", cls->name); + } + + /* Save again with PRESERVE -- the function should early-return + * (class is preserved, not expired, same tags), leaving the DB + * record unchanged. We verify by loading persistent classes and + * checking the class is still defined. */ + EvalContextHeapPersistentSave(ctx, "timer_test", 60, + CONTEXT_STATE_POLICY_PRESERVE, "tag1"); + + /* Class should still be defined after the second PRESERVE save */ + { + const Class *cls = EvalContextClassGet(ctx, "default", "timer_test"); + assert_true(cls != NULL); + assert_string_equal("timer_test", cls->name); + } + + /* Save with RESET policy -- the record SHOULD be overwritten. + * The class should still be loadable afterward. */ + EvalContextHeapPersistentSave(ctx, "timer_test", 60, + CONTEXT_STATE_POLICY_RESET, "tag1"); + + { + const Class *cls = EvalContextClassGet(ctx, "default", "timer_test"); + assert_true(cls != NULL); + assert_string_equal("timer_test", cls->name); + } + + EvalContextDestroy(ctx); +} + int main() { PRINT_TEST_BANNER(); @@ -157,6 +202,7 @@ int main() const UnitTest tests[] = { unit_test(test_class_persistence), + unit_test(test_persistent_class_timer_policy), unit_test(test_changes_chroot), unit_test(test_eval_with_token_from_list), }; diff --git a/tests/unit/evalfunction_test.c b/tests/unit/evalfunction_test.c index 4a69f438f7..b0ba60194a 100644 --- a/tests/unit/evalfunction_test.c +++ b/tests/unit/evalfunction_test.c @@ -1,5 +1,9 @@ #include +/* Protect against duplicate definition of symbol CF_FNCALL_TYPES since we are + * including evalfunction.c */ +#define CFENGINE_EVALFUNCTION_TEST_C + #include #include diff --git a/tests/unit/lastseen_test.c b/tests/unit/lastseen_test.c index 0344a2e59b..4f710bd073 100644 --- a/tests/unit/lastseen_test.c +++ b/tests/unit/lastseen_test.c @@ -70,6 +70,7 @@ static void test_newentry(void) KeyHostSeen q; assert_int_equal(ReadDB(db, "qiSHA-12345", &q, sizeof(q)), true); + assert_false(q.acknowledged); assert_int_equal(q.lastseen, 666); assert_double_close(q.Q.q, 0.0); assert_double_close(q.Q.dq, 0.0); @@ -102,6 +103,7 @@ static void test_update(void) KeyHostSeen q; assert_int_equal(ReadDB(db, "qiSHA-12345", &q, sizeof(q)), true); + assert_false(q.acknowledged); assert_int_equal(q.lastseen, 1110); assert_double_close(q.Q.q, 555.0); assert_double_close(q.Q.dq, 555.0); @@ -662,11 +664,7 @@ void FatalError(ARG_UNUSED char *s, ...) exit(42); } -HashMethod CF_DEFAULT_DIGEST; pthread_mutex_t *cft_output; -char VIPADDRESS[CF_MAX_IP_LEN]; -RSA *PUBKEY; -bool MINUSF; char *HashPrintSafe(ARG_UNUSED char *dst, ARG_UNUSED size_t dst_size, ARG_UNUSED const unsigned char *digest, diff --git a/tests/unit/processes_select_test.c b/tests/unit/processes_select_test.c new file mode 100644 index 0000000000..f9cfbb805e --- /dev/null +++ b/tests/unit/processes_select_test.c @@ -0,0 +1,45 @@ +#include + +#include +#include +#include + +static void test_SplitProcLine_windows(void) +{ + + char buf[CF_BUFSIZE]; + snprintf(buf, sizeof(buf), "%-20s %5s %s %s %8s %8s %-3s %s %s %5s %s", + "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND"); + + char *names[CF_PROCCOLS] = {0}; + int start[CF_PROCCOLS]; + int end[CF_PROCCOLS]; + + GetProcessColumnNames(buf, names, start, end); + + const char *const proc_line = "NETWORK SERVICE 540 0.0 0.3 5092 11180 ? ? Apr28 00:00 C:\\Windows\\system32\\svchost.exe -k RPCSS -p"; + time_t pstime = time(NULL); + + char *column[CF_PROCCOLS] = {0}; + + bool ret = SplitProcLine(proc_line, pstime, names, start, end, PCA_AllColumnsPresent, column); + assert_true(ret); + assert_string_equal(column[0], "NETWORK SERVICE"); + + for (int i = 0; i < CF_PROCCOLS; i++) + { + free(names[i]); + free(column[i]); + } +} + +int main() +{ + PRINT_TEST_BANNER(); + const UnitTest tests[] = + { + unit_test(test_SplitProcLine_windows), + }; + + return run_tests(tests); +} diff --git a/tests/unit/protocol_recv_overflow_test.c b/tests/unit/protocol_recv_overflow_test.c new file mode 100644 index 0000000000..2d2d9945ee --- /dev/null +++ b/tests/unit/protocol_recv_overflow_test.c @@ -0,0 +1,111 @@ +/* + * Regression test for CFE-4687 / cfengine/core PR #6171: + * off-by-one in the ProtocolGet() and ProtocolOpenDir() receive buffers + * in libcfnet/protocol.c. + * + * Background + * ---------- + * The receive primitives NUL-terminate what they read, and the count read + * can equal the requested length: + * + * TLSRecv() tls_generic.c:807 buffer[received] = '\0'; + * RecvSocketStream() classic.c:54 buffer[already] = '\0'; + * + * Both are documented to write up to "toget + 1" bytes (classic.c:5-7), so a + * caller must hand them a buffer of at least toget + 1 bytes. net.c:151 and + * ProtocolStat() (protocol.c:260) honor this with CF_BUFSIZE buffers. + * + * ProtocolOpenDir() and ProtocolGet() did not: they declared + * + * char buf[CF_MSGSIZE]; // CF_MSGSIZE == CF_BUFSIZE - CF_INBAND_OFFSET + * + * and then received up to CF_MSGSIZE bytes into it. A peer that fills the + * record makes "received" reach CF_MSGSIZE, so the terminating NUL is written + * to buf[CF_MSGSIZE] -- one byte past the array. The byte count is peer + * controlled (the transaction length field for OPENDIR, accepted up to + * CF_MSGSIZE at net.c:214), so the write crosses the trust boundary. + * + * What this test does + * ------------------- + * It drives the real ProtocolOpenDir() over a socketpair using the classic + * protocol. The classic data path uses RecvSocketStream(), whose terminator + * write is identical to the TLS path's TLSRecv(), so the same off-by-one is + * surfaced without needing a TLS handshake. A "server" sends a single CF_DONE + * transaction carrying exactly CF_MSGSIZE payload bytes -- the maximum + * ReceiveTransaction() accepts. + * + * On unpatched code the terminating write lands at buf[CF_MSGSIZE] inside + * ProtocolOpenDir()'s stack frame; under AddressSanitizer (the project's + * "ASAN Unit Tests" CI job) this aborts with a stack-buffer-overflow. With the + * fix (buf sized CF_BUFSIZE) the write is in bounds and the test completes. + * + * ProtocolGet() carries the identical defect and the identical one-line fix, + * but receives via TLSRecv() directly, which requires a live SSL session; + * there is no TLS-handshake harness in tests/unit, so it is not driven here. + */ + +#include + +#include +#include /* ProtocolOpenDir */ +#include /* ConnectionInfo* */ +#include /* AgentConnection, CF_MSGSIZE, CF_DONE */ +#include /* SendTransaction */ +#include /* Seq, SeqDestroy */ + +#include +#include +#include + +static void test_opendir_recv_terminator_overflow(void) +{ + int sv[2]; + int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sv); + assert_int_equal(ret, 0); + + /* --- malicious/non-conforming server side (sv[1]) --- */ + ConnectionInfo *server = ConnectionInfoNew(); + ConnectionInfoSetSocket(server, sv[1]); + ConnectionInfoSetProtocolVersion(server, CF_PROTOCOL_CLASSIC); + + /* A record-filling reply: exactly CF_MSGSIZE payload bytes, the maximum + * ReceiveTransaction() permits (net.c:214). CF_DONE so the client's + * receive loop runs exactly once. Content is irrelevant -- the overflow + * happens during the receive, before any payload is interpreted. */ + char payload[CF_MSGSIZE]; + memset(payload, 'A', sizeof(payload)); + + ret = SendTransaction(server, payload, CF_MSGSIZE, CF_DONE); + assert_int_equal(ret, 0); + + /* --- client side (sv[0]): the real vulnerable function --- */ + AgentConnection conn; + memset(&conn, 0, sizeof(conn)); + conn.conn_info = ConnectionInfoNew(); + ConnectionInfoSetSocket(conn.conn_info, sv[0]); + ConnectionInfoSetProtocolVersion(conn.conn_info, CF_PROTOCOL_CLASSIC); + + /* On unpatched code this overflows buf[CF_MSGSIZE] while receiving and + * AddressSanitizer aborts here. On patched code it returns normally. */ + Seq *result = ProtocolOpenDir(&conn, "/tmp"); + + /* Reaching this point means no out-of-bounds write occurred. */ + SeqDestroy(result); + ConnectionInfoDestroy(&conn.conn_info); + ConnectionInfoDestroy(&server); + close(sv[0]); + close(sv[1]); + + assert_true(true); +} + +int main(void) +{ + PRINT_TEST_BANNER(); + const UnitTest tests[] = + { + unit_test(test_opendir_recv_terminator_overflow), + }; + + return run_tests(tests); +} diff --git a/tests/unit/rlist_test.c b/tests/unit/rlist_test.c index 5064fe08a7..688fa9cca9 100644 --- a/tests/unit/rlist_test.c +++ b/tests/unit/rlist_test.c @@ -825,7 +825,6 @@ const void *EvalContextVariableGet(const EvalContext *ctx, const VarRef *lval, D fail(); } -pthread_mutex_t *cft_lock; int __ThreadLock(pthread_mutex_t *name) { return true; diff --git a/tests/unit/set_domainname_test.c b/tests/unit/set_domainname_test.c index 233f065b05..79a0c4863b 100644 --- a/tests/unit/set_domainname_test.c +++ b/tests/unit/set_domainname_test.c @@ -7,11 +7,6 @@ #include #include -/* Global variables we care about */ - -char VFQNAME[CF_MAXVARSIZE]; -char VUQNAME[CF_MAXVARSIZE / 2]; -char VDOMAIN[CF_MAXVARSIZE / 2]; static struct hostent h = { .h_name = "laptop.intra.cfengine.com" diff --git a/tests/valgrind-check/Containerfile b/tests/valgrind-check/Containerfile index a0ef77c9f5..d725752c8c 100644 --- a/tests/valgrind-check/Containerfile +++ b/tests/valgrind-check/Containerfile @@ -1,7 +1,6 @@ FROM ubuntu:22.04 AS build -RUN DEBIAN_FRONTEND=noninteractive apt-get update -y -RUN DEBIAN_FRONTEND=noninteractive apt-get install -y libssl-dev libxml2-dev libpam0g-dev liblmdb-dev libacl1-dev libpcre2-dev -RUN DEBIAN_FRONTEND=noninteractive apt-get install -y python3 git flex bison byacc automake make autoconf libtool valgrind +RUN DEBIAN_FRONTEND=noninteractive apt-get update -y --fix-missing && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y libssl-dev libxml2-dev libpam0g-dev liblmdb-dev libacl1-dev libpcre2-dev python3 git flex bison byacc automake make autoconf libtool valgrind curl COPY masterfiles masterfiles COPY core core WORKDIR core diff --git a/tests/valgrind-check/valgrind.sh b/tests/valgrind-check/valgrind.sh index dfd334196b..3b2e466513 100644 --- a/tests/valgrind-check/valgrind.sh +++ b/tests/valgrind-check/valgrind.sh @@ -120,7 +120,7 @@ print_ps # cf-serverd running under valgrind can be really slow to start, let's give it # some time before we move on and potentially hit the wall if it's actually # malfunctioning -tries=12 # max 2 minutes +tries=24 # max 4 minutes while /var/cfengine/bin/cf-net -H $BOOTSTRAP_IP connect | grep Failed; do tries=$((tries - 1)) if [ $tries -le 0 ]; then