Skip to contentSkip to conversation

Fix semanage in envinronment without default policy or when -S <store> is used

PATCH Superseded Petr Lautrbach 2 participants 15 messages Dec 20, 2018 – Jan 5, 2019 SELinux security module

lore
Share & tools
lore
#0 lore raw

The following set of patches tries to fix semanage in non-standard environments.

A backtrace when semanage was run on a system without installed policy, see
https://github.com/SELinuxProject/selinux/issues/81
https://bugzilla.redhat.com/show_bug.cgi?id=1558861

The fix is based on
https://github.com/fishilico/selinux/commit/00eb0cc86185d2145ea3ec61df08c587faba1375
by Nicolas Iooss <[email protected]>

And when semanage was run -S <store>, sepolicy module was initialized with the default policy file (targeted) and also selinux module used the same default. It meant that semanage either backtraced when the default policy was not installed or used wrong store and therefore didn't behave correctly.

E.g. # semanage login -S minimum -d -s unconfined_u -r s0-s0:c0.c1023 __default__ libsemanage.dbase_llist_query: could not query record value
OSError: [Errno 0] Error

#1 lore raw

PATCH 1/4 python/semanage: move valid_types initialisations to class constructors

Based on idea from Nicolas Iooss <[email protected]>

Fixes:

$ sudo semanage
Traceback (most recent call last):
  File "/usr/sbin/semanage", line 28, in <module>
    import seobject
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1045, in <module>
    class portRecords(semanageRecords):
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1047, in portRecords
    valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
  File "/usr/lib/python3.7/site-packages/sepolicy/__init__.py", line 203, in <genexpr>
    return ({
  File "/usr/lib64/python3.7/site-packages/setools/typeattrquery.py", line 65, in results
    for attr in self.policy.typeattributes():
AttributeError: 'NoneType' object has no attribute 'typeattributes'

https://github.com/SELinuxProject/selinux/issues/81

---
 python/semanage/seobject.py | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)
python/semanage/seobject.py +20 -13
index efec0a55..2b43b65c 100644
@@ -1043,13 +1043,15 @@ class seluserRecords(semanageRecords):
 
 
 class portRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def __genkey(self, port, proto):
         if proto == "tcp":
@@ -1823,14 +1825,16 @@ class ibendportRecords(semanageRecords):
             print(rec)
 
 class nodeRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         self.protocol = ["ipv4", "ipv6"]
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def validate(self, addr, mask, protocol):
         newaddr = addr
@@ -2264,14 +2268,17 @@ class interfaceRecords(semanageRecords):
 
 
 class fcontextRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
-        valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
+            self.valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
+        except RuntimeError:
+            pass
+
         self.equiv = {}
         self.equiv_dist = {}
         self.equal_ind = False
Signature · 1 line
2.20.1
#2 lore raw

Re: [PATCH 1/4] python/semanage: move valid_types initialisations to class constructors

Quoted 18 lines · Petr Lautrbach

Based on idea from Nicolas Iooss <[email protected]>

Fixes:

$ sudo semanage
Traceback (most recent call last):
  File "/usr/sbin/semanage", line 28, in <module>
    import seobject
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1045, in <module>
    class portRecords(semanageRecords):
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1047, in portRecords
    valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
  File "/usr/lib/python3.7/site-packages/sepolicy/__init__.py", line 203, in <genexpr>
    return ({
  File "/usr/lib64/python3.7/site-packages/setools/typeattrquery.py", line 65, in results
    for attr in self.policy.typeattributes():
AttributeError: 'NoneType' object has no attribute 'typeattributes'
Quoted 3 lines

https://github.com/SELinuxProject/selinux/issues/81

Why are classes ibpkeyRecords and ibendportRecords not covered by the changes from this patch?

Nicolas

Quoted 75 lines
---
 python/semanage/seobject.py | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)
python/semanage/seobject.py +20 -14
index efec0a55..2b43b65c 100644
@@ -1043,13 +1043,15 @@ class seluserRecords(semanageRecords):
 
 
 class portRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def __genkey(self, port, proto):
         if proto == "tcp":
@@ -1823,14 +1825,16 @@ class ibendportRecords(semanageRecords):
             print(rec)
 
 class nodeRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         self.protocol = ["ipv4", "ipv6"]
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def validate(self, addr, mask, protocol):
         newaddr = addr
@@ -2264,14 +2268,17 @@ class interfaceRecords(semanageRecords):
 
 
 class fcontextRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
-        valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
+            self.valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
+        except RuntimeError:
+            pass
+
         self.equiv = {}
         self.equiv_dist = {}
         self.equal_ind = False
--

2.20.1

#3 lore raw

Re: [PATCH 1/4] python/semanage: move valid_types initialisations to class constructors

Quoted 19 lines · Nicolas Iooss
Quoted 18 lines · Petr Lautrbach

Based on idea from Nicolas Iooss <[email protected]>

Fixes:

$ sudo semanage
Traceback (most recent call last):
  File "/usr/sbin/semanage", line 28, in <module>
    import seobject
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1045, in <module>
    class portRecords(semanageRecords):
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1047, in portRecords
    valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
  File "/usr/lib/python3.7/site-packages/sepolicy/__init__.py", line 203, in <genexpr>
    return ({
  File "/usr/lib64/python3.7/site-packages/setools/typeattrquery.py", line 65, in results
    for attr in self.policy.typeattributes():
AttributeError: 'NoneType' object has no attribute 'typeattributes'
Quoted 6 lines
Quoted 3 lines

https://github.com/SELinuxProject/selinux/issues/81

Why are classes ibpkeyRecords and ibendportRecords not covered by the changes from this patch?

Because I missed that out. I'll send another set with ibendportRecords and ibpkeyRecords covered.

Thanks!

Quoted 78 lines

Nicolas

Quoted 75 lines
---
 python/semanage/seobject.py | 33 ++++++++++++++++++++-------------
 1 file changed, 20 insertions(+), 13 deletions(-)
python/semanage/seobject.py +20 -14
index efec0a55..2b43b65c 100644
@@ -1043,13 +1043,15 @@ class seluserRecords(semanageRecords):
 
 
 class portRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def __genkey(self, port, proto):
         if proto == "tcp":
@@ -1823,14 +1825,16 @@ class ibendportRecords(semanageRecords):
             print(rec)
 
 class nodeRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         self.protocol = ["ipv4", "ipv6"]
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def validate(self, addr, mask, protocol):
         newaddr = addr
@@ -2264,14 +2268,17 @@ class interfaceRecords(semanageRecords):
 
 
 class fcontextRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
-        valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
+            self.valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
+        except RuntimeError:
+            pass
+
         self.equiv = {}
         self.equiv_dist = {}
         self.equal_ind = False
--

2.20.1

#4 lore raw

PATCH 2/4 python/semanage: import sepolicy only when it's needed

In reply to Petr Lautrbach

Related:
https://github.com/SELinuxProject/selinux/issues/81

---
 python/semanage/semanage | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
python/semanage/semanage +6 -2
index a192fac8..1cb13683 100644
@@ -73,7 +73,7 @@ usage_interface_dict = {' --add': ('-t TYPE', '-r RANGE', 'interface'), ' --modi
 usage_boolean = "semanage boolean [-h] [-n] [-N] [-S STORE] ["
 usage_boolean_dict = {' --modify': ('(', '--on', '|', '--off', ')', 'boolean'), ' --list': ('-C',), '  --extract': ('',), ' --deleteall': ('',)}
 
-import sepolicy
+
 
 
 class CheckRole(argparse.Action):
@@ -82,7 +82,11 @@ class CheckRole(argparse.Action):
         newval = getattr(namespace, self.dest)
         if not newval:
             newval = []
-        roles = sepolicy.get_all_roles()
+        try:
+            import sepolicy
+            roles = sepolicy.get_all_roles()
+        except ValueError:
+            roles = []
         for v in value.split():
             if v not in roles:
                 raise ValueError("%s must be an SELinux role:\nValid roles: %s" % (v, ", ".join(roles)))
Signature · 1 line
2.20.1
#5 lore raw

PATCH 3/4 python/sepolicy: Add sepolicy.load_store_policy(store)

In reply to Petr Lautrbach

load_store_policy() allows to (re)load SELinux policy based on a store name. It is useful when SELinux is disabled and default policy is not installed; or when a user wants to query or manipulate another policy.

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/sepolicy/sepolicy/__init__.py | 12 ++++++++++++
 1 file changed, 12 insertions(+)
python/sepolicy/sepolicy/__init__.py +12 -0
index fbeb731d..b69a6b94 100644
@@ -129,6 +129,13 @@ def get_installed_policy(root="/"):
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
+def get_store_policy(store, root="/"):
+    try:
+        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
+        policies.sort()
+        return policies[-1]
+    except:
+        return None
 
 def policy(policy_file):
     global all_domains
@@ -156,6 +163,11 @@ def policy(policy_file):
     except:
         raise ValueError(_("Failed to read %s policy file") % policy_file)
 
+def load_store_policy(store):
+    policy_file = get_store_policy(store)
+    if not policy_file:
+        return None
+    policy(policy_file)
 
 try:
     policy_file = get_installed_policy()
Signature · 1 line
2.20.1
#6 lore raw

Re: [PATCH 3/4] python/sepolicy: Add sepolicy.load_store_policy(store)

Quoted 17 lines · Petr Lautrbach

load_store_policy() allows to (re)load SELinux policy based on a store name. It is useful when SELinux is disabled and default policy is not installed; or when a user wants to query or manipulate another policy.

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/sepolicy/sepolicy/__init__.py | 12 ++++++++++++
 1 file changed, 12 insertions(+)
python/sepolicy/sepolicy/__init__.py +0 -0
index fbeb731d..b69a6b94 100644

python/sepolicy/sepolicy/__init__.py def get_installed_policy(root="/"): · line 138

Quoted 10 lines
python/sepolicy/sepolicy/__init__.py +7 -0
@@ -129,6 +129,13 @@ def get_installed_policy(root="/"):
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
+def get_store_policy(store, root="/"):
+    try:
+        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
+        policies.sort()
+        return policies[-1]
+    except:
+        return None

Hi, I agree this function is useful. Nevertheless the sorting order seems to be fragile because '100' < '99', so the policy filename needs to be parsed in order to extract the version as an integer and sort according to it. Moreover its second parameter ("root") is not used and I would rather avoid adding new bare excepts to the code base.

I suggest the following implementation of this function:

def get_store_policy(store):
"""Get the path to the policy file located in the given store name""" def policy_sortkey(policy_path):
# Parse the extension of a policy path which looks like
.../policy/policy.31
extension = policy_path.rsplit('/policy.', 1)[1]
try:
return int(extension), policy_path
except ValueError:
# Fallback with sorting on the full path
return 0, policy_path
policies = glob.glob("%s%s/policy/policy.*" %
(selinux.selinux_path(), store))
if not policies:
return None
# Return the policy with the higher version number policies.sort(key=policy_sortkey)
return policies[-1] if policies else None

It is more complex but fixes the issues I have identified. If you want to keep "root", it may be possible to use it with both "glob.glob("%s/%s/%s/policy/policy.*" % (root, selinux.selinux_path(), store))" and "return os.path.realpath(policies[-1]) if policies else None" (in order to simplify double-slashes into a single "/" character). What do you think of this?

Anyway, thanks for the patches!
Nicolas

#7 lore raw

Re: [PATCH 3/4] python/sepolicy: Add sepolicy.load_store_policy(store)

Quoted 56 lines · Nicolas Iooss
Quoted 17 lines · Petr Lautrbach

load_store_policy() allows to (re)load SELinux policy based on a store name. It is useful when SELinux is disabled and default policy is not installed; or when a user wants to query or manipulate another policy.

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/sepolicy/sepolicy/__init__.py | 12 ++++++++++++
 1 file changed, 12 insertions(+)
python/sepolicy/sepolicy/__init__.py +0 -0
index fbeb731d..b69a6b94 100644

python/sepolicy/sepolicy/__init__.py def get_installed_policy(root="/"): · line 138

Quoted 10 lines
python/sepolicy/sepolicy/__init__.py +7 -0
@@ -129,6 +129,13 @@ def get_installed_policy(root="/"):
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
+def get_store_policy(store, root="/"):
+    try:
+        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
+        policies.sort()
+        return policies[-1]
+    except:
+        return None

Hi, I agree this function is useful. Nevertheless the sorting order seems to be fragile because '100' < '99', so the policy filename needs to be parsed in order to extract the version as an integer and sort according to it. Moreover its second parameter ("root") is not used and I would rather avoid adding new bare excepts to the code base.

I suggest the following implementation of this function:

def get_store_policy(store):
"""Get the path to the policy file located in the given store name""" def policy_sortkey(policy_path):
# Parse the extension of a policy path which looks like
.../policy/policy.31
extension = policy_path.rsplit('/policy.', 1)[1]
try:
return int(extension), policy_path
except ValueError:
# Fallback with sorting on the full path
return 0, policy_path
policies = glob.glob("%s%s/policy/policy.*" %
(selinux.selinux_path(), store))
if not policies:
return None
# Return the policy with the higher version number policies.sort(key=policy_sortkey)
return policies[-1] if policies else None

Quoted 7 lines

It is more complex but fixes the issues I have identified. If you want to keep "root", it may be possible to use it with both "glob.glob("%s/%s/%s/policy/policy.*" % (root, selinux.selinux_path(), store))" and "return os.path.realpath(policies[-1]) if policies else None" (in order to simplify double-slashes into a single "/" character). What do you think of this?

It looks good to me. I'll only move policy_sortkey out of this function and use it in also get_installed_policy() as this function use the original sort method.

Petr

#8 lore raw

PATCH 4/4 python/semanage: Load a store policy and set the store SELinux policy root

In reply to Petr Lautrbach

When "store" is set, sepolicy needs to load a new policy file and selinux module needs to set the new store root path.

With this patch, semanage is able to work correctly with non-default -S <store> even when the default policy is not installed yet.

Fixes:

$ sudo semanage login -S minimum -m -s unconfined_u -r s0-s0:c0.c1023 __default__
libsemanage.dbase_llist_query: could not query record value
OSError: [Errno 0] Error

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/semanage/seobject.py | 2 ++
 1 file changed, 2 insertions(+)
python/semanage/seobject.py +2 -0
index 2b43b65c..7b9c68b1 100644
@@ -260,6 +260,8 @@ class semanageRecords:
         if self.store == "" or self.store == localstore:
             self.mylog = logger()
         else:
+            sepolicy.load_store_policy(self.store)
+            selinux.selinux_set_policy_root("%s%s" % (selinux.selinux_path(), self.store))
             self.mylog = nulllogger()
 
     def set_reload(self, load):
Signature · 1 line
2.20.1
#9 lore raw

PATCH v2 1/5 python/semanage: move valid_types initialisations to class constructors

In reply to Petr Lautrbach

Based on idea from Nicolas Iooss <[email protected]>

Fixes:

$ sudo semanage
Traceback (most recent call last):
  File "/usr/sbin/semanage", line 28, in <module>
    import seobject
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1045, in <module>
    class portRecords(semanageRecords):
  File "/usr/lib/python3.7/site-packages/seobject.py", line 1047, in portRecords
    valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
  File "/usr/lib/python3.7/site-packages/sepolicy/__init__.py", line 203, in <genexpr>
    return ({
  File "/usr/lib64/python3.7/site-packages/setools/typeattrquery.py", line 65, in results
    for attr in self.policy.typeattributes():
AttributeError: 'NoneType' object has no attribute 'typeattributes'

https://github.com/SELinuxProject/selinux/issues/81

---
 python/semanage/seobject.py | 57 ++++++++++++++++++++++---------------
 1 file changed, 34 insertions(+), 23 deletions(-)
python/semanage/seobject.py +34 -23
index efec0a55..4490e03f 100644
@@ -1043,13 +1043,15 @@ class seluserRecords(semanageRecords):
 
 
 class portRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "port_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def __genkey(self, port, proto):
         if proto == "tcp":
@@ -1321,14 +1323,16 @@ class portRecords(semanageRecords):
             print(rec)
 
 class ibpkeyRecords(semanageRecords):
-    try:
-        q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibpkey_type"])
-        valid_types = sorted(str(t) for t in q.results())
-    except:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibpkey_type"])
+            self.valid_types = sorted(str(t) for t in q.results())
+        except:
+            pass
 
     def __genkey(self, pkey, subnet_prefix):
         if subnet_prefix == "":
@@ -1579,14 +1583,16 @@ class ibpkeyRecords(semanageRecords):
             print(rec)
 
 class ibendportRecords(semanageRecords):
-    try:
-        q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibendport_type"])
-        valid_types = set(str(t) for t in q.results())
-    except:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibendport_type"])
+            self.valid_types = set(str(t) for t in q.results())
+        except:
+            pass
 
     def __genkey(self, ibendport, ibdev_name):
         if ibdev_name == "":
@@ -1823,14 +1829,16 @@ class ibendportRecords(semanageRecords):
             print(rec)
 
 class nodeRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         self.protocol = ["ipv4", "ipv6"]
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "node_type"))[0]["types"])
+        except RuntimeError:
+            pass
 
     def validate(self, addr, mask, protocol):
         newaddr = addr
@@ -2264,14 +2272,17 @@ class interfaceRecords(semanageRecords):
 
 
 class fcontextRecords(semanageRecords):
-    try:
-        valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
-        valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
-    except RuntimeError:
-        valid_types = []
+
+    valid_types = []
 
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
+        try:
+            self.valid_types = list(list(sepolicy.info(sepolicy.ATTRIBUTE, "file_type"))[0]["types"])
+            self.valid_types += list(list(sepolicy.info(sepolicy.ATTRIBUTE, "device_node"))[0]["types"])
+        except RuntimeError:
+            pass
+
         self.equiv = {}
         self.equiv_dist = {}
         self.equal_ind = False
Signature · 1 line
2.20.1
#10 lore raw

PATCH v2 2/5 python/semanage: import sepolicy only when it's needed

Related:
https://github.com/SELinuxProject/selinux/issues/81

---
 python/semanage/semanage | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
python/semanage/semanage +6 -2
index a192fac8..1cb13683 100644
@@ -73,7 +73,7 @@ usage_interface_dict = {' --add': ('-t TYPE', '-r RANGE', 'interface'), ' --modi
 usage_boolean = "semanage boolean [-h] [-n] [-N] [-S STORE] ["
 usage_boolean_dict = {' --modify': ('(', '--on', '|', '--off', ')', 'boolean'), ' --list': ('-C',), '  --extract': ('',), ' --deleteall': ('',)}
 
-import sepolicy
+
 
 
 class CheckRole(argparse.Action):
@@ -82,7 +82,11 @@ class CheckRole(argparse.Action):
         newval = getattr(namespace, self.dest)
         if not newval:
             newval = []
-        roles = sepolicy.get_all_roles()
+        try:
+            import sepolicy
+            roles = sepolicy.get_all_roles()
+        except ValueError:
+            roles = []
         for v in value.split():
             if v not in roles:
                 raise ValueError("%s must be an SELinux role:\nValid roles: %s" % (v, ", ".join(roles)))
Signature · 1 line
2.20.1
#11 lore raw

PATCH v2 3/5 python/sepolicy: Add sepolicy.load_store_policy(store)

In reply to Petr Lautrbach

load_store_policy() allows to (re)load SELinux policy based on a store name. It is useful when SELinux is disabled and default policy is not installed; or when a user wants to query or manipulate another policy.

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/sepolicy/sepolicy/__init__.py | 12 ++++++++++++
 1 file changed, 12 insertions(+)
python/sepolicy/sepolicy/__init__.py +12 -0
index fbeb731d..b69a6b94 100644
@@ -129,6 +129,13 @@ def get_installed_policy(root="/"):
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
+def get_store_policy(store, root="/"):
+    try:
+        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
+        policies.sort()
+        return policies[-1]
+    except:
+        return None
 
 def policy(policy_file):
     global all_domains
@@ -156,6 +163,11 @@ def policy(policy_file):
     except:
         raise ValueError(_("Failed to read %s policy file") % policy_file)
 
+def load_store_policy(store):
+    policy_file = get_store_policy(store)
+    if not policy_file:
+        return None
+    policy(policy_file)
 
 try:
     policy_file = get_installed_policy()
Signature · 1 line
2.20.1
#12 lore raw

PATCH v2 4/5 python/semanage: Load a store policy and set the store SELinux policy root

In reply to Petr Lautrbach

When "store" is set, sepolicy needs to load a new policy file and selinux module needs to set the new store root path.

With this patch, semanage is able to work correctly with non-default -S <store> even when the default policy is not installed yet.

Fixes:

$ sudo semanage login -S minimum -m -s unconfined_u -r s0-s0:c0.c1023 __default__
libsemanage.dbase_llist_query: could not query record value
OSError: [Errno 0] Error

Related: https://bugzilla.redhat.com/show_bug.cgi?id=1558861

---
 python/semanage/seobject.py | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
python/semanage/seobject.py +4 -2
index 4490e03f..556d3ba5 100644
@@ -260,6 +260,8 @@ class semanageRecords:
         if self.store == "" or self.store == localstore:
             self.mylog = logger()
         else:
+            sepolicy.load_store_policy(self.store)
+            selinux.selinux_set_policy_root("%s%s" % (selinux.selinux_path(), self.store))
             self.mylog = nulllogger()
 
     def set_reload(self, load):
@@ -1329,7 +1331,7 @@ class ibpkeyRecords(semanageRecords):
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         try:
-            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibpkey_type"])
+            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_store_policy(self.store)), attrs=["ibpkey_type"])
             self.valid_types = sorted(str(t) for t in q.results())
         except:
             pass
@@ -1589,7 +1591,7 @@ class ibendportRecords(semanageRecords):
     def __init__(self, args = None):
         semanageRecords.__init__(self, args)
         try:
-            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_installed_policy()), attrs=["ibendport_type"])
+            q = setools.TypeQuery(setools.SELinuxPolicy(sepolicy.get_store_policy(self.store)), attrs=["ibendport_type"])
             self.valid_types = set(str(t) for t in q.results())
         except:
             pass
Signature · 1 line
2.20.1
#13 lore raw

PATCH v2 5/5 python/sepolicy: Make policy files sorting more robust

In reply to Petr Lautrbach

The sorting order seems to be fragile because '100' < '99', so the policy filename needs to be parsed in order to extract the version as an integer and sort according to it.

Based on idea from Nicolas Iooss <[email protected]>

---
 python/sepolicy/sepolicy/__init__.py | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)
python/sepolicy/sepolicy/__init__.py +18 -7
index b69a6b94..6f729472 100644
@@ -119,23 +119,34 @@ all_allow_rules = None
 all_transitions = None
 
 
+def policy_sortkey(policy_path):
+    # Parse the extension of a policy path which looks like .../policy/policy.31
+    extension = policy_path.rsplit('/policy.', 1)[1]
+    try:
+        return int(extension), policy_path
+    except ValueError:
+        # Fallback with sorting on the full path
+        return 0, policy_path
+
 def get_installed_policy(root="/"):
     try:
         path = root + selinux.selinux_binary_policy_path()
         policies = glob.glob("%s.*" % path)
-        policies.sort()
+        policies.sort(key=policy_sortkey)
         return policies[-1]
     except:
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
-def get_store_policy(store, root="/"):
-    try:
-        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
-        policies.sort()
-        return policies[-1]
-    except:
+def get_store_policy(store):
+    """Get the path to the policy file located in the given store name"""
+    policies = glob.glob("%s%s/policy/policy.*" %
+                         (selinux.selinux_path(), store))
+    if not policies:
         return None
+    # Return the policy with the higher version number
+    policies.sort(key=policy_sortkey)
+    return policies[-1]
 
 def policy(policy_file):
     global all_domains
Signature · 1 line
2.20.1
#14 lore raw

Re: [PATCH v2 5/5] python/sepolicy: Make policy files sorting more robust

Quoted 8 lines · Petr Lautrbach

The sorting order seems to be fragile because '100' < '99', so the policy filename needs to be parsed in order to extract the version as an integer and sort according to it.

Based on idea from Nicolas Iooss <[email protected]>

Thanks, merged all 5 commits.
Nicolas

Quoted 53 lines
---
 python/sepolicy/sepolicy/__init__.py | 25 ++++++++++++++++++-------
 1 file changed, 18 insertions(+), 7 deletions(-)
python/sepolicy/sepolicy/__init__.py +18 -8
index b69a6b94..6f729472 100644
@@ -119,23 +119,34 @@ all_allow_rules = None
 all_transitions = None
 
 
+def policy_sortkey(policy_path):
+    # Parse the extension of a policy path which looks like .../policy/policy.31
+    extension = policy_path.rsplit('/policy.', 1)[1]
+    try:
+        return int(extension), policy_path
+    except ValueError:
+        # Fallback with sorting on the full path
+        return 0, policy_path
+
 def get_installed_policy(root="/"):
     try:
         path = root + selinux.selinux_binary_policy_path()
         policies = glob.glob("%s.*" % path)
-        policies.sort()
+        policies.sort(key=policy_sortkey)
         return policies[-1]
     except:
         pass
     raise ValueError(_("No SELinux Policy installed"))
 
-def get_store_policy(store, root="/"):
-    try:
-        policies = glob.glob("%s%s/policy/policy.*" % (selinux.selinux_path(), store))
-        policies.sort()
-        return policies[-1]
-    except:
+def get_store_policy(store):
+    """Get the path to the policy file located in the given store name"""
+    policies = glob.glob("%s%s/policy/policy.*" %
+                         (selinux.selinux_path(), store))
+    if not policies:
         return None
+    # Return the policy with the higher version number
+    policies.sort(key=policy_sortkey)
+    return policies[-1]
 
 def policy(policy_file):
     global all_domains
--

2.20.1