Debian Codegraph @

lib/ansible/module_utils/facts/system/selinux.py

raw
1 # Collect facts related to selinux
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 import typing as t
21
22 from ansible.module_utils.facts.collector import BaseFactCollector
23
24 try:
25 from ansible.module_utils.compat import selinux
26 HAVE_SELINUX = True
27 except ImportError:
28 HAVE_SELINUX = False
29
30 SELINUX_MODE_DICT = {
31 1: 'enforcing',
32 0: 'permissive',
33 -1: 'disabled'
34 }
35
36
37 class SelinuxFactCollector(BaseFactCollector):
38 name = 'selinux'
39 _fact_ids = set() # type: t.Set[str]
40
41 def collect(self, module=None, collected_facts=None):
42 facts_dict = {}
43 selinux_facts = {}
44
45 # If selinux library is missing, only set the status and selinux_python_present since
46 # there is no way to tell if SELinux is enabled or disabled on the system
47 # without the library.
48 if not HAVE_SELINUX:
49 selinux_facts['status'] = 'Missing selinux Python library'
50 facts_dict['selinux'] = selinux_facts
51 facts_dict['selinux_python_present'] = False
52 return facts_dict
53
54 # Set a boolean for testing whether the Python library is present
55 facts_dict['selinux_python_present'] = True
56
57 if not selinux.is_selinux_enabled():
58 selinux_facts['status'] = 'disabled'
59 else:
60 selinux_facts['status'] = 'enabled'
61
62 try:
63 selinux_facts['policyvers'] = selinux.security_policyvers()
64 except (AttributeError, OSError):
65 selinux_facts['policyvers'] = 'unknown'
66
67 try:
68 (rc, configmode) = selinux.selinux_getenforcemode()
69 if rc == 0:
70 selinux_facts['config_mode'] = SELINUX_MODE_DICT.get(configmode, 'unknown')
71 else:
72 selinux_facts['config_mode'] = 'unknown'
73 except (AttributeError, OSError):
74 selinux_facts['config_mode'] = 'unknown'
75
76 try:
77 mode = selinux.security_getenforce()
78 selinux_facts['mode'] = SELINUX_MODE_DICT.get(mode, 'unknown')
79 except (AttributeError, OSError):
80 selinux_facts['mode'] = 'unknown'
81
82 try:
83 (rc, policytype) = selinux.selinux_getpolicytype()
84 if rc == 0:
85 selinux_facts['type'] = policytype
86 else:
87 selinux_facts['type'] = 'unknown'
88 except (AttributeError, OSError):
89 selinux_facts['type'] = 'unknown'
90
91 facts_dict['selinux'] = selinux_facts
92 return facts_dict