| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016, Dag Wieers (@dagwieers) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: sefcontext |
| 11 |
short_description: Manages SELinux file context mapping definitions |
| 12 |
description: |
| 13 |
- Manages SELinux file context mapping definitions. |
| 14 |
- Similar to the C(semanage fcontext) command. |
| 15 |
extends_documentation_fragment: |
| 16 |
- community.general._attributes |
| 17 |
- community.general._attributes.platform |
| 18 |
attributes: |
| 19 |
check_mode: |
| 20 |
support: full |
| 21 |
diff_mode: |
| 22 |
support: full |
| 23 |
platform: |
| 24 |
platforms: linux |
| 25 |
options: |
| 26 |
target: |
| 27 |
description: |
| 28 |
- Target path (expression). |
| 29 |
type: str |
| 30 |
required: true |
| 31 |
aliases: [path] |
| 32 |
ftype: |
| 33 |
description: |
| 34 |
- The file type that should have SELinux contexts applied. |
| 35 |
- 'The following file type options are available:' |
| 36 |
- V(a) for all files, |
| 37 |
- V(b) for block devices, |
| 38 |
- V(c) for character devices, |
| 39 |
- V(d) for directories, |
| 40 |
- V(f) for regular files, |
| 41 |
- V(l) for symbolic links, |
| 42 |
- V(p) for named pipes, |
| 43 |
- V(s) for socket files. |
| 44 |
type: str |
| 45 |
choices: [a, b, c, d, f, l, p, s] |
| 46 |
default: a |
| 47 |
setype: |
| 48 |
description: |
| 49 |
- SELinux type for the specified O(target). |
| 50 |
type: str |
| 51 |
substitute: |
| 52 |
description: |
| 53 |
- Path to use to substitute file context(s) for the specified O(target). The context labeling for the O(target) subtree |
| 54 |
is made equivalent to this path. |
| 55 |
- This is also referred to as SELinux file context equivalence and it implements the C(equal) functionality of the SELinux |
| 56 |
management tools. |
| 57 |
version_added: 6.4.0 |
| 58 |
type: str |
| 59 |
aliases: [equal] |
| 60 |
seuser: |
| 61 |
description: |
| 62 |
- SELinux user for the specified O(target). |
| 63 |
- Defaults to V(system_u) for new file contexts and to existing value when modifying file contexts. |
| 64 |
type: str |
| 65 |
selevel: |
| 66 |
description: |
| 67 |
- SELinux range for the specified O(target). |
| 68 |
- Defaults to V(s0) for new file contexts and to existing value when modifying file contexts. |
| 69 |
type: str |
| 70 |
aliases: [serange] |
| 71 |
state: |
| 72 |
description: |
| 73 |
- Whether the SELinux file context must be V(absent) or V(present). |
| 74 |
- Specifying V(absent) without either O(setype) or O(substitute) deletes both SELinux type or path substitution mappings |
| 75 |
that match O(target). |
| 76 |
type: str |
| 77 |
choices: [absent, present] |
| 78 |
default: present |
| 79 |
reload: |
| 80 |
description: |
| 81 |
- Reload SELinux policy after commit. |
| 82 |
- Note that this does not apply SELinux file contexts to existing files. |
| 83 |
type: bool |
| 84 |
default: true |
| 85 |
ignore_selinux_state: |
| 86 |
description: |
| 87 |
- Useful for scenarios (chrooted environment) that you cannot get the real SELinux state. |
| 88 |
type: bool |
| 89 |
default: false |
| 90 |
notes: |
| 91 |
- The changes are persistent across reboots. |
| 92 |
- O(setype) and O(substitute) are mutually exclusive. |
| 93 |
- If O(state=present) then one of O(setype) or O(substitute) is mandatory. |
| 94 |
- The M(community.general.sefcontext) module does not modify existing files to the new SELinux context(s), so it is advisable |
| 95 |
to first create the SELinux file contexts before creating files, or run C(restorecon) manually for the existing files |
| 96 |
that require the new SELinux file contexts. |
| 97 |
- Not applying SELinux fcontexts to existing files is a deliberate decision as it would be unclear what reported changes |
| 98 |
would entail to, and there is no guarantee that applying SELinux fcontext does not pick up other unrelated prior changes. |
| 99 |
requirements: |
| 100 |
- libselinux-python |
| 101 |
- policycoreutils-python |
| 102 |
author: |
| 103 |
- Dag Wieers (@dagwieers) |
| 104 |
""" |
| 105 |
|
| 106 |
EXAMPLES = r""" |
| 107 |
- name: Allow apache to modify files in /srv/git_repos |
| 108 |
community.general.sefcontext: |
| 109 |
target: '/srv/git_repos(/.*)?' |
| 110 |
setype: httpd_sys_rw_content_t |
| 111 |
state: present |
| 112 |
|
| 113 |
- name: Substitute file contexts for path /srv/containers with /var/lib/containers |
| 114 |
community.general.sefcontext: |
| 115 |
target: /srv/containers |
| 116 |
substitute: /var/lib/containers |
| 117 |
state: present |
| 118 |
|
| 119 |
- name: Delete file context path substitution for /srv/containers |
| 120 |
community.general.sefcontext: |
| 121 |
target: /srv/containers |
| 122 |
substitute: /var/lib/containers |
| 123 |
state: absent |
| 124 |
|
| 125 |
- name: Delete any file context mappings for path /srv/git |
| 126 |
community.general.sefcontext: |
| 127 |
target: /srv/git |
| 128 |
state: absent |
| 129 |
|
| 130 |
- name: Apply new SELinux file context to filesystem |
| 131 |
ansible.builtin.command: restorecon -irv /srv/git_repos |
| 132 |
""" |
| 133 |
|
| 134 |
RETURN = r""" |
| 135 |
# Default return values |
| 136 |
""" |
| 137 |
|
| 138 |
import traceback |
| 139 |
|
| 140 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 141 |
|
| 142 |
SELINUX_IMP_ERR = None |
| 143 |
try: |
| 144 |
import selinux |
| 145 |
|
| 146 |
HAVE_SELINUX = True |
| 147 |
except ImportError: |
| 148 |
SELINUX_IMP_ERR = traceback.format_exc() |
| 149 |
HAVE_SELINUX = False |
| 150 |
|
| 151 |
SEOBJECT_IMP_ERR = None |
| 152 |
try: |
| 153 |
import seobject |
| 154 |
|
| 155 |
HAVE_SEOBJECT = True |
| 156 |
except ImportError: |
| 157 |
SEOBJECT_IMP_ERR = traceback.format_exc() |
| 158 |
HAVE_SEOBJECT = False |
| 159 |
|
| 160 |
# Add missing entries (backward compatible) |
| 161 |
if HAVE_SEOBJECT: |
| 162 |
seobject.file_types.update( |
| 163 |
a=seobject.SEMANAGE_FCONTEXT_ALL, |
| 164 |
b=seobject.SEMANAGE_FCONTEXT_BLOCK, |
| 165 |
c=seobject.SEMANAGE_FCONTEXT_CHAR, |
| 166 |
d=seobject.SEMANAGE_FCONTEXT_DIR, |
| 167 |
f=seobject.SEMANAGE_FCONTEXT_REG, |
| 168 |
l=seobject.SEMANAGE_FCONTEXT_LINK, |
| 169 |
p=seobject.SEMANAGE_FCONTEXT_PIPE, |
| 170 |
s=seobject.SEMANAGE_FCONTEXT_SOCK, |
| 171 |
) |
| 172 |
|
| 173 |
# Make backward compatible |
| 174 |
option_to_file_type_str = dict( |
| 175 |
a="all files", |
| 176 |
b="block device", |
| 177 |
c="character device", |
| 178 |
d="directory", |
| 179 |
f="regular file", |
| 180 |
l="symbolic link", |
| 181 |
p="named pipe", |
| 182 |
s="socket", |
| 183 |
) |
| 184 |
|
| 185 |
|
| 186 |
def get_runtime_status(ignore_selinux_state=False): |
| 187 |
return True if ignore_selinux_state is True else selinux.is_selinux_enabled() |
| 188 |
|
| 189 |
|
| 190 |
def semanage_fcontext_exists(sefcontext, target, ftype): |
| 191 |
"""Get the SELinux file context mapping definition from policy. Return None if it does not exist.""" |
| 192 |
|
| 193 |
# Beware that records comprise of a string representation of the file_type |
| 194 |
record = (target, option_to_file_type_str[ftype]) |
| 195 |
records = sefcontext.get_all() |
| 196 |
try: |
| 197 |
return records[record] |
| 198 |
except KeyError: |
| 199 |
return None |
| 200 |
|
| 201 |
|
| 202 |
def semanage_fcontext_substitute_exists(sefcontext, target): |
| 203 |
"""Get the SELinux file context path substitution definition from policy. Return None if it does not exist.""" |
| 204 |
|
| 205 |
return sefcontext.equiv_dist.get(target, sefcontext.equiv.get(target)) |
| 206 |
|
| 207 |
|
| 208 |
def semanage_fcontext_modify(module, result, target, ftype, setype, substitute, do_reload, serange, seuser, sestore=""): |
| 209 |
"""Add or modify SELinux file context mapping definition to the policy.""" |
| 210 |
|
| 211 |
changed = False |
| 212 |
prepared_diff = "" |
| 213 |
|
| 214 |
try: |
| 215 |
sefcontext = seobject.fcontextRecords(sestore) |
| 216 |
sefcontext.set_reload(do_reload) |
| 217 |
if substitute is None: |
| 218 |
exists = semanage_fcontext_exists(sefcontext, target, ftype) |
| 219 |
if exists: |
| 220 |
# Modify existing entry |
| 221 |
orig_seuser, orig_serole, orig_setype, orig_serange = exists |
| 222 |
|
| 223 |
if seuser is None: |
| 224 |
seuser = orig_seuser |
| 225 |
if serange is None: |
| 226 |
serange = orig_serange |
| 227 |
|
| 228 |
if setype != orig_setype or seuser != orig_seuser or serange != orig_serange: |
| 229 |
if not module.check_mode: |
| 230 |
sefcontext.modify(target, setype, ftype, serange, seuser) |
| 231 |
changed = True |
| 232 |
|
| 233 |
if module._diff: |
| 234 |
prepared_diff += "# Change to semanage file context mappings\n" |
| 235 |
prepared_diff += ( |
| 236 |
f"-{target} {ftype} {orig_seuser}:{orig_serole}:{orig_setype}:{orig_serange}\n" |
| 237 |
) |
| 238 |
prepared_diff += f"+{target} {ftype} {seuser}:{orig_serole}:{setype}:{serange}\n" |
| 239 |
else: |
| 240 |
# Add missing entry |
| 241 |
if seuser is None: |
| 242 |
seuser = "system_u" |
| 243 |
if serange is None: |
| 244 |
serange = "s0" |
| 245 |
|
| 246 |
if not module.check_mode: |
| 247 |
sefcontext.add(target, setype, ftype, serange, seuser) |
| 248 |
changed = True |
| 249 |
|
| 250 |
if module._diff: |
| 251 |
prepared_diff += "# Addition to semanage file context mappings\n" |
| 252 |
prepared_diff += f"+{target} {ftype} {seuser}:object_r:{setype}:{serange}\n" |
| 253 |
else: |
| 254 |
exists = semanage_fcontext_substitute_exists(sefcontext, target) |
| 255 |
if exists: |
| 256 |
# Modify existing path substitution entry |
| 257 |
orig_substitute = exists |
| 258 |
|
| 259 |
if substitute != orig_substitute: |
| 260 |
if not module.check_mode: |
| 261 |
sefcontext.modify_equal(target, substitute) |
| 262 |
changed = True |
| 263 |
|
| 264 |
if module._diff: |
| 265 |
prepared_diff += "# Change to semanage file context path substitutions\n" |
| 266 |
prepared_diff += f"-{target} = {orig_substitute}\n" |
| 267 |
prepared_diff += f"+{target} = {substitute}\n" |
| 268 |
else: |
| 269 |
# Add missing path substitution entry |
| 270 |
if not module.check_mode: |
| 271 |
sefcontext.add_equal(target, substitute) |
| 272 |
changed = True |
| 273 |
if module._diff: |
| 274 |
prepared_diff += "# Addition to semanage file context path substitutions\n" |
| 275 |
prepared_diff += f"+{target} = {substitute}\n" |
| 276 |
|
| 277 |
except Exception as e: |
| 278 |
module.fail_json(msg=f"{e.__class__.__name__}: {e}\n") |
| 279 |
|
| 280 |
if module._diff and prepared_diff: |
| 281 |
result["diff"] = dict(prepared=prepared_diff) |
| 282 |
|
| 283 |
if changed and not module.check_mode: |
| 284 |
# Flush the in-process matchpathcon cache |
| 285 |
selinux.matchpathcon_fini() |
| 286 |
|
| 287 |
module.exit_json(changed=changed, seuser=seuser, serange=serange, **result) |
| 288 |
|
| 289 |
|
| 290 |
def semanage_fcontext_delete(module, result, target, ftype, setype, substitute, do_reload, sestore=""): |
| 291 |
"""Delete SELinux file context mapping definition from the policy.""" |
| 292 |
|
| 293 |
changed = False |
| 294 |
prepared_diff = "" |
| 295 |
|
| 296 |
try: |
| 297 |
sefcontext = seobject.fcontextRecords(sestore) |
| 298 |
sefcontext.set_reload(do_reload) |
| 299 |
exists = semanage_fcontext_exists(sefcontext, target, ftype) |
| 300 |
substitute_exists = semanage_fcontext_substitute_exists(sefcontext, target) |
| 301 |
if exists and substitute is None: |
| 302 |
# Remove existing entry |
| 303 |
orig_seuser, orig_serole, orig_setype, orig_serange = exists |
| 304 |
|
| 305 |
if not module.check_mode: |
| 306 |
sefcontext.delete(target, ftype) |
| 307 |
changed = True |
| 308 |
|
| 309 |
if module._diff: |
| 310 |
prepared_diff += "# Deletion to semanage file context mappings\n" |
| 311 |
prepared_diff += f"-{target} {ftype} {exists[0]}:{exists[1]}:{exists[2]}:{exists[3]}\n" |
| 312 |
if ( |
| 313 |
substitute_exists |
| 314 |
and setype is None |
| 315 |
and ((substitute is not None and substitute_exists == substitute) or substitute is None) |
| 316 |
): |
| 317 |
# Remove existing path substitution entry |
| 318 |
orig_substitute = substitute_exists |
| 319 |
|
| 320 |
if not module.check_mode: |
| 321 |
sefcontext.delete(target, orig_substitute) |
| 322 |
changed = True |
| 323 |
|
| 324 |
if module._diff: |
| 325 |
prepared_diff += "# Deletion to semanage file context path substitutions\n" |
| 326 |
prepared_diff += f"-{target} = {orig_substitute}\n" |
| 327 |
|
| 328 |
except Exception as e: |
| 329 |
module.fail_json(msg=f"{e.__class__.__name__}: {e}\n") |
| 330 |
|
| 331 |
if module._diff and prepared_diff: |
| 332 |
result["diff"] = dict(prepared=prepared_diff) |
| 333 |
|
| 334 |
if changed and not module.check_mode: |
| 335 |
# Flush the in-process matchpathcon cache |
| 336 |
selinux.matchpathcon_fini() |
| 337 |
|
| 338 |
module.exit_json(changed=changed, **result) |
| 339 |
|
| 340 |
|
| 341 |
def main(): |
| 342 |
module = AnsibleModule( |
| 343 |
argument_spec=dict( |
| 344 |
ignore_selinux_state=dict(type="bool", default=False), |
| 345 |
target=dict(type="str", required=True, aliases=["path"]), |
| 346 |
ftype=dict(type="str", default="a", choices=list(option_to_file_type_str.keys())), |
| 347 |
setype=dict(type="str"), |
| 348 |
substitute=dict(type="str", aliases=["equal"]), |
| 349 |
seuser=dict(type="str"), |
| 350 |
selevel=dict(type="str", aliases=["serange"]), |
| 351 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 352 |
reload=dict(type="bool", default=True), |
| 353 |
), |
| 354 |
mutually_exclusive=[ |
| 355 |
("setype", "substitute"), |
| 356 |
("substitute", "ftype"), |
| 357 |
("substitute", "seuser"), |
| 358 |
("substitute", "selevel"), |
| 359 |
], |
| 360 |
required_if=[ |
| 361 |
("state", "present", ("setype", "substitute"), True), |
| 362 |
], |
| 363 |
supports_check_mode=True, |
| 364 |
) |
| 365 |
if not HAVE_SELINUX: |
| 366 |
module.fail_json(msg=missing_required_lib("libselinux-python"), exception=SELINUX_IMP_ERR) |
| 367 |
|
| 368 |
if not HAVE_SEOBJECT: |
| 369 |
module.fail_json(msg=missing_required_lib("policycoreutils-python"), exception=SEOBJECT_IMP_ERR) |
| 370 |
|
| 371 |
ignore_selinux_state = module.params["ignore_selinux_state"] |
| 372 |
|
| 373 |
if not get_runtime_status(ignore_selinux_state): |
| 374 |
module.fail_json(msg="SELinux is disabled on this host.") |
| 375 |
|
| 376 |
target = module.params["target"] |
| 377 |
ftype = module.params["ftype"] |
| 378 |
setype = module.params["setype"] |
| 379 |
substitute = module.params["substitute"] |
| 380 |
seuser = module.params["seuser"] |
| 381 |
serange = module.params["selevel"] |
| 382 |
state = module.params["state"] |
| 383 |
do_reload = module.params["reload"] |
| 384 |
|
| 385 |
result = dict(target=target, ftype=ftype, setype=setype, substitute=substitute, state=state) |
| 386 |
|
| 387 |
if state == "present": |
| 388 |
semanage_fcontext_modify(module, result, target, ftype, setype, substitute, do_reload, serange, seuser) |
| 389 |
elif state == "absent": |
| 390 |
semanage_fcontext_delete(module, result, target, ftype, setype, substitute, do_reload) |
| 391 |
else: |
| 392 |
module.fail_json(msg=f'Invalid value of argument "state": {state}') |
| 393 |
|
| 394 |
|
| 395 |
if __name__ == "__main__": |
| 396 |
main() |