Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 50 additions & 10 deletions src/OVAL/probes/unix/linux/systemdshared.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@

#include <libgen.h>
#include <stdio.h>
#include <string.h>
#include "common/debug_priv.h"
#include "common/list.h"
#include "oscap_helpers.h"
#include "oval_dbus.h"

Expand Down Expand Up @@ -116,7 +118,8 @@
return ret;
}

static int get_all_systemd_units(DBusConnection* conn, int(*callback)(const char *, void *), void *cbarg)
static int get_systemd_units(DBusConnection *conn, const char *method, bool unit_files,

Check failure on line 121 in src/OVAL/probes/unix/linux/systemdshared.h

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 41 to the 25 allowed.

See more on https://sonarcloud.io/project/issues?id=OpenSCAP_openscap&issues=AaHGq4m4lRBT6m4tTYXg&open=AaHGq4m4lRBT6m4tTYXg&pullRequest=2485
struct oscap_htable *seen, int(*callback)(const char *, void *), void *cbarg)
{
DBusMessage *msg = NULL;
DBusPendingCall *pending = NULL;
Expand All @@ -126,7 +129,7 @@
"org.freedesktop.systemd1",
"/org/freedesktop/systemd1",
"org.freedesktop.systemd1.Manager",
"ListUnitFiles"
method
);
if (msg == NULL) {
dD("Failed to create dbus_message via dbus_message_new_method_call!");
Expand Down Expand Up @@ -169,7 +172,7 @@
}

dbus_message_iter_recurse(&args, &unit_iter);
do {
while (dbus_message_iter_get_arg_type(&unit_iter) != DBUS_TYPE_INVALID) {

Check warning on line 175 in src/OVAL/probes/unix/linux/systemdshared.h

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Reduce the number of nested "goto" statements from 4 to 1 authorized.

See more on https://sonarcloud.io/project/issues?id=OpenSCAP_openscap&issues=AaHGq4m4lRBT6m4tTYXh&open=AaHGq4m4lRBT6m4tTYXh&pullRequest=2485
if (dbus_message_iter_get_arg_type(&unit_iter) != DBUS_TYPE_STRUCT) {
dD("Expected unit struct as elements in returned array. Instead received: %s.", dbus_message_type_to_string(dbus_message_iter_get_arg_type(&unit_iter)));
goto cleanup;
Expand All @@ -185,15 +188,40 @@

_DBusBasicValue value;
dbus_message_iter_get_basic(&unit_full_path_and_name, &value);
char *unit_name_s = oscap_strdup(basename(value.str));
oscap_strrm(unit_name_s, "@");
int cbret = callback(unit_name_s, cbarg);
free(unit_name_s);
if (cbret != 0) {
goto cleanup;
if (!unit_files) {
/* Known units can include unresolved dependencies. Do not collect
* dummy properties for names with no corresponding unit. */
DBusMessageIter load_state = unit_full_path_and_name;
if (!dbus_message_iter_next(&load_state) || !dbus_message_iter_next(&load_state)
|| dbus_message_iter_get_arg_type(&load_state) != DBUS_TYPE_STRING)
goto cleanup;
_DBusBasicValue state;
dbus_message_iter_get_basic(&load_state, &state);
if (strcmp(state.str, "not-found") == 0) {
dbus_message_iter_next(&unit_iter);
continue;
}
}
/* ListUnitFiles returns paths, whereas ListUnits returns unit names.
* Never turn a template into a different, nonexistent unit by removing
* its @. Actual instances are returned by ListUnits or have their own
* unit file (for example, an enabled instance symlink).
*/
char *unit_path = oscap_strdup(value.str);
const char *unit_name = unit_files ? basename(unit_path) : unit_path;
const char *instance = strchr(unit_name, '@');
bool is_template = instance != NULL && instance[1] == '.';
if (!is_template && oscap_htable_get(seen, unit_name) == NULL) {
oscap_htable_add(seen, unit_name, (void *) true);
int cbret = callback(unit_name, cbarg);
if (cbret != 0) {
free(unit_path);
goto cleanup;
}
}
free(unit_path);
dbus_message_iter_next(&unit_iter);
}
while (dbus_message_iter_next(&unit_iter));

dbus_message_unref(msg); msg = NULL;

Expand All @@ -209,4 +237,16 @@
return ret;
}

static int get_all_systemd_units(DBusConnection *conn, int(*callback)(const char *, void *), void *cbarg)
{
struct oscap_htable *seen = oscap_htable_new();
/* Keep installed units even when disabled and not currently loaded. Add
* loaded units to include template instances and transient units too. */
int ret = get_systemd_units(conn, "ListUnitFiles", true, seen, callback, cbarg);
if (ret == 0)
ret = get_systemd_units(conn, "ListUnits", false, seen, callback, cbarg);
oscap_htable_free(seen, NULL);
return ret;
}

#endif
6 changes: 6 additions & 0 deletions tests/probes/systemdunitproperty/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
if(ENABLE_PROBES_LINUX)
if(DBUS_FOUND)
add_oscap_ctest("probes/systemdunitproperty/test_systemd_units.sh"
COMMAND bash "${CMAKE_CURRENT_SOURCE_DIR}/test_systemd_units.sh"
LABELS linux linux_only)
set_tests_properties("probes/systemdunitproperty/test_systemd_units.sh" PROPERTIES
SKIP_RETURN_CODE 255
ENVIRONMENT "srcdir=${CMAKE_CURRENT_SOURCE_DIR};builddir=${CMAKE_BINARY_DIR}")
add_oscap_test("test_probes_systemdunitproperty.sh" LABELS linux linux_only)
add_oscap_test("test_probes_systemdunitproperty_mount_wants.sh" LABELS linux linux_only)
add_oscap_test("test_probes_systemdunitproperty_offline_mode.sh" LABELS linux linux_only)
Expand Down
148 changes: 148 additions & 0 deletions tests/probes/systemdunitproperty/test_systemd_units.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Exercise both systemd probes on a private bus, without host systemd or root."""

import os
import re
import shlex
import subprocess
import tempfile
import unittest
import xml.etree.ElementTree as ET
from pathlib import Path

import dbus
import dbusmock


BUS_NAME = 'org.freedesktop.systemd1'
MANAGER_PATH = '/org/freedesktop/systemd1'
MANAGER_IFACE = BUS_NAME + '.Manager'
UNIT_IFACE = BUS_NAME + '.Unit'
DEFINITIONS = 'http://oval.mitre.org/XMLSchema/oval-definitions-5'
LINUX = DEFINITIONS + '#linux'
COMMON = 'http://oval.mitre.org/XMLSchema/oval-common-5'
RESULTS = 'http://oval.mitre.org/XMLSchema/oval-results-5'
SYSCHAR = 'http://oval.mitre.org/XMLSchema/oval-system-characteristics-5#linux'


class SystemdUnitsTest(dbusmock.DBusTestCase):
@classmethod
def setUpClass(cls):
cls.start_session_bus()

def check_units(self, files, loaded, missing=()):
server = self.spawn_server(BUS_NAME, MANAGER_PATH, MANAGER_IFACE)
try:
obj = self.get_dbus().get_object(BUS_NAME, MANAGER_PATH)
mock = dbus.Interface(obj, dbusmock.MOCK_IFACE)
expected = {u for u, _ in files if '@.' not in u} | set(loaded)
# This fake unit models systemd's dummy defaults for a missing name.
# The probes must never query it merely because a template exists.
paths = {u: MANAGER_PATH + '/unit/u' + str(i)
for i, u in enumerate(sorted(expected | set(missing) | {'user-runtime-dir.service'}))}
rows = [(u, u, 'loaded', 'active', 'running', '', paths[u], 0, '', '/')
for u in loaded]
rows += [(u, u, 'not-found', 'inactive', 'dead', '', paths[u], 0, '', '/')
for u in missing]
mock.AddMethods(MANAGER_IFACE, [
('ListUnitFiles', '', 'a(ss)', 'ret = ' + repr([
('/usr/lib/systemd/system/' + u, state) for u, state in files])),
('ListUnits', '', 'a(ssssssouso)', 'ret = ' + repr(rows)),
('LoadUnit', 's', 'o', 'ret = ' + repr(paths) + '[args[0]]'),
])
for unit, path in paths.items():
mock.AddObject(path, UNIT_IFACE, {
'LoadState': 'loaded' if unit in expected else 'not-found',
'Requires': dbus.Array([], signature='s'),
'Wants': dbus.Array([], signature='s'),
}, [])

root = ET.Element('oval_definitions', xmlns=DEFINITIONS)
generator = ET.SubElement(root, 'generator')
for key, value in [('product_name', 'OpenSCAP test'), ('product_version', '1'),
('schema_version', '5.11'), ('timestamp', '2026-01-01T00:00:00')]:
ET.SubElement(generator, '{' + COMMON + '}' + key).text = value
definitions = ET.SubElement(root, 'definitions')
tests = ET.SubElement(root, 'tests')
objects = ET.SubElement(root, 'objects')
cases = ['user-runtime-dir@1000.service', 'user-runtime-dir@.service',
'user-runtime-dir.service', 'disabled.service', 'persist@42.service',
'duplicate.target', 'transient.service', 'missing@1.service', None]
number = 0
for kind in ['systemdunitproperty', 'systemdunitdependency']:
for unit in cases:
number += 1
ident = 'oval:0:{}:' + str(number)
definition = ET.SubElement(definitions, 'definition', {
'id': ident.format('def'), 'class': 'compliance', 'version': '1'})
metadata = ET.SubElement(definition, 'metadata')
ET.SubElement(metadata, 'title').text = 'Systemd unit enumeration'
ET.SubElement(metadata, 'description').text = 'Installed and loaded units'
ET.SubElement(ET.SubElement(definition, 'criteria'), 'criterion',
test_ref=ident.format('tst'))
exists = bool(expected) if unit is None else unit in expected
test = ET.SubElement(tests, kind + '_test', {
'xmlns': LINUX, 'id': ident.format('tst'), 'version': '1',
'check': 'all', 'comment': 'true',
'check_existence': 'at_least_one_exists' if exists else 'none_exist'})
ET.SubElement(test, 'object', object_ref=ident.format('obj'))
objdef = ET.SubElement(objects, kind + '_object', {
'xmlns': LINUX, 'id': ident.format('obj'), 'version': '1'})
ET.SubElement(objdef, 'unit', operation='pattern match').text = (
'.*' if unit is None else '^' + re.escape(unit) + '$')
if kind == 'systemdunitproperty':
ET.SubElement(objdef, 'property').text = 'LoadState'

env = dict(os.environ, DBUS_SYSTEM_BUS_ADDRESS=os.environ['DBUS_SESSION_BUS_ADDRESS'])
with tempfile.TemporaryDirectory() as tmp:
source, result = Path(tmp) / 'input.xml', Path(tmp) / 'results.xml'
ET.ElementTree(root).write(source, encoding='utf-8', xml_declaration=True)
run = subprocess.run(shlex.split(os.environ['OSCAP']) + [
'oval', 'eval', '--results', str(result), str(source)],
env=env, text=True, capture_output=True, timeout=30)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
self.assertEqual(run.stderr, '')
collected = ET.parse(result)
evaluated = collected.findall('.//{' + RESULTS + '}definition')
self.assertEqual(len(evaluated), number)
for definition in evaluated:
self.assertEqual(definition.get('result'), 'true', definition.attrib)
for kind in ['systemdunitproperty', 'systemdunitdependency']:
items = collected.findall('.//{' + SYSCHAR + '}' + kind + '_item')
names = [item.find('{' + SYSCHAR + '}unit').text for item in items]
self.assertEqual(set(names), expected)
calls = mock.GetMethodCalls('LoadUnit')
loaded_names = [str(args[0]) for _, args in calls]
self.assertNotIn('user-runtime-dir.service', loaded_names)
self.assertNotIn('user-runtime-dir@.service', loaded_names)
self.assertNotIn('missing@1.service', loaded_names)
if 'duplicate.target' in expected:
# Exact and wildcard queries from each probe, with no duplicate
# callbacks from the two lists (or duplicate entries in a list).
self.assertEqual(loaded_names.count('duplicate.target'), 4)
finally:
server.terminate()
server.wait()

def test_installed_and_loaded(self):
self.check_units([
('user-runtime-dir@.service', 'static'), ('disabled.service', 'disabled'),
('duplicate.target', 'enabled'), ('duplicate.target', 'enabled'),
('persist@42.service', 'enabled')], [
'user-runtime-dir@1000.service', 'duplicate.target', 'transient.service'])

def test_no_loaded_units(self):
self.check_units([('disabled.service', 'disabled'), ('persist@42.service', 'enabled')], [])

def test_no_installed_units(self):
self.check_units([], ['user-runtime-dir@1000.service', 'transient.service'])

def test_missing_loaded_unit(self):
self.check_units([], ['transient.service'], ['missing@1.service', 'user-runtime-dir.service'])

def test_empty_lists(self):
self.check_units([], [])


if __name__ == '__main__':
unittest.main()
17 changes: 17 additions & 0 deletions tests/probes/systemdunitproperty/test_systemd_units.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env bash

. $builddir/tests/test_common.sh

set -e -o pipefail

function test_systemd_units {
probecheck "systemdunitproperty" || return 255
probecheck "systemdunitdependency" || return 255
require_python_module "dbusmock" || return 255
require "dbus-daemon" || return 255

# The Python fixture starts a private bus. It never talks to host systemd.
python3 "${srcdir}/test_systemd_units.py"
}

test_run "Systemd probes enumerate installed units and real instances" test_systemd_units