util: add selinux config file related helpers

Add a helper, `parse_config`, to parse a selinux configuration file,
see selinux(8), and return a dictionary containing the configuration
data in key, value pairs. This, in turn, can be fed into the other
helper method, `config_get_policy`, to get the effective policy or
`None` if SELinux is disabled or the policy type is not configured.
Add a new test suite that checks the basic functionality of the
helpers above.
This commit is contained in:
Christian Kellner 2020-04-08 17:18:56 +02:00 committed by David Rheinsberg
parent 47412e1bb7
commit 50beb4ffb5
2 changed files with 72 additions and 0 deletions

29
osbuild/util/selinux.py Normal file
View file

@ -0,0 +1,29 @@
"""SELinux utility functions"""
from typing import Dict, TextIO
def parse_config(config_file: TextIO):
"""Parse an SELinux configuration file"""
config = {}
for line in config_file:
line = line.strip()
if not line:
continue
if line.startswith('#'):
continue
k, v = line.split('=', 1)
config[k.strip()] = v.strip()
return config
def config_get_policy(config: Dict[str, str]):
"""Return the effective SELinux policy
Checks if SELinux is enabled and if so returns the
policy; otherwise `None` is returned.
"""
enabled = config.get('SELINUX', 'disabled')
if enabled not in ['enforcing', 'permissive']:
return None
return config.get('SELINUXTYPE', None)

43
test/test_util_selinux.py Normal file
View file

@ -0,0 +1,43 @@
import io
import unittest
import subprocess
from osbuild.util import selinux
class TestObjectStore(unittest.TestCase):
def test_selinux_config(self):
f = io.StringIO()
cfg = selinux.parse_config(f)
self.assertIsNotNone(cfg)
policy = selinux.config_get_policy(cfg)
self.assertIsNone(policy)
example_good = """
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=enforcing
# SELINUXTYPE= can take one of these three values:
# targeted - Targeted processes are protected,
# minimum - Modification of targeted policy.
# mls - Multi Level Security protection.
SELINUXTYPE=targeted
"""
f = io.StringIO(example_good)
cfg = selinux.parse_config(f)
self.assertIn('SELINUX', cfg)
self.assertIn('SELINUXTYPE', cfg)
self.assertEqual(cfg['SELINUX'], 'enforcing')
self.assertEqual(cfg['SELINUXTYPE'], 'targeted')
policy = selinux.config_get_policy(cfg)
self.assertEqual(policy, 'targeted')
if __name__ == "__main__":
unittest.main()