Skip to contentSkip to conversation

libselinux: add Python binding for selinux_policy_open()

PATCH In review Stephen Smalley 1 participant 3 messages Sep 24 SELinux security module

lore
Share & tools
lore

Stephen Smalley

author maintainer
#0 lore raw

PATCH 1/2 libselinux: add Python binding for selinux_policy_open()

Regenerate selinuxswig_python_exception.i so the SWIG-wrapped selinux_policy_open() raises OSError from errno on failure instead of returning -1, and add a policy_open(path, mode="r") convenience helper to the %pythoncode block that calls selinux_policy_open(path, O_RDONLY|O_CLOEXEC) and returns an os.fdopen()'d file object. Python callers can then read policy configuration files with the same fallback-root search that C users of selinux_policy_open()/selinux_policy_fopen() get:

with selinux.policy_open(selinux.selinux_translations_path()) as f:
...

---
 libselinux/src/selinuxswig_python.i           | 9 +++++++++
 libselinux/src/selinuxswig_python_exception.i | 8 ++++++++
 2 files changed, 17 insertions(+)
libselinux/src/selinuxswig_python.i +9 -0
index 74d923e4..2340ed2d 100644
@@ -62,6 +62,15 @@ def install(src, dest):
     """ An SELinux-friendly shutil.move method """
     shutil.move(src, dest)
     restorecon(dest, recursive=True)
+
+def policy_open(path, mode="r", **kwargs):
+    """ Open a policy configuration file for reading, searching fallback configuration roots (see selinux_policy_open(3)). Returns a file object """
+    fd = selinux_policy_open(path, os.O_RDONLY | os.O_CLOEXEC)
+    try:
+        return os.fdopen(fd, mode, **kwargs)
+    except:  # noqa: E722
+        os.close(fd)
+        raise
 %}
 
 /* security_get_boolean_names() typemap */
libselinux/src/selinuxswig_python_exception.i +8 -0
index e5e55a79..6ab1bc6a 100644
@@ -743,6 +743,14 @@
   }
 }
 
+%exception selinux_policy_open {
+  $action
+  if (result < 0) {
+     PyErr_SetFromErrno(PyExc_OSError);
+     SWIG_fail;
+  }
+}
+
 %exception selinux_check_access {
   $action
   if (result < 0) {
Signature · 1 line
2.55.0
author maintainer
#1 lore raw

PATCH 2/2 python: read policy configuration files via selinux.policy_open()

Switch the direct open() reads of files under selinux_policy_root() in chcat, semanage, and sepolicy over to selinux.policy_open(), so that a distribution shipping policy configuration under a fallback root such as /usr/lib/selinux/<type> (with only local overrides in /etc/selinux/<type>) is handled the same way as by the C users of selinux_policy_open()/selinux_policy_fopen().

policy_open() raises the same OSError subclasses as open() on failure, so the existing except IOError/OSError handlers are unchanged. The file_contexts.subs write path in seobject.commit is left as-is; writes always go to the primary root.

/etc/selinux/sepolgen.conf and the /etc/selinux/ directory listing in gui/statusPage.py are top-level (not under the policy root) and so are not covered by selinux_policy_open(); they are left for a separate change.

---
 python/chcat/chcat                   |  2 +-
 python/semanage/seobject.py          |  4 ++--
 python/sepolicy/sepolicy/__init__.py | 12 ++++++------
 3 files changed, 9 insertions(+), 9 deletions(-)
python/chcat/chcat +1 -1
index c4f59229..5a9e94fb 100755
@@ -365,7 +365,7 @@ def usage():
 
 
 def listcats():
-    fd = open(selinux.selinux_translations_path())
+    fd = selinux.policy_open(selinux.selinux_translations_path())
     for l in fd.read().split("\n"):
         if l.startswith("#"):
             continue
python/semanage/seobject.py +2 -2
index b790597d..61a1a501 100644
@@ -2373,7 +2373,7 @@ class fcontextRecords(semanageRecords):
         self.equiv_dist = {}
         self.equal_ind = False
         try:
-            fd = open(selinux.selinux_file_context_subs_path(), "r")
+            fd = selinux.policy_open(selinux.selinux_file_context_subs_path())
             for i in fd.readlines():
                 i = i.strip()
                 if len(i) == 0:
@@ -2386,7 +2386,7 @@ class fcontextRecords(semanageRecords):
         except IOError:
             pass
         try:
-            fd = open(selinux.selinux_file_context_subs_dist_path(), "r")
+            fd = selinux.policy_open(selinux.selinux_file_context_subs_dist_path())
             for i in fd.readlines():
                 i = i.strip()
                 if len(i) == 0:
python/sepolicy/sepolicy/__init__.py +6 -6
index 3b87a869..bb241121 100644
@@ -589,7 +589,7 @@ def find_entrypoint_path(exe, exclude_list=[]):
 
 def read_file_equiv(edict, fc_path, modify):
     try:
-        with open(fc_path, "r") as fd:
+        with selinux.policy_open(fc_path) as fd:
             for e in fd:
                 f = e.split()
                 if f and not f[0].startswith('#'):
@@ -624,7 +624,7 @@ def get_local_file_paths(fc_path=selinux.selinux_file_context_path()):
         return local_files
     local_files = []
     try:
-        with open(fc_path + ".local", "r") as fd:
+        with selinux.policy_open(fc_path + ".local") as fd:
             fc = fd.readlines()
     except OSError as e:
         if e.errno != errno.ENOENT:
@@ -650,15 +650,15 @@ def get_fcdict(fc_path=selinux.selinux_file_context_path()):
     global fcdict
     if fcdict:
         return fcdict
-    fd = open(fc_path, "r")
+    fd = selinux.policy_open(fc_path)
     fc = fd.readlines()
     fd.close()
-    fd = open(fc_path + ".homedirs", "r")
+    fd = selinux.policy_open(fc_path + ".homedirs")
     fc += fd.readlines()
     fd.close()
     fcdict = {}
     try:
-        with open(fc_path + ".local", "r") as fd:
+        with selinux.policy_open(fc_path + ".local") as fd:
             fc += fd.readlines()
     except OSError as e:
         if e.errno != errno.ENOENT:
@@ -957,7 +957,7 @@ def get_login_mappings():
     if login_mappings:
         return login_mappings
 
-    fd = open(selinux.selinux_usersconf_path(), "r")
+    fd = selinux.policy_open(selinux.selinux_usersconf_path())
     buf = fd.read()
     fd.close()
     login_mappings = []
Signature · 1 line
2.55.0
author maintainer
#2 lore raw
In reply to Stephen Smalley
Quoted 9 lines · Stephen Smalley

Regenerate selinuxswig_python_exception.i so the SWIG-wrapped selinux_policy_open() raises OSError from errno on failure instead of returning -1, and add a policy_open(path, mode="r") convenience helper to the %pythoncode block that calls selinux_policy_open(path, O_RDONLY|O_CLOEXEC) and returns an os.fdopen()'d file object. Python callers can then read policy configuration files with the same fallback-root search that C users of selinux_policy_open()/selinux_policy_fopen() get:

Quoted 4 lines

with selinux.policy_open(selinux.selinux_translations_path()) as f:
...

This has been merged.