| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, Maciej Delmanowski <[email protected]> |
| 4 |
# Copyright (c) 2017, Alexander Korinek <[email protected]> |
| 5 |
# Copyright (c) 2016, Peter Sagerson <[email protected]> |
| 6 |
# Copyright (c) 2016, Jiri Tyr <[email protected]> |
| 7 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 8 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
DOCUMENTATION = r""" |
| 13 |
module: ldap_attrs |
| 14 |
short_description: Add or remove multiple LDAP attribute values |
| 15 |
description: |
| 16 |
- Add or remove multiple LDAP attribute values. |
| 17 |
notes: |
| 18 |
- This only deals with attributes on existing entries. To add or remove whole entries, see M(community.general.ldap_entry). |
| 19 |
- If O(honor_binary=true), an attribute that includes the C(binary) option as per |
| 20 |
L(RFC 4522, https://www.rfc-editor.org/rfc/rfc4522.html#section-3) will be considered as binary. Its contents must be |
| 21 |
specified as Base64 and sent to the LDAP after decoding. If an attribute must be handled as binary without including |
| 22 |
the C(binary) option, it can be listed in O(binary_attributes). |
| 23 |
- For O(state=present) and O(state=absent), when handling text attributes, all value comparisons are performed on the |
| 24 |
server for maximum accuracy. For O(state=exact) or binary attributes, values have to be compared in Python, which |
| 25 |
obviously ignores LDAP matching rules. This should work out in most cases, but it is theoretically possible to see |
| 26 |
spurious changes when target and actual values are semantically identical but lexically distinct. |
| 27 |
- Support for binary values was added in community.general 12.5.0. |
| 28 |
version_added: '0.2.0' |
| 29 |
author: |
| 30 |
- Jiri Tyr (@jtyr) |
| 31 |
- Alexander Korinek (@noles) |
| 32 |
- Maciej Delmanowski (@drybjed) |
| 33 |
requirements: |
| 34 |
- python-ldap |
| 35 |
attributes: |
| 36 |
check_mode: |
| 37 |
support: full |
| 38 |
diff_mode: |
| 39 |
support: full |
| 40 |
version_added: 8.5.0 |
| 41 |
options: |
| 42 |
state: |
| 43 |
type: str |
| 44 |
choices: [present, absent, exact] |
| 45 |
default: present |
| 46 |
description: |
| 47 |
- The state of the attribute values. If V(present), all given attribute values are added if they are missing. If V(absent), |
| 48 |
all given attribute values are removed if present. If V(exact), the set of attribute values is forced to exactly those |
| 49 |
provided and no others. If O(state=exact) and the attribute value is empty, all values for this attribute are removed. |
| 50 |
binary_attributes: |
| 51 |
description: |
| 52 |
- If O(state=present), attributes whose values must be handled as raw sequences of bytes must be listed here. |
| 53 |
- The values provided for the attributes will be converted from Base64. |
| 54 |
type: list |
| 55 |
elements: str |
| 56 |
default: [] |
| 57 |
version_added: 12.5.0 |
| 58 |
honor_binary: |
| 59 |
description: |
| 60 |
- If O(state=present) and this option is V(true), attributes whose name include the V(binary) option |
| 61 |
will be treated as Base64-encoded byte sequences automatically, even if they are not listed in O(binary_attributes). |
| 62 |
type: bool |
| 63 |
default: false |
| 64 |
version_added: 12.5.0 |
| 65 |
attributes: |
| 66 |
required: true |
| 67 |
type: dict |
| 68 |
description: |
| 69 |
- The attribute(s) and value(s) to add or remove. |
| 70 |
- Each attribute value can be a string for single-valued attributes or a list of strings for multi-valued attributes. |
| 71 |
- If you specify values for this option in YAML, please note that you can improve readability for long string values |
| 72 |
by using YAML block modifiers as seen in the examples for this module. |
| 73 |
- Note that when using values that YAML/ansible-core interprets as other types, like V(yes), V(no) (booleans), or V(2.10) |
| 74 |
(float), make sure to quote them if these are meant to be strings. Otherwise the wrong values may be sent to LDAP. |
| 75 |
ordered: |
| 76 |
type: bool |
| 77 |
default: false |
| 78 |
description: |
| 79 |
- If V(true), prepend list values with X-ORDERED index numbers in all attributes specified in the current task. This |
| 80 |
is useful mostly with C(olcAccess) attribute to easily manage LDAP Access Control Lists. |
| 81 |
extends_documentation_fragment: |
| 82 |
- community.general._ldap.documentation |
| 83 |
- community.general._attributes |
| 84 |
""" |
| 85 |
|
| 86 |
|
| 87 |
EXAMPLES = r""" |
| 88 |
- name: Configure directory number 1 for example.com |
| 89 |
community.general.ldap_attrs: |
| 90 |
dn: olcDatabase={1}hdb,cn=config |
| 91 |
attributes: |
| 92 |
olcSuffix: dc=example,dc=com |
| 93 |
state: exact |
| 94 |
|
| 95 |
# The complex argument format is required here to pass a list of ACL strings. |
| 96 |
- name: Set up the ACL |
| 97 |
community.general.ldap_attrs: |
| 98 |
dn: olcDatabase={1}hdb,cn=config |
| 99 |
attributes: |
| 100 |
olcAccess: |
| 101 |
- >- |
| 102 |
{0}to attrs=userPassword,shadowLastChange |
| 103 |
by self write |
| 104 |
by anonymous auth |
| 105 |
by dn="cn=admin,dc=example,dc=com" write |
| 106 |
by * none' |
| 107 |
- >- |
| 108 |
{1}to dn.base="dc=example,dc=com" |
| 109 |
by dn="cn=admin,dc=example,dc=com" write |
| 110 |
by * read |
| 111 |
state: exact |
| 112 |
|
| 113 |
# An alternative approach with automatic X-ORDERED numbering |
| 114 |
- name: Set up the ACL |
| 115 |
community.general.ldap_attrs: |
| 116 |
dn: olcDatabase={1}hdb,cn=config |
| 117 |
attributes: |
| 118 |
olcAccess: |
| 119 |
- >- |
| 120 |
to attrs=userPassword,shadowLastChange |
| 121 |
by self write |
| 122 |
by anonymous auth |
| 123 |
by dn="cn=admin,dc=example,dc=com" write |
| 124 |
by * none' |
| 125 |
- >- |
| 126 |
to dn.base="dc=example,dc=com" |
| 127 |
by dn="cn=admin,dc=example,dc=com" write |
| 128 |
by * read |
| 129 |
ordered: true |
| 130 |
state: exact |
| 131 |
|
| 132 |
- name: Declare some indexes |
| 133 |
community.general.ldap_attrs: |
| 134 |
dn: olcDatabase={1}hdb,cn=config |
| 135 |
attributes: |
| 136 |
olcDbIndex: |
| 137 |
- objectClass eq |
| 138 |
- uid eq |
| 139 |
|
| 140 |
- name: Set up a root user, which we can use later to bootstrap the directory |
| 141 |
community.general.ldap_attrs: |
| 142 |
dn: olcDatabase={1}hdb,cn=config |
| 143 |
attributes: |
| 144 |
olcRootDN: cn=root,dc=example,dc=com |
| 145 |
olcRootPW: "{SSHA}tabyipcHzhwESzRaGA7oQ/SDoBZQOGND" |
| 146 |
state: exact |
| 147 |
|
| 148 |
- name: Replace a CA certificate |
| 149 |
community.general.ldap_attrs: |
| 150 |
dn: cn=ISRG Root X1,ou=ca,ou=certificates,dc=example,dc=org |
| 151 |
honor_binary: true |
| 152 |
state: exact |
| 153 |
attributes: |
| 154 |
cACertificate;binary: >- |
| 155 |
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw |
| 156 |
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh |
| 157 |
# ... |
| 158 |
|
| 159 |
- name: Remove an attribute with a specific value |
| 160 |
community.general.ldap_attrs: |
| 161 |
dn: uid=jdoe,ou=people,dc=example,dc=com |
| 162 |
attributes: |
| 163 |
description: "An example user account" |
| 164 |
state: absent |
| 165 |
server_uri: ldap://localhost/ |
| 166 |
bind_dn: cn=admin,dc=example,dc=com |
| 167 |
bind_pw: password |
| 168 |
|
| 169 |
- name: Remove specified attribute(s) from an entry |
| 170 |
community.general.ldap_attrs: |
| 171 |
dn: uid=jdoe,ou=people,dc=example,dc=com |
| 172 |
attributes: |
| 173 |
description: [] |
| 174 |
state: exact |
| 175 |
server_uri: ldap://localhost/ |
| 176 |
bind_dn: cn=admin,dc=example,dc=com |
| 177 |
bind_pw: password |
| 178 |
""" |
| 179 |
|
| 180 |
|
| 181 |
RETURN = r""" |
| 182 |
modlist: |
| 183 |
description: List of modified parameters. |
| 184 |
returned: success |
| 185 |
type: list |
| 186 |
sample: |
| 187 |
- [2, "olcRootDN", ["cn=root,dc=example,dc=com"]] |
| 188 |
""" |
| 189 |
|
| 190 |
import base64 |
| 191 |
import binascii |
| 192 |
import re |
| 193 |
import traceback |
| 194 |
|
| 195 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 196 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 197 |
|
| 198 |
from ansible_collections.community.general.plugins.module_utils._ldap import ( |
| 199 |
LdapGeneric, |
| 200 |
gen_specs, |
| 201 |
ldap_required_together, |
| 202 |
) |
| 203 |
|
| 204 |
LDAP_IMP_ERR = None |
| 205 |
try: |
| 206 |
import ldap |
| 207 |
import ldap.filter |
| 208 |
|
| 209 |
HAS_LDAP = True |
| 210 |
except ImportError: |
| 211 |
LDAP_IMP_ERR = traceback.format_exc() |
| 212 |
HAS_LDAP = False |
| 213 |
|
| 214 |
|
| 215 |
class LdapAttrs(LdapGeneric): |
| 216 |
def __init__(self, module): |
| 217 |
LdapGeneric.__init__(self, module) |
| 218 |
|
| 219 |
# Shortcuts |
| 220 |
self.attrs = self.module.params["attributes"] |
| 221 |
self.state = self.module.params["state"] |
| 222 |
self.ordered = self.module.params["ordered"] |
| 223 |
self.binary = set(attr.lower() for attr in self.module.params["binary_attributes"]) |
| 224 |
self.honor_binary = self.module.params["honor_binary"] |
| 225 |
|
| 226 |
# Cached attribute values |
| 227 |
self._cached_values = {} |
| 228 |
|
| 229 |
def _order_values(self, values): |
| 230 |
"""Prepend X-ORDERED index numbers to attribute's values.""" |
| 231 |
ordered_values = [] |
| 232 |
|
| 233 |
if isinstance(values, list): |
| 234 |
for index, value in enumerate(values): |
| 235 |
cleaned_value = re.sub(r"^\{\d+\}", "", value) |
| 236 |
ordered_values.append(f"{{{index!s}}}{cleaned_value}") |
| 237 |
|
| 238 |
return ordered_values |
| 239 |
|
| 240 |
def _is_binary(self, attr_name): |
| 241 |
"""Check if an attribute must be considered binary.""" |
| 242 |
lc_name = attr_name.lower() |
| 243 |
return (self.honor_binary and "binary" in lc_name.split(";")) or lc_name in self.binary |
| 244 |
|
| 245 |
def _normalize_values(self, values, is_binary): |
| 246 |
"""Normalize attribute's values.""" |
| 247 |
if is_binary: |
| 248 |
converter = base64.b64decode |
| 249 |
else: |
| 250 |
converter = to_bytes |
| 251 |
|
| 252 |
if not isinstance(values, list): |
| 253 |
values = [values] |
| 254 |
elif self.ordered and not is_binary: |
| 255 |
values = self._order_values([str(value) for value in values]) |
| 256 |
|
| 257 |
try: |
| 258 |
return [converter(value) for value in values] |
| 259 |
except binascii.Error: |
| 260 |
return None |
| 261 |
|
| 262 |
def add(self): |
| 263 |
modlist = [] |
| 264 |
new_attrs = {} |
| 265 |
bad_bin_attrs = [] |
| 266 |
for name, values in self.module.params["attributes"].items(): |
| 267 |
norm_values = self._normalize_values(values, self._is_binary(name)) |
| 268 |
if norm_values is None: |
| 269 |
bad_bin_attrs.append(name) |
| 270 |
continue |
| 271 |
added_values = [] |
| 272 |
for value in norm_values: |
| 273 |
if self._is_value_absent(name, value): |
| 274 |
modlist.append((ldap.MOD_ADD, name, value)) |
| 275 |
added_values.append(value) |
| 276 |
if added_values: |
| 277 |
new_attrs[name] = norm_values |
| 278 |
return modlist, {}, new_attrs, bad_bin_attrs |
| 279 |
|
| 280 |
def delete(self): |
| 281 |
modlist = [] |
| 282 |
old_attrs = {} |
| 283 |
new_attrs = {} |
| 284 |
bad_bin_attrs = [] |
| 285 |
for name, values in self.module.params["attributes"].items(): |
| 286 |
norm_values = self._normalize_values(values, self._is_binary(name)) |
| 287 |
if norm_values is None: |
| 288 |
bad_bin_attrs.append(name) |
| 289 |
continue |
| 290 |
removed_values = [] |
| 291 |
for value in norm_values: |
| 292 |
if self._is_value_present(name, value): |
| 293 |
removed_values.append(value) |
| 294 |
modlist.append((ldap.MOD_DELETE, name, value)) |
| 295 |
if removed_values: |
| 296 |
old_attrs[name] = norm_values |
| 297 |
new_attrs[name] = [value for value in norm_values if value not in removed_values] |
| 298 |
return modlist, old_attrs, new_attrs, bad_bin_attrs |
| 299 |
|
| 300 |
def exact(self): |
| 301 |
modlist = [] |
| 302 |
old_attrs = {} |
| 303 |
new_attrs = {} |
| 304 |
bad_bin_attrs = [] |
| 305 |
for name, values in self.module.params["attributes"].items(): |
| 306 |
norm_values = self._normalize_values(values, self._is_binary(name)) |
| 307 |
if norm_values is None: |
| 308 |
bad_bin_attrs.append(name) |
| 309 |
continue |
| 310 |
current = self._get_all_values_of(name) |
| 311 |
|
| 312 |
if frozenset(norm_values) != frozenset(current): |
| 313 |
if len(current) == 0: |
| 314 |
modlist.append((ldap.MOD_ADD, name, norm_values)) |
| 315 |
elif len(norm_values) == 0: |
| 316 |
modlist.append((ldap.MOD_DELETE, name, None)) |
| 317 |
else: |
| 318 |
modlist.append((ldap.MOD_REPLACE, name, norm_values)) |
| 319 |
old_attrs[name] = current |
| 320 |
new_attrs[name] = norm_values |
| 321 |
if len(current) == 1 and len(norm_values) == 1: |
| 322 |
old_attrs[name] = current[0] |
| 323 |
new_attrs[name] = norm_values[0] |
| 324 |
|
| 325 |
return modlist, old_attrs, new_attrs, bad_bin_attrs |
| 326 |
|
| 327 |
def _is_value_present(self, name, value): |
| 328 |
"""True if the target attribute has the given value.""" |
| 329 |
if self._is_binary(name): |
| 330 |
return value in self._get_all_values_of(name) |
| 331 |
|
| 332 |
try: |
| 333 |
escaped_value = ldap.filter.escape_filter_chars(to_text(value)) |
| 334 |
filterstr = f"({name}={escaped_value})" |
| 335 |
dns = self.connection.search_s(self.dn, ldap.SCOPE_BASE, filterstr) |
| 336 |
is_present = len(dns) == 1 |
| 337 |
except ldap.NO_SUCH_OBJECT: |
| 338 |
is_present = False |
| 339 |
|
| 340 |
return is_present |
| 341 |
|
| 342 |
def _get_all_values_of(self, name): |
| 343 |
"""Return all values of an attribute.""" |
| 344 |
lc_name = name.lower() |
| 345 |
if lc_name not in self._cached_values: |
| 346 |
try: |
| 347 |
results = self.connection.search_s(self.dn, ldap.SCOPE_BASE, attrlist=[name]) |
| 348 |
except ldap.LDAPError as e: |
| 349 |
self.fail(f"Cannot search for attribute {name}", e) |
| 350 |
attrs = results[0][1] |
| 351 |
self._cached_values[lc_name] = next((v for k, v in attrs.items() if k.lower() == lc_name), []) |
| 352 |
return self._cached_values[lc_name] |
| 353 |
|
| 354 |
def _is_value_absent(self, name, value): |
| 355 |
"""True if the target attribute doesn't have the given value.""" |
| 356 |
return not self._is_value_present(name, value) |
| 357 |
|
| 358 |
def _reencode_modlist(self, modlist): |
| 359 |
"""Re-encode binary attribute values in the modlist into Base64 in |
| 360 |
order to avoid crashing the plugin when returning the modlist to |
| 361 |
Ansible.""" |
| 362 |
output = [] |
| 363 |
for mod_op, attr, values in modlist: |
| 364 |
if self._is_binary(attr) and values is not None: |
| 365 |
values = [base64.b64encode(value) for value in values] |
| 366 |
output.append((mod_op, attr, values)) |
| 367 |
return output |
| 368 |
|
| 369 |
def _reencode_attributes(self, attributes): |
| 370 |
"""Re-encode binary attribute values in an attribute dict into Base64 in |
| 371 |
order to avoid crashing the plugin when returning the dict to Ansible.""" |
| 372 |
output = {} |
| 373 |
for name, values in attributes.items(): |
| 374 |
if self._is_binary(name): |
| 375 |
if isinstance(values, list): |
| 376 |
values = [base64.b64encode(value) for value in values] |
| 377 |
else: |
| 378 |
values = base64.b64encode(values) |
| 379 |
output[name] = values |
| 380 |
return output |
| 381 |
|
| 382 |
|
| 383 |
def main(): |
| 384 |
module = AnsibleModule( |
| 385 |
argument_spec=gen_specs( |
| 386 |
attributes=dict(type="dict", required=True), |
| 387 |
binary_attributes=dict(default=[], type="list", elements="str"), |
| 388 |
honor_binary=dict(default=False, type="bool"), |
| 389 |
ordered=dict(type="bool", default=False), |
| 390 |
state=dict(type="str", default="present", choices=["absent", "exact", "present"]), |
| 391 |
), |
| 392 |
supports_check_mode=True, |
| 393 |
required_together=ldap_required_together(), |
| 394 |
) |
| 395 |
|
| 396 |
if not HAS_LDAP: |
| 397 |
module.fail_json(msg=missing_required_lib("python-ldap"), exception=LDAP_IMP_ERR) |
| 398 |
|
| 399 |
# Instantiate the LdapAttr object |
| 400 |
ldap = LdapAttrs(module) |
| 401 |
old_attrs = None |
| 402 |
new_attrs = None |
| 403 |
modlist = [] |
| 404 |
|
| 405 |
state = module.params["state"] |
| 406 |
|
| 407 |
# Perform action |
| 408 |
if state == "present": |
| 409 |
modlist, old_attrs, new_attrs, bad_attrs = ldap.add() |
| 410 |
elif state == "absent": |
| 411 |
modlist, old_attrs, new_attrs, bad_attrs = ldap.delete() |
| 412 |
elif state == "exact": |
| 413 |
modlist, old_attrs, new_attrs, bad_attrs = ldap.exact() |
| 414 |
|
| 415 |
if bad_attrs: |
| 416 |
s_bad_attrs = ", ".join(bad_attrs) |
| 417 |
module.fail_json(msg=f"Invalid Base64-encoded attribute values for {s_bad_attrs}") |
| 418 |
|
| 419 |
changed = False |
| 420 |
|
| 421 |
if len(modlist) > 0: |
| 422 |
changed = True |
| 423 |
|
| 424 |
if not module.check_mode: |
| 425 |
try: |
| 426 |
ldap.connection.modify_s(ldap.dn, modlist) |
| 427 |
except Exception as e: |
| 428 |
module.fail_json(msg="Attribute action failed.", details=f"{e}") |
| 429 |
|
| 430 |
# If the data contain binary attributes/changes, we need to re-encode them |
| 431 |
# using Base64. |
| 432 |
modlist = ldap._reencode_modlist(modlist) |
| 433 |
old_attrs = ldap._reencode_attributes(old_attrs) |
| 434 |
new_attrs = ldap._reencode_attributes(new_attrs) |
| 435 |
|
| 436 |
module.exit_json(changed=changed, modlist=modlist, diff={"before": old_attrs, "after": new_attrs}) |
| 437 |
|
| 438 |
|
| 439 |
if __name__ == "__main__": |
| 440 |
main() |