Ensure quoted filespec when using egrep to allow for regex with selinux

This commit is contained in:
David Murphy 2023-11-08 17:30:58 -07:00 committed by Pedro Algarvio
parent c9c0ad0b46
commit 1bbe6489fd
3 changed files with 37 additions and 1 deletions

1
changelog/65340.fixed.md Normal file
View file

@ -0,0 +1 @@
Fix regex for filespec adding/deleting fcontext policy in selinux

View file

@ -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"

View file

@ -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}",
)