| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2014, Dan Keder <[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: seport |
| 11 |
short_description: Manages SELinux network port type definitions |
| 12 |
description: |
| 13 |
- Manages SELinux network port type definitions. |
| 14 |
extends_documentation_fragment: |
| 15 |
- community.general._attributes |
| 16 |
attributes: |
| 17 |
check_mode: |
| 18 |
support: full |
| 19 |
diff_mode: |
| 20 |
support: none |
| 21 |
options: |
| 22 |
ports: |
| 23 |
description: |
| 24 |
- Ports or port ranges. |
| 25 |
- Can be a list (since 2.6) or comma separated string. |
| 26 |
type: list |
| 27 |
elements: str |
| 28 |
required: true |
| 29 |
proto: |
| 30 |
description: |
| 31 |
- Protocol for the specified port. |
| 32 |
- Support for V(dccp) and V(sctp) has been added in community.general 12.4.0. |
| 33 |
type: str |
| 34 |
required: true |
| 35 |
choices: [tcp, udp, dccp, sctp] |
| 36 |
setype: |
| 37 |
description: |
| 38 |
- SELinux type for the specified port. |
| 39 |
type: str |
| 40 |
required: true |
| 41 |
state: |
| 42 |
description: |
| 43 |
- Desired boolean value. |
| 44 |
type: str |
| 45 |
choices: [absent, present] |
| 46 |
default: present |
| 47 |
reload: |
| 48 |
description: |
| 49 |
- Reload SELinux policy after commit. |
| 50 |
type: bool |
| 51 |
default: true |
| 52 |
ignore_selinux_state: |
| 53 |
description: |
| 54 |
- Run independent of selinux runtime state. |
| 55 |
type: bool |
| 56 |
default: false |
| 57 |
local: |
| 58 |
description: |
| 59 |
- Work with local modifications only. |
| 60 |
type: bool |
| 61 |
default: false |
| 62 |
version_added: 5.6.0 |
| 63 |
notes: |
| 64 |
- The changes are persistent across reboots. |
| 65 |
- Not tested on any Debian based system. |
| 66 |
requirements: |
| 67 |
- libselinux-python |
| 68 |
- policycoreutils-python |
| 69 |
author: |
| 70 |
- Dan Keder (@dankeder) |
| 71 |
""" |
| 72 |
|
| 73 |
EXAMPLES = r""" |
| 74 |
- name: Allow Apache to listen on tcp port 8888 |
| 75 |
community.general.seport: |
| 76 |
ports: 8888 |
| 77 |
proto: tcp |
| 78 |
setype: http_port_t |
| 79 |
state: present |
| 80 |
|
| 81 |
- name: Allow sshd to listen on tcp port 8991 |
| 82 |
community.general.seport: |
| 83 |
ports: 8991 |
| 84 |
proto: tcp |
| 85 |
setype: ssh_port_t |
| 86 |
state: present |
| 87 |
|
| 88 |
- name: Allow memcached to listen on tcp ports 10000-10100 and 10112 |
| 89 |
community.general.seport: |
| 90 |
ports: 10000-10100,10112 |
| 91 |
proto: tcp |
| 92 |
setype: memcache_port_t |
| 93 |
state: present |
| 94 |
|
| 95 |
- name: Allow memcached to listen on tcp ports 10000-10100 and 10112 |
| 96 |
community.general.seport: |
| 97 |
ports: |
| 98 |
- 10000-10100 |
| 99 |
- 10112 |
| 100 |
proto: tcp |
| 101 |
setype: memcache_port_t |
| 102 |
state: present |
| 103 |
|
| 104 |
- name: Remove tcp port 22 local modification if exists |
| 105 |
community.general.seport: |
| 106 |
ports: 22 |
| 107 |
protocol: tcp |
| 108 |
setype: ssh_port_t |
| 109 |
state: absent |
| 110 |
local: true |
| 111 |
""" |
| 112 |
|
| 113 |
import traceback |
| 114 |
|
| 115 |
SELINUX_IMP_ERR = None |
| 116 |
try: |
| 117 |
import selinux |
| 118 |
|
| 119 |
HAVE_SELINUX = True |
| 120 |
except ImportError: |
| 121 |
SELINUX_IMP_ERR = traceback.format_exc() |
| 122 |
HAVE_SELINUX = False |
| 123 |
|
| 124 |
SEOBJECT_IMP_ERR = None |
| 125 |
try: |
| 126 |
import seobject |
| 127 |
|
| 128 |
HAVE_SEOBJECT = True |
| 129 |
except ImportError: |
| 130 |
SEOBJECT_IMP_ERR = traceback.format_exc() |
| 131 |
HAVE_SEOBJECT = False |
| 132 |
|
| 133 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 134 |
|
| 135 |
|
| 136 |
def get_runtime_status(ignore_selinux_state=False): |
| 137 |
return ignore_selinux_state or selinux.is_selinux_enabled() |
| 138 |
|
| 139 |
|
| 140 |
def semanage_port_get_ports(seport, setype, proto, local): |
| 141 |
"""Get the list of ports that have the specified type definition. |
| 142 |
|
| 143 |
:param community.general.seport: Instance of seobject.portRecords |
| 144 |
|
| 145 |
:type setype: str |
| 146 |
:param setype: SELinux type. |
| 147 |
|
| 148 |
:type proto: str |
| 149 |
:param proto: Protocol ('tcp', 'udp', 'dccp', 'sctp') |
| 150 |
|
| 151 |
:rtype: list |
| 152 |
:return: List of ports that have the specified SELinux type. |
| 153 |
""" |
| 154 |
records = seport.get_all_by_type(locallist=local) |
| 155 |
if (setype, proto) in records: |
| 156 |
return records[(setype, proto)] |
| 157 |
else: |
| 158 |
return [] |
| 159 |
|
| 160 |
|
| 161 |
def _parse_port_range(port): |
| 162 |
"""Return (low, high) integers for a port or port range string.""" |
| 163 |
parts = str(port).split("-", 1) |
| 164 |
low = int(parts[0]) |
| 165 |
high = int(parts[1]) if len(parts) == 2 else low |
| 166 |
return low, high |
| 167 |
|
| 168 |
|
| 169 |
def _port_is_covered(port, existing_ports): |
| 170 |
"""Return True if port (or range) is fully covered by an existing port entry.""" |
| 171 |
req_low, req_high = _parse_port_range(port) |
| 172 |
for entry in existing_ports: |
| 173 |
entry_low, entry_high = _parse_port_range(entry) |
| 174 |
if entry_low <= req_low and req_high <= entry_high: |
| 175 |
return True |
| 176 |
return False |
| 177 |
|
| 178 |
|
| 179 |
def semanage_port_get_type(seport, port, proto): |
| 180 |
"""Get the SELinux type of the specified port. |
| 181 |
|
| 182 |
:param community.general.seport: Instance of seobject.portRecords |
| 183 |
|
| 184 |
:type port: str |
| 185 |
:param port: Port or port range (example: "8080", "8080-9090") |
| 186 |
|
| 187 |
:type proto: str |
| 188 |
:param proto: Protocol ('tcp', 'udp', 'dccp', 'sctp') |
| 189 |
|
| 190 |
:rtype: tuple |
| 191 |
:return: Tuple containing the SELinux type and MLS/MCS level, or None if not found. |
| 192 |
""" |
| 193 |
if isinstance(port, str): |
| 194 |
ports = port.split("-", 1) |
| 195 |
if len(ports) == 1: |
| 196 |
ports.extend(ports) |
| 197 |
else: |
| 198 |
ports = (port, port) |
| 199 |
|
| 200 |
key = (int(ports[0]), int(ports[1]), proto) |
| 201 |
|
| 202 |
records = seport.get_all() |
| 203 |
return records.get(key) |
| 204 |
|
| 205 |
|
| 206 |
def semanage_port_add(module, ports, proto, setype, do_reload, serange="s0", sestore="", local=False): |
| 207 |
"""Add SELinux port type definition to the policy. |
| 208 |
|
| 209 |
:type module: AnsibleModule |
| 210 |
:param module: Ansible module |
| 211 |
|
| 212 |
:type ports: list |
| 213 |
:param ports: List of ports and port ranges to add (e.g. ["8080", "8080-9090"]) |
| 214 |
|
| 215 |
:type proto: str |
| 216 |
:param proto: Protocol ('tcp', 'udp', 'dccp', 'sctp') |
| 217 |
|
| 218 |
:type setype: str |
| 219 |
:param setype: SELinux type |
| 220 |
|
| 221 |
:type do_reload: bool |
| 222 |
:param do_reload: Whether to reload SELinux policy after commit |
| 223 |
|
| 224 |
:type serange: str |
| 225 |
:param serange: SELinux MLS/MCS range (defaults to 's0') |
| 226 |
|
| 227 |
:type sestore: str |
| 228 |
:param sestore: SELinux store |
| 229 |
|
| 230 |
:rtype: bool |
| 231 |
:return: True if the policy was changed, otherwise False |
| 232 |
""" |
| 233 |
change = False |
| 234 |
try: |
| 235 |
seport = seobject.portRecords(sestore) |
| 236 |
seport.set_reload(do_reload) |
| 237 |
ports_by_type = semanage_port_get_ports(seport, setype, proto, local) |
| 238 |
for port in ports: |
| 239 |
if _port_is_covered(port, ports_by_type): |
| 240 |
continue |
| 241 |
|
| 242 |
change = True |
| 243 |
if module.check_mode: |
| 244 |
continue |
| 245 |
port_type = semanage_port_get_type(seport, port, proto) |
| 246 |
if port_type is None: |
| 247 |
seport.add(port, proto, serange, setype) |
| 248 |
else: |
| 249 |
seport.modify(port, proto, serange, setype) |
| 250 |
|
| 251 |
except FileNotFoundError as e: |
| 252 |
module.fail_json( |
| 253 |
msg=f"Failed to modify SELinux port policy, possibly due to a port overlap with an existing range: {e}\n", |
| 254 |
exception=traceback.format_exc(), |
| 255 |
) |
| 256 |
except (ValueError, OSError, KeyError, RuntimeError) as e: |
| 257 |
module.fail_json(msg=f"{e.__class__.__name__}: {e}\n", exception=traceback.format_exc()) |
| 258 |
|
| 259 |
return change |
| 260 |
|
| 261 |
|
| 262 |
def semanage_port_del(module, ports, proto, setype, do_reload, sestore="", local=False): |
| 263 |
"""Delete SELinux port type definition from the policy. |
| 264 |
|
| 265 |
:type module: AnsibleModule |
| 266 |
:param module: Ansible module |
| 267 |
|
| 268 |
:type ports: list |
| 269 |
:param ports: List of ports and port ranges to delete (e.g. ["8080", "8080-9090"]) |
| 270 |
|
| 271 |
:type proto: str |
| 272 |
:param proto: Protocol ('tcp', 'udp', 'dccp', 'sctp') |
| 273 |
|
| 274 |
:type setype: str |
| 275 |
:param setype: SELinux type. |
| 276 |
|
| 277 |
:type do_reload: bool |
| 278 |
:param do_reload: Whether to reload SELinux policy after commit |
| 279 |
|
| 280 |
:type sestore: str |
| 281 |
:param sestore: SELinux store |
| 282 |
|
| 283 |
:rtype: bool |
| 284 |
:return: True if the policy was changed, otherwise False |
| 285 |
""" |
| 286 |
change = False |
| 287 |
try: |
| 288 |
seport = seobject.portRecords(sestore) |
| 289 |
seport.set_reload(do_reload) |
| 290 |
ports_by_type = semanage_port_get_ports(seport, setype, proto, local) |
| 291 |
for port in ports: |
| 292 |
if port in ports_by_type: |
| 293 |
change = True |
| 294 |
if not module.check_mode: |
| 295 |
seport.delete(port, proto) |
| 296 |
|
| 297 |
except FileNotFoundError as e: |
| 298 |
module.fail_json( |
| 299 |
msg=f"Failed to modify SELinux port policy, possibly due to a port overlap with an existing range: {e}\n", |
| 300 |
exception=traceback.format_exc(), |
| 301 |
) |
| 302 |
except (ValueError, OSError, KeyError, RuntimeError) as e: |
| 303 |
module.fail_json(msg=f"{e.__class__.__name__}: {e}\n", exception=traceback.format_exc()) |
| 304 |
|
| 305 |
return change |
| 306 |
|
| 307 |
|
| 308 |
def main(): |
| 309 |
module = AnsibleModule( |
| 310 |
argument_spec=dict( |
| 311 |
ignore_selinux_state=dict(type="bool", default=False), |
| 312 |
ports=dict(type="list", elements="str", required=True), |
| 313 |
proto=dict(type="str", required=True, choices=["tcp", "udp", "dccp", "sctp"]), |
| 314 |
setype=dict(type="str", required=True), |
| 315 |
state=dict(type="str", default="present", choices=["absent", "present"]), |
| 316 |
reload=dict(type="bool", default=True), |
| 317 |
local=dict(type="bool", default=False), |
| 318 |
), |
| 319 |
supports_check_mode=True, |
| 320 |
) |
| 321 |
|
| 322 |
if not HAVE_SELINUX: |
| 323 |
module.fail_json(msg=missing_required_lib("libselinux-python"), exception=SELINUX_IMP_ERR) |
| 324 |
|
| 325 |
if not HAVE_SEOBJECT: |
| 326 |
module.fail_json(msg=missing_required_lib("policycoreutils-python"), exception=SEOBJECT_IMP_ERR) |
| 327 |
|
| 328 |
ignore_selinux_state = module.params["ignore_selinux_state"] |
| 329 |
|
| 330 |
if not get_runtime_status(ignore_selinux_state): |
| 331 |
module.fail_json(msg="SELinux is disabled on this host.") |
| 332 |
|
| 333 |
ports = module.params["ports"] |
| 334 |
proto = module.params["proto"] |
| 335 |
setype = module.params["setype"] |
| 336 |
state = module.params["state"] |
| 337 |
do_reload = module.params["reload"] |
| 338 |
local = module.params["local"] |
| 339 |
|
| 340 |
result = { |
| 341 |
"ports": ports, |
| 342 |
"proto": proto, |
| 343 |
"setype": setype, |
| 344 |
"state": state, |
| 345 |
} |
| 346 |
|
| 347 |
if state == "present": |
| 348 |
result["changed"] = semanage_port_add(module, ports, proto, setype, do_reload, local=local) |
| 349 |
elif state == "absent": |
| 350 |
result["changed"] = semanage_port_del(module, ports, proto, setype, do_reload, local=local) |
| 351 |
else: |
| 352 |
module.fail_json(msg=f'Invalid value of argument "state": {state}') |
| 353 |
|
| 354 |
module.exit_json(**result) |
| 355 |
|
| 356 |
|
| 357 |
if __name__ == "__main__": |
| 358 |
main() |