From 7204ae0f390886459600902addd5ccbbe2a4b925 Mon Sep 17 00:00:00 2001
From: Marco Fargetta <mfargett@redhat.com>
Date: Wed, 15 Jan 2025 16:00:12 +0100
Subject: [PATCH] Replace libselinux restorecon API with CLI

The restorecon API in libselinux has a problem fixing the context if it
is update from the same script.

The bug is present in several RHEL releases and it is documented here:

https://issues.redhat.com/browse/RHEL-73348

Following the advice in the issue, the API call has been temporarily replaced
with the equivalent CLI.
---
 .../python/pki/server/deployment/__init__.py  | 28 +++++++++++++++----
 1 file changed, 23 insertions(+), 5 deletions(-)

diff --git a/base/server/python/pki/server/deployment/__init__.py b/base/server/python/pki/server/deployment/__init__.py
index 0b64b8d74f5..baac6d3f0a4 100644
--- a/base/server/python/pki/server/deployment/__init__.py
+++ b/base/server/python/pki/server/deployment/__init__.py
@@ -5188,11 +5188,29 @@ def store_manifest(self):
         self.instance.copy(manifest_file, manifest_archive, force=True)
 
     def restore_selinux_contexts(self):
-
-        selinux.restorecon(self.instance.base_dir, True)
-        selinux.restorecon(config.PKI_DEPLOYMENT_LOG_ROOT, True)
-        selinux.restorecon(self.instance.actual_logs_dir, True)
-        selinux.restorecon(self.instance.actual_conf_dir, True)
+        # The restocon API is not working in RHEL
+        # (see https://issues.redhat.com/browse/RHEL-73348).
+        #
+        #selinux.restorecon(self.instance.base_dir, True)
+        #selinux.restorecon(config.PKI_DEPLOYMENT_LOG_ROOT, True)
+        #selinux.restorecon(self.instance.actual_logs_dir, True)
+        #selinux.restorecon(self.instance.actual_conf_dir, True)
+        folders = [
+            self.instance.base_dir,
+            config.PKI_DEPLOYMENT_LOG_ROOT,
+            self.instance.actual_logs_dir,
+            self.instance.actual_conf_dir
+        ]
+        for folder in folders:
+            cmd = [
+                '/usr/sbin/restorecon',
+                '-R'
+            ]
+            if logger.isEnabledFor(logging.DEBUG):
+                cmd.append('-v')
+            cmd.append(folder)
+            logger.debug('Command: %s', ' '.join(cmd))
+            subprocess.run(cmd, check=True)
 
     def selinux_context_exists(self, records, context_value):
         '''