| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2016, Peter Sagerson <[email protected]> |
| 4 |
# Copyright (c) 2020, Sebastian Pfahl <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: ldap_search |
| 12 |
version_added: '0.2.0' |
| 13 |
short_description: Search for entries in a LDAP server |
| 14 |
description: |
| 15 |
- Return the results of an LDAP search. |
| 16 |
author: |
| 17 |
- Sebastian Pfahl (@eryx12o45) |
| 18 |
requirements: |
| 19 |
- python-ldap |
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
support: full |
| 23 |
diff_mode: |
| 24 |
support: none |
| 25 |
options: |
| 26 |
dn: |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
description: |
| 30 |
- The LDAP DN to search in. |
| 31 |
scope: |
| 32 |
choices: [base, onelevel, subordinate, children] |
| 33 |
default: base |
| 34 |
type: str |
| 35 |
description: |
| 36 |
- The LDAP scope to use. |
| 37 |
- V(subordinate) requires the LDAPv3 subordinate feature extension. |
| 38 |
- V(children) is equivalent to a "subtree" scope. |
| 39 |
filter: |
| 40 |
default: '(objectClass=*)' |
| 41 |
type: str |
| 42 |
description: |
| 43 |
- Used for filtering the LDAP search result. |
| 44 |
attrs: |
| 45 |
type: list |
| 46 |
elements: str |
| 47 |
description: |
| 48 |
- A list of attributes for limiting the result. Use an actual list or a comma-separated string. |
| 49 |
schema: |
| 50 |
default: false |
| 51 |
type: bool |
| 52 |
description: |
| 53 |
- Set to V(true) to return the full attribute schema of entries, not their attribute values. Overrides O(attrs) when |
| 54 |
provided. |
| 55 |
page_size: |
| 56 |
default: 0 |
| 57 |
type: int |
| 58 |
description: |
| 59 |
- The page size when performing a simple paged result search (RFC 2696). This setting can be tuned to reduce issues |
| 60 |
with timeouts and server limits. |
| 61 |
- Setting the page size to V(0) (default) disables paged searching. |
| 62 |
version_added: 7.1.0 |
| 63 |
base64_attributes: |
| 64 |
description: |
| 65 |
- If provided, all attribute values returned that are listed in this option are Base64 encoded. |
| 66 |
- If the special value V(*) appears in this list, all attributes are Base64 encoded. |
| 67 |
- All other attribute values are converted to UTF-8 strings. If they contain binary data, please note that invalid UTF-8 |
| 68 |
bytes are omitted. |
| 69 |
type: list |
| 70 |
elements: str |
| 71 |
version_added: 7.0.0 |
| 72 |
extends_documentation_fragment: |
| 73 |
- community.general._ldap.documentation |
| 74 |
- community.general._attributes |
| 75 |
""" |
| 76 |
|
| 77 |
EXAMPLES = r""" |
| 78 |
- name: Return all entries within the 'groups' organizational unit. |
| 79 |
community.general.ldap_search: |
| 80 |
dn: "ou=groups,dc=example,dc=com" |
| 81 |
register: ldap_groups |
| 82 |
|
| 83 |
- name: Return GIDs for all groups |
| 84 |
community.general.ldap_search: |
| 85 |
dn: "ou=groups,dc=example,dc=com" |
| 86 |
scope: "onelevel" |
| 87 |
attrs: |
| 88 |
- "gidNumber" |
| 89 |
register: ldap_group_gids |
| 90 |
""" |
| 91 |
|
| 92 |
# @FIXME RV 'results' is meant to be used when 'loop:' was used with the module. |
| 93 |
RESULTS = r""" |
| 94 |
results: |
| 95 |
description: |
| 96 |
- For every entry found, one dictionary is returned. |
| 97 |
- Every dictionary contains a key C(dn) with the entry's DN as a value. |
| 98 |
- Every attribute of the entry found is added to the dictionary. If the key has precisely one value, that value is taken |
| 99 |
directly, otherwise the key's value is a list. |
| 100 |
- Note that all values (for single-element lists) and list elements (for multi-valued lists) are UTF-8 strings. Some might |
| 101 |
contain Base64-encoded binary data; which ones is determined by the O(base64_attributes) option. |
| 102 |
type: list |
| 103 |
elements: dict |
| 104 |
""" |
| 105 |
|
| 106 |
import base64 |
| 107 |
import traceback |
| 108 |
|
| 109 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 110 |
from ansible.module_utils.common.text.converters import to_bytes, to_text |
| 111 |
|
| 112 |
from ansible_collections.community.general.plugins.module_utils._ldap import ( |
| 113 |
LdapGeneric, |
| 114 |
gen_specs, |
| 115 |
ldap_required_together, |
| 116 |
) |
| 117 |
|
| 118 |
LDAP_IMP_ERR = None |
| 119 |
try: |
| 120 |
import ldap |
| 121 |
|
| 122 |
HAS_LDAP = True |
| 123 |
except ImportError: |
| 124 |
LDAP_IMP_ERR = traceback.format_exc() |
| 125 |
HAS_LDAP = False |
| 126 |
|
| 127 |
|
| 128 |
def main(): |
| 129 |
module = AnsibleModule( |
| 130 |
argument_spec=gen_specs( |
| 131 |
dn=dict(type="str", required=True), |
| 132 |
scope=dict(type="str", default="base", choices=["base", "onelevel", "subordinate", "children"]), |
| 133 |
filter=dict(type="str", default="(objectClass=*)"), |
| 134 |
attrs=dict(type="list", elements="str"), |
| 135 |
schema=dict(type="bool", default=False), |
| 136 |
page_size=dict(type="int", default=0), |
| 137 |
base64_attributes=dict(type="list", elements="str"), |
| 138 |
), |
| 139 |
supports_check_mode=True, |
| 140 |
required_together=ldap_required_together(), |
| 141 |
) |
| 142 |
|
| 143 |
if not HAS_LDAP: |
| 144 |
module.fail_json(msg=missing_required_lib("python-ldap"), exception=LDAP_IMP_ERR) |
| 145 |
|
| 146 |
try: |
| 147 |
LdapSearch(module).main() |
| 148 |
except Exception as exception: |
| 149 |
module.fail_json(msg="Attribute action failed.", details=f"{exception}") |
| 150 |
|
| 151 |
|
| 152 |
def _normalize_string(val, convert_to_base64): |
| 153 |
if isinstance(val, (str, bytes)): |
| 154 |
if isinstance(val, str): |
| 155 |
val = to_bytes(val, encoding="utf-8") |
| 156 |
if convert_to_base64: |
| 157 |
val = to_text(base64.b64encode(val)) |
| 158 |
else: |
| 159 |
# See https://github.com/ansible/ansible/issues/80258#issuecomment-1477038952 for details. |
| 160 |
# We want to make sure that all strings are properly UTF-8 encoded, even if they were not, |
| 161 |
# or happened to be byte strings. |
| 162 |
val = to_text(val, "utf-8", errors="replace") |
| 163 |
# See also https://github.com/ansible-collections/community.general/issues/5704. |
| 164 |
return val |
| 165 |
|
| 166 |
|
| 167 |
def _extract_entry(dn, attrs, base64_attributes): |
| 168 |
extracted = {"dn": dn} |
| 169 |
for attr, val in list(attrs.items()): |
| 170 |
convert_to_base64 = "*" in base64_attributes or attr in base64_attributes |
| 171 |
if len(val) == 1: |
| 172 |
extracted[attr] = _normalize_string(val[0], convert_to_base64) |
| 173 |
else: |
| 174 |
extracted[attr] = [_normalize_string(v, convert_to_base64) for v in val] |
| 175 |
return extracted |
| 176 |
|
| 177 |
|
| 178 |
class LdapSearch(LdapGeneric): |
| 179 |
def __init__(self, module): |
| 180 |
LdapGeneric.__init__(self, module) |
| 181 |
|
| 182 |
self.filterstr = self.module.params["filter"] |
| 183 |
self.attrlist = [] |
| 184 |
self.page_size = self.module.params["page_size"] |
| 185 |
self._load_scope() |
| 186 |
self._load_attrs() |
| 187 |
self._load_schema() |
| 188 |
self._base64_attributes = set(self.module.params["base64_attributes"] or []) |
| 189 |
|
| 190 |
def _load_schema(self): |
| 191 |
self.schema = self.module.params["schema"] |
| 192 |
if self.schema: |
| 193 |
self.attrsonly = 1 |
| 194 |
else: |
| 195 |
self.attrsonly = 0 |
| 196 |
|
| 197 |
def _load_scope(self): |
| 198 |
spec = dict( |
| 199 |
base=ldap.SCOPE_BASE, |
| 200 |
onelevel=ldap.SCOPE_ONELEVEL, |
| 201 |
subordinate=ldap.SCOPE_SUBORDINATE, |
| 202 |
children=ldap.SCOPE_SUBTREE, |
| 203 |
) |
| 204 |
self.scope = spec[self.module.params["scope"]] |
| 205 |
|
| 206 |
def _load_attrs(self): |
| 207 |
self.attrlist = self.module.params["attrs"] or None |
| 208 |
|
| 209 |
def main(self): |
| 210 |
results = self.perform_search() |
| 211 |
self.module.exit_json(changed=False, results=results) |
| 212 |
|
| 213 |
def perform_search(self): |
| 214 |
ldap_entries = [] |
| 215 |
controls = [] |
| 216 |
if self.page_size > 0: |
| 217 |
controls.append(ldap.controls.libldap.SimplePagedResultsControl(True, size=self.page_size, cookie="")) |
| 218 |
try: |
| 219 |
while True: |
| 220 |
response = self.connection.search_ext( |
| 221 |
self.dn, |
| 222 |
self.scope, |
| 223 |
filterstr=self.filterstr, |
| 224 |
attrlist=self.attrlist, |
| 225 |
attrsonly=self.attrsonly, |
| 226 |
serverctrls=controls, |
| 227 |
) |
| 228 |
rtype, results, rmsgid, serverctrls = self.connection.result3(response) |
| 229 |
for result in results: |
| 230 |
if isinstance(result[1], dict): |
| 231 |
if self.schema: |
| 232 |
ldap_entries.append(dict(dn=result[0], attrs=list(result[1].keys()))) |
| 233 |
else: |
| 234 |
ldap_entries.append(_extract_entry(result[0], result[1], self._base64_attributes)) |
| 235 |
cookies = [ |
| 236 |
c.cookie |
| 237 |
for c in serverctrls |
| 238 |
if c.controlType == ldap.controls.libldap.SimplePagedResultsControl.controlType |
| 239 |
] |
| 240 |
if self.page_size > 0 and cookies and cookies[0]: |
| 241 |
controls[0].cookie = cookies[0] |
| 242 |
else: |
| 243 |
return ldap_entries |
| 244 |
except ldap.NO_SUCH_OBJECT: |
| 245 |
self.module.fail_json(msg=f"Base not found: {self.dn}") |
| 246 |
|
| 247 |
|
| 248 |
if __name__ == "__main__": |
| 249 |
main() |