Skip to content

Commit

Permalink
fs: Add restorecon to fs utility
Browse files Browse the repository at this point in the history
We need to handle selinx contexts properly to prevent AVCs.
  • Loading branch information
jakub-vavra-cz committed Sep 19, 2024
1 parent f935c8a commit d368988
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions pytest_mh/utils/fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ def mkdir(self, path: str, *, mode: str | None = None, user: str | None = None,
""",
log_level=ProcessLogLevel.Error,
)
self.restorecon(path)

def mkdir_p(
self, path: str, *, mode: str | None = None, user: str | None = None, group: str | None = None
Expand Down Expand Up @@ -113,6 +114,7 @@ def mkdir_p(
""",
log_level=ProcessLogLevel.Error,
)
self.restorecon(path)

if result.stdout and result.stdout != path:
if not backup_exists:
Expand Down Expand Up @@ -276,6 +278,7 @@ def write(
input=contents,
log_level=ProcessLogLevel.Error,
)
self.restorecon(path)

def append(
self,
Expand Down Expand Up @@ -342,6 +345,7 @@ def touch(
""",
log_level=ProcessLogLevel.Error,
)
self.restorecon(path)

def truncate(
self,
Expand Down Expand Up @@ -404,6 +408,7 @@ def copy(
""",
log_level=ProcessLogLevel.Error,
)
self.restorecon(dstpath)

def upload(
self,
Expand Down Expand Up @@ -447,6 +452,7 @@ def upload(
input=encoded,
log_level=ProcessLogLevel.Error,
)
self.restorecon(remote_path)

def upload_to_tmp(
self,
Expand Down Expand Up @@ -757,3 +763,23 @@ def sed(self, command: str, path: str, args: list[str] | None = None) -> Process
self.logger.info(f"Running sed {command} on {path}")
args = args if args else []
return self.host.conn.exec(["sed", *args, command, path], log_level=ProcessLogLevel.Error)

def restorecon(self, path: str) -> bool:
"""
Restore selinux context on a file or directory.
Does nothing when restorecon is not present on os without selinux.
:param path: File or directory where changes will happen
:type path: str
:return: True if restorecon succeeded
:rtype: bool
"""
if self.exists("/usr/sbin/restorecon"):
self.logger.info(f"Running restorecon -rvF on {path}")
result = self.host.conn.exec(
["restorecon", "-rvF", path], log_level=ProcessLogLevel.Error, raise_on_error=False
)
return result.rc == 0
else:
self.logger.info("Binary restorecon is missing.")
return False

0 comments on commit d368988

Please sign in to comment.