Debian Codegraph @

ansible_collections/community/general/plugins/modules/ldap_entry.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Peter Sagerson <[email protected]>
4 # Copyright (c) 2016, Jiri Tyr <[email protected]>
5 #
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: ldap_entry
13 short_description: Add or remove LDAP entries
14 description:
15 - Add or remove LDAP entries. This module only asserts the existence or non-existence of an LDAP entry, not its attributes.
16 To assert the attribute values of an entry, see M(community.general.ldap_attrs).
17 author:
18 - Jiri Tyr (@jtyr)
19 requirements:
20 - python-ldap
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 attributes:
28 description:
29 - If O(state=present), attributes necessary to create an entry. Existing entries are never modified. To assert specific
30 attribute values on an existing entry, use M(community.general.ldap_attrs) module instead.
31 - Each attribute value can be a string for single-valued attributes or a list of strings for multi-valued attributes.
32 - If you specify values for this option in YAML, please note that you can improve readability for long string values
33 by using YAML block modifiers as seen in the examples for this module.
34 - Note that when using values that YAML/ansible-core interprets as other types, like V(yes), V(no) (booleans), or V(2.10)
35 (float), make sure to quote them if these are meant to be strings. Otherwise the wrong values may be sent to LDAP.
36 - If O(honor_binary=true), an attribute that includes the C(binary) option as per
37 L(RFC 4522, https://www.rfc-editor.org/rfc/rfc4522.html#section-3) will be considered as binary. Its contents must be
38 specified as Base64 and sent to the LDAP after decoding. If an attribute must be handled as binary without including
39 the C(binary) option, it can be listed in O(binary_attributes).
40 Support for binary values was added in community.general 12.5.0.
41 type: dict
42 default: {}
43 binary_attributes:
44 description:
45 - If O(state=present), attributes whose values must be handled as raw sequences of bytes must be listed here.
46 - The values provided for the attributes will be converted from Base64.
47 type: list
48 elements: str
49 default: []
50 version_added: 12.5.0
51 honor_binary:
52 description:
53 - If O(state=present) and this option is V(true), attributes whose name include the V(binary) option
54 will be treated as Base64-encoded byte sequences automatically, even if they are not listed in O(binary_attributes).
55 type: bool
56 default: false
57 version_added: 12.5.0
58 objectClass:
59 description:
60 - If O(state=present), value or list of values to use when creating the entry. It can either be a string or an actual
61 list of strings.
62 type: list
63 elements: str
64 state:
65 description:
66 - The target state of the entry.
67 choices: [present, absent]
68 default: present
69 type: str
70 recursive:
71 description:
72 - If O(state=delete), a flag indicating whether a single entry or the whole branch must be deleted.
73 type: bool
74 default: false
75 version_added: 4.6.0
76 extends_documentation_fragment:
77 - community.general._ldap.documentation
78 - community.general._attributes
79 """
80
81
82 EXAMPLES = r"""
83 - name: Make sure we have a parent entry for users
84 community.general.ldap_entry:
85 dn: ou=users,dc=example,dc=com
86 objectClass: organizationalUnit
87
88 - name: Make sure we have an admin user
89 community.general.ldap_entry:
90 dn: cn=admin,dc=example,dc=com
91 objectClass:
92 - simpleSecurityObject
93 - organizationalRole
94 - myPhotoObject
95 binary_attributes:
96 - myPhoto
97 attributes:
98 description: An LDAP administrator
99 userPassword: "{SSHA}tabyipcHzhwESzRaGA7oQ/SDoBZQOGND"
100 myPhoto: >-
101 /9j/4AAQSkZJRgABAQAAAQABAAD/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNt
102 cwIQAABtbnRyUkdCIFhZWiAH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAAA
103 # ...
104
105 - name: Make sure a CA certificate is present
106 community.general.ldap_attrs:
107 dn: cn=ISRG Root X1,ou=ca,ou=certificates,dc=example,dc=org
108 honor_binary: true
109 objectClass:
110 - pkiCA
111 - applicationProcess
112 attributes:
113 cn: ISRG Root X1
114 cACertificate;binary: >-
115 MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
116 TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
117 # ...
118
119 - name: Set possible values for attributes elements
120 community.general.ldap_entry:
121 dn: cn=admin,dc=example,dc=com
122 objectClass:
123 - simpleSecurityObject
124 - organizationalRole
125 attributes:
126 description: An LDAP Administrator
127 roleOccupant:
128 - cn=Chocs Puddington,ou=Information Technology,dc=example,dc=com
129 - cn=Alice Stronginthebrain,ou=Information Technology,dc=example,dc=com
130 olcAccess:
131 - >-
132 {0}to attrs=userPassword,shadowLastChange
133 by self write
134 by anonymous auth
135 by dn="cn=admin,dc=example,dc=com" write
136 by * none'
137 - >-
138 {1}to dn.base="dc=example,dc=com"
139 by dn="cn=admin,dc=example,dc=com" write
140 by * read
141
142 - name: Get rid of an old entry
143 community.general.ldap_entry:
144 dn: ou=stuff,dc=example,dc=com
145 state: absent
146 server_uri: ldap://localhost/
147 bind_dn: cn=admin,dc=example,dc=com
148 bind_pw: password
149
150 #
151 # The same as in the previous example but with the authentication details
152 # stored in the ldap_auth variable:
153 #
154 # ldap_auth:
155 # server_uri: ldap://localhost/
156 # bind_dn: cn=admin,dc=example,dc=com
157 # bind_pw: password
158 #
159 # In the example below, 'args' is a task keyword, passed at the same level as the module
160 - name: Get rid of an old entry
161 community.general.ldap_entry:
162 dn: ou=stuff,dc=example,dc=com
163 state: absent
164 args: "{{ ldap_auth }}"
165 """
166
167
168 RETURN = r"""
169 # Default return values
170 """
171
172 import base64
173 import binascii
174 import traceback
175
176 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
177 from ansible.module_utils.common.text.converters import to_bytes
178
179 from ansible_collections.community.general.plugins.module_utils._ldap import (
180 LdapGeneric,
181 gen_specs,
182 ldap_required_together,
183 )
184
185 LDAP_IMP_ERR = None
186 try:
187 import ldap.controls
188 import ldap.modlist
189
190 HAS_LDAP = True
191 except ImportError:
192 LDAP_IMP_ERR = traceback.format_exc()
193 HAS_LDAP = False
194
195
196 class LdapEntry(LdapGeneric):
197 def __init__(self, module):
198 LdapGeneric.__init__(self, module)
199
200 # Shortcuts
201 self.state = self.module.params["state"]
202 self.recursive = self.module.params["recursive"]
203 self.binary = set(attr.lower() for attr in self.module.params["binary_attributes"])
204 self.honor_binary = self.module.params["honor_binary"]
205
206 # Add the objectClass into the list of attributes
207 self.module.params["attributes"]["objectClass"] = self.module.params["objectClass"]
208
209 # Load attributes
210 if self.state == "present":
211 self.attrs, bad_attrs = self._load_attrs()
212 if bad_attrs:
213 s_bad_attrs = ", ".join(bad_attrs)
214 self.module.fail_json(msg=f"Invalid Base64-encoded attribute values for {s_bad_attrs}")
215
216 def _is_binary(self, attr_name):
217 """Check if an attribute must be considered binary."""
218 lc_name = attr_name.lower()
219 return (self.honor_binary and "binary" in lc_name.split(";")) or lc_name in self.binary
220
221 def _load_attrs(self):
222 """Turn attribute's value to array. Attribute values are converted to
223 raw bytes, either by encoding the string itself, or by decoding it from
224 base 64, depending on the binary attributes settings."""
225 attrs = {}
226 bad_attrs = []
227
228 for name, value in self.module.params["attributes"].items():
229 if self._is_binary(name):
230 converter = base64.b64decode
231 else:
232 converter = to_bytes
233 if not isinstance(value, list):
234 value = [value]
235 try:
236 attrs[name] = [converter(v) for v in value]
237 except binascii.Error:
238 bad_attrs.append(name)
239
240 return attrs, bad_attrs
241
242 def add(self):
243 """If self.dn does not exist, returns a callable that will add it."""
244
245 def _add():
246 self.connection.add_s(self.dn, modlist)
247
248 if not self._is_entry_present():
249 modlist = ldap.modlist.addModlist(self.attrs)
250 action = _add
251 else:
252 action = None
253
254 return action
255
256 def delete(self):
257 """If self.dn exists, returns a callable that will delete either
258 the item itself if the recursive option is not set or the whole branch
259 if it is."""
260
261 def _delete():
262 self.connection.delete_s(self.dn)
263
264 def _delete_recursive():
265 """Attempt recursive deletion using the subtree-delete control.
266 If that fails, do it manually."""
267 try:
268 subtree_delete = ldap.controls.ValueLessRequestControl("1.2.840.113556.1.4.805")
269 self.connection.delete_ext_s(self.dn, serverctrls=[subtree_delete])
270 except ldap.NOT_ALLOWED_ON_NONLEAF:
271 search = self.connection.search_s(self.dn, ldap.SCOPE_SUBTREE, attrlist=("dn",))
272 search.reverse()
273 for entry in search:
274 self.connection.delete_s(entry[0])
275
276 if self._is_entry_present():
277 if self.recursive:
278 action = _delete_recursive
279 else:
280 action = _delete
281 else:
282 action = None
283
284 return action
285
286 def _is_entry_present(self):
287 try:
288 self.connection.search_s(self.dn, ldap.SCOPE_BASE)
289 except ldap.NO_SUCH_OBJECT:
290 is_present = False
291 else:
292 is_present = True
293
294 return is_present
295
296
297 def main():
298 module = AnsibleModule(
299 argument_spec=gen_specs(
300 attributes=dict(default={}, type="dict"),
301 binary_attributes=dict(default=[], type="list", elements="str"),
302 honor_binary=dict(default=False, type="bool"),
303 objectClass=dict(type="list", elements="str"),
304 state=dict(default="present", choices=["present", "absent"]),
305 recursive=dict(default=False, type="bool"),
306 ),
307 required_if=[("state", "present", ["objectClass"])],
308 supports_check_mode=True,
309 required_together=ldap_required_together(),
310 )
311
312 if not HAS_LDAP:
313 module.fail_json(msg=missing_required_lib("python-ldap"), exception=LDAP_IMP_ERR)
314
315 state = module.params["state"]
316
317 # Instantiate the LdapEntry object
318 ldap = LdapEntry(module)
319
320 # Get the action function
321 if state == "present":
322 action = ldap.add()
323 elif state == "absent":
324 action = ldap.delete()
325
326 # Perform the action
327 if action is not None and not module.check_mode:
328 try:
329 action()
330 except Exception as e:
331 module.fail_json(msg="Entry action failed.", details=f"{e}", exception=traceback.format_exc())
332
333 module.exit_json(changed=(action is not None))
334
335
336 if __name__ == "__main__":
337 main()