From 1bbe6489fde9c15805595cbb02a147714dbf67ff Mon Sep 17 00:00:00 2001 From: David Murphy < dmurphy@saltstack.com> Date: Wed, 8 Nov 2023 17:30:58 -0700 Subject: [PATCH] Ensure quoted filespec when using egrep to allow for regex with selinux --- changelog/65340.fixed.md | 1 + salt/modules/selinux.py | 2 +- tests/pytests/unit/modules/test_selinux.py | 35 ++++++++++++++++++++++ 3 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 changelog/65340.fixed.md diff --git a/changelog/65340.fixed.md b/changelog/65340.fixed.md new file mode 100644 index 00000000000..ed26da9f3cd --- /dev/null +++ b/changelog/65340.fixed.md @@ -0,0 +1 @@ +Fix regex for filespec adding/deleting fcontext policy in selinux diff --git a/salt/modules/selinux.py b/salt/modules/selinux.py index 7c09783da70..c12db3d9e19 100644 --- a/salt/modules/selinux.py +++ b/salt/modules/selinux.py @@ -617,7 +617,7 @@ def _fcontext_add_or_delete_policy( if "add" == action: # need to use --modify if context for name file exists, otherwise ValueError filespec = re.escape(name) - cmd = f"semanage fcontext -l | egrep {filespec}" + cmd = f"semanage fcontext -l | egrep '{filespec}'" current_entry_text = __salt__["cmd.shell"](cmd, ignore_retcode=True) if current_entry_text != "": action = "modify" diff --git a/tests/pytests/unit/modules/test_selinux.py b/tests/pytests/unit/modules/test_selinux.py index 05d3ca25e24..a48287b7648 100644 --- a/tests/pytests/unit/modules/test_selinux.py +++ b/tests/pytests/unit/modules/test_selinux.py @@ -1,3 +1,5 @@ +import re + import pytest import salt.modules.selinux as selinux @@ -376,3 +378,36 @@ SELINUXTYPE=targeted for line in writes: if line.startswith("SELINUX="): assert line == "SELINUX=disabled" + + +@pytest.mark.parametrize( + "name,sel_type", + ( + ("/srv/ssl/ldap/.*[.]key", "slapd_cert_t"), + ("/srv/ssl/ldap(/.*[.](pem|crt))?", "cert_t"), + ), +) +def test_selinux_add_policy_regex(name, sel_type): + """ + Test adding policy with regex components parsing the stdout response of restorecon used in fcontext_policy_applied, new style. + """ + mock_cmd_shell = MagicMock(return_value={"retcode": 0}) + mock_cmd_run_all = MagicMock(return_value={"retcode": 0}) + + with patch.dict(selinux.__salt__, {"cmd.shell": mock_cmd_shell}), patch.dict( + selinux.__salt__, {"cmd.run_all": mock_cmd_run_all} + ): + selinux.fcontext_add_policy(name, sel_type=sel_type) + filespec = re.escape(name) + filespec_test = f"'{filespec}'" + expected_cmd_shell = f"semanage fcontext -l | egrep {filespec_test}" + mock_cmd_shell.assert_called_once_with( + f"{expected_cmd_shell}", + ignore_retcode=True, + ) + expected_cmd_run_all = ( + f"semanage fcontext --modify --type {sel_type} {filespec}" + ) + mock_cmd_run_all.assert_called_once_with( + f"{expected_cmd_run_all}", + )