From d97687c12ba6cbca1d732534ff7394bd14547d92 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20=C4=8Cern=C3=BD?= <jcerny@redhat.com>
Date: Fri, 10 Sep 2021 14:53:42 +0200
Subject: [PATCH] Add an alternative source of hostname
If /etc/hostname can't be read, we will try to open /proc/sys/kernel/hostname instead.
Resolves: rhbz#1977668
---
src/XCCDF/result.c | 5 ++++
tests/API/XCCDF/unittests/CMakeLists.txt | 1 +
.../XCCDF/unittests/test_results_hostname.sh | 26 +++++++++++++++++++
3 files changed, 32 insertions(+)
create mode 100755 tests/API/XCCDF/unittests/test_results_hostname.sh
diff --git a/src/XCCDF/result.c b/src/XCCDF/result.c
index 91fcc6041d..c0ad4b926f 100644
--- a/src/XCCDF/result.c
+++ b/src/XCCDF/result.c
@@ -271,6 +271,11 @@ static char *_get_etc_hostname(const char *oscap_probe_root)
fp = oscap_fopen_with_prefix(oscap_probe_root, "/etc/hostname");
+ if (fp == NULL) {
+ dD("Trying to use /proc/sys/kernel/hostname instead of /etc/hostname");
+ fp = oscap_fopen_with_prefix(oscap_probe_root, "/proc/sys/kernel/hostname");
+ }
+
if (fp == NULL)
goto fail;
diff --git a/tests/API/XCCDF/unittests/CMakeLists.txt b/tests/API/XCCDF/unittests/CMakeLists.txt
index 52645834c4..6549538440 100644
--- a/tests/API/XCCDF/unittests/CMakeLists.txt
+++ b/tests/API/XCCDF/unittests/CMakeLists.txt
@@ -101,3 +101,4 @@ add_oscap_test("test_fix_arf.sh")
add_oscap_test("test_fix_resultid_by_suffix.sh")
add_oscap_test("test_generate_fix_ansible_vars.sh")
add_oscap_test("test_xccdf_requires_conflicts.sh")
+add_oscap_test("test_results_hostname.sh")
diff --git a/tests/API/XCCDF/unittests/test_results_hostname.sh b/tests/API/XCCDF/unittests/test_results_hostname.sh
new file mode 100755
index 0000000000..c4408affbb
--- /dev/null
+++ b/tests/API/XCCDF/unittests/test_results_hostname.sh
@@ -0,0 +1,26 @@
+#!/usr/bin/env bash
+. $builddir/tests/test_common.sh
+
+set -e
+set -o pipefail
+
+result=$(mktemp)
+tmpdir=$(mktemp -d)
+
+export OSCAP_PROBE_ROOT="$tmpdir"
+
+mkdir -p "$tmpdir/etc"
+echo "hostname_defined_in_etc_hostname" > "$tmpdir/etc/hostname"
+$OSCAP xccdf eval --results "$result" "$srcdir/test_single_rule.ds.xml" || ret=$?
+assert_exists 1 '/Benchmark/TestResult/target[text()="hostname_defined_in_etc_hostname"]'
+assert_exists 0 '/Benchmark/TestResult/target[text()="hostname_defined_in_proc_sys_kernel"]'
+
+rm -rf "$tmpdir/etc/hostname"
+mkdir -p "$tmpdir/proc/sys/kernel/"
+echo "hostname_defined_in_proc_sys_kernel" > "$tmpdir/proc/sys/kernel/hostname"
+$OSCAP xccdf eval --results "$result" "$srcdir/test_single_rule.ds.xml" || ret=$?
+assert_exists 0 '/Benchmark/TestResult/target[text()="hostname_defined_in_etc_hostname"]'
+assert_exists 1 '/Benchmark/TestResult/target[text()="hostname_defined_in_proc_sys_kernel"]'
+
+rm -f "$result"
+rm -rf "$tmpdir"