| 1 |
#!/usr/bin/env python |
| 2 |
|
| 3 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
|
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
import os |
| 12 |
import copy |
| 13 |
|
| 14 |
from ansible.module_utils.parsing.convert_bool import boolean |
| 15 |
from ansible.module_utils.six import iteritems |
| 16 |
|
| 17 |
try: |
| 18 |
import ldap |
| 19 |
except ImportError as e: |
| 20 |
pass |
| 21 |
|
| 22 |
|
| 23 |
LDAP_SEARCH_OUT_OF_SCOPE_ERROR = "trying to search by DN for an entry that exists outside of the tree specified with the BaseDN for search" |
| 24 |
|
| 25 |
|
| 26 |
def validate_ldap_sync_config(config): |
| 27 |
# Validate url |
| 28 |
url = config.get("url") |
| 29 |
if not url: |
| 30 |
return "url should be non empty attribute." |
| 31 |
|
| 32 |
# Make sure bindDN and bindPassword are both set, or both unset |
| 33 |
bind_dn = config.get("bindDN", "") |
| 34 |
bind_password = config.get("bindPassword", "") |
| 35 |
if (len(bind_dn) == 0) != (len(bind_password) == 0): |
| 36 |
return "bindDN and bindPassword must both be specified, or both be empty." |
| 37 |
|
| 38 |
insecure = boolean(config.get("insecure")) |
| 39 |
ca_file = config.get("ca") |
| 40 |
if insecure: |
| 41 |
if url.startswith("ldaps://"): |
| 42 |
return "Cannot use ldaps scheme with insecure=true." |
| 43 |
if ca_file: |
| 44 |
return "Cannot specify a ca with insecure=true." |
| 45 |
elif ca_file and not os.path.isfile(ca_file): |
| 46 |
return "could not read ca file: {0}.".format(ca_file) |
| 47 |
|
| 48 |
nameMapping = config.get("groupUIDNameMapping", {}) |
| 49 |
for k, v in iteritems(nameMapping): |
| 50 |
if len(k) == 0 or len(v) == 0: |
| 51 |
return "groupUIDNameMapping has empty key or value" |
| 52 |
|
| 53 |
schemas = [] |
| 54 |
schema_list = ("rfc2307", "activeDirectory", "augmentedActiveDirectory") |
| 55 |
for schema in schema_list: |
| 56 |
if schema in config: |
| 57 |
schemas.append(schema) |
| 58 |
|
| 59 |
if len(schemas) == 0: |
| 60 |
return ( |
| 61 |
"No schema-specific config was provided, should be one of %s" |
| 62 |
% ", ".join(schema_list) |
| 63 |
) |
| 64 |
if len(schemas) > 1: |
| 65 |
return "Exactly one schema-specific config is required; found (%d) %s" % ( |
| 66 |
len(schemas), |
| 67 |
",".join(schemas), |
| 68 |
) |
| 69 |
|
| 70 |
if schemas[0] == "rfc2307": |
| 71 |
return validate_RFC2307(config.get("rfc2307")) |
| 72 |
elif schemas[0] == "activeDirectory": |
| 73 |
return validate_ActiveDirectory(config.get("activeDirectory")) |
| 74 |
elif schemas[0] == "augmentedActiveDirectory": |
| 75 |
return validate_AugmentedActiveDirectory(config.get("augmentedActiveDirectory")) |
| 76 |
|
| 77 |
|
| 78 |
def validate_ldap_query(qry, isDNOnly=False): |
| 79 |
# validate query scope |
| 80 |
scope = qry.get("scope") |
| 81 |
if scope and scope not in ("", "sub", "one", "base"): |
| 82 |
return "invalid scope %s" % scope |
| 83 |
|
| 84 |
# validate deref aliases |
| 85 |
derefAlias = qry.get("derefAliases") |
| 86 |
if derefAlias and derefAlias not in ("never", "search", "base", "always"): |
| 87 |
return "not a valid LDAP alias dereferncing behavior: %s", derefAlias |
| 88 |
|
| 89 |
# validate timeout |
| 90 |
timeout = qry.get("timeout") |
| 91 |
if timeout and float(timeout) < 0: |
| 92 |
return "timeout must be equal to or greater than zero" |
| 93 |
|
| 94 |
# Validate DN only |
| 95 |
qry_filter = qry.get("filter", "") |
| 96 |
if isDNOnly: |
| 97 |
if len(qry_filter) > 0: |
| 98 |
return 'cannot specify a filter when using "dn" as the UID attribute' |
| 99 |
else: |
| 100 |
# validate filter |
| 101 |
if len(qry_filter) == 0 or qry_filter[0] != "(": |
| 102 |
return "filter does not start with an '('" |
| 103 |
return None |
| 104 |
|
| 105 |
|
| 106 |
def validate_RFC2307(config): |
| 107 |
qry = config.get("groupsQuery") |
| 108 |
if not qry or not isinstance(qry, dict): |
| 109 |
return "RFC2307: groupsQuery requires a dictionary" |
| 110 |
error = validate_ldap_query(qry) |
| 111 |
if not error: |
| 112 |
return error |
| 113 |
for field in ( |
| 114 |
"groupUIDAttribute", |
| 115 |
"groupNameAttributes", |
| 116 |
"groupMembershipAttributes", |
| 117 |
"userUIDAttribute", |
| 118 |
"userNameAttributes", |
| 119 |
): |
| 120 |
value = config.get(field) |
| 121 |
if not value: |
| 122 |
return "RFC2307: {0} is required.".format(field) |
| 123 |
|
| 124 |
users_qry = config.get("usersQuery") |
| 125 |
if not users_qry or not isinstance(users_qry, dict): |
| 126 |
return "RFC2307: usersQuery requires a dictionary" |
| 127 |
|
| 128 |
isUserDNOnly = config.get("userUIDAttribute").strip() == "dn" |
| 129 |
return validate_ldap_query(users_qry, isDNOnly=isUserDNOnly) |
| 130 |
|
| 131 |
|
| 132 |
def validate_ActiveDirectory(config, label="ActiveDirectory"): |
| 133 |
users_qry = config.get("usersQuery") |
| 134 |
if not users_qry or not isinstance(users_qry, dict): |
| 135 |
return "{0}: usersQuery requires as dictionnary".format(label) |
| 136 |
error = validate_ldap_query(users_qry) |
| 137 |
if not error: |
| 138 |
return error |
| 139 |
|
| 140 |
for field in ("userNameAttributes", "groupMembershipAttributes"): |
| 141 |
value = config.get(field) |
| 142 |
if not value: |
| 143 |
return "{0}: {1} is required.".format(field, label) |
| 144 |
|
| 145 |
return None |
| 146 |
|
| 147 |
|
| 148 |
def validate_AugmentedActiveDirectory(config): |
| 149 |
error = validate_ActiveDirectory(config, label="AugmentedActiveDirectory") |
| 150 |
if not error: |
| 151 |
return error |
| 152 |
for field in ("groupUIDAttribute", "groupNameAttributes"): |
| 153 |
value = config.get(field) |
| 154 |
if not value: |
| 155 |
return "AugmentedActiveDirectory: {0} is required".format(field) |
| 156 |
groups_qry = config.get("groupsQuery") |
| 157 |
if not groups_qry or not isinstance(groups_qry, dict): |
| 158 |
return "AugmentedActiveDirectory: groupsQuery requires as dictionnary." |
| 159 |
|
| 160 |
isGroupDNOnly = config.get("groupUIDAttribute").strip() == "dn" |
| 161 |
return validate_ldap_query(groups_qry, isDNOnly=isGroupDNOnly) |
| 162 |
|
| 163 |
|
| 164 |
def determine_ldap_scope(scope): |
| 165 |
if scope in ("", "sub"): |
| 166 |
return ldap.SCOPE_SUBTREE |
| 167 |
elif scope == "base": |
| 168 |
return ldap.SCOPE_BASE |
| 169 |
elif scope == "one": |
| 170 |
return ldap.SCOPE_ONELEVEL |
| 171 |
return None |
| 172 |
|
| 173 |
|
| 174 |
def determine_deref_aliases(derefAlias): |
| 175 |
mapping = { |
| 176 |
"never": ldap.DEREF_NEVER, |
| 177 |
"search": ldap.DEREF_SEARCHING, |
| 178 |
"base": ldap.DEREF_FINDING, |
| 179 |
"always": ldap.DEREF_ALWAYS, |
| 180 |
} |
| 181 |
result = None |
| 182 |
if derefAlias in mapping: |
| 183 |
result = mapping.get(derefAlias) |
| 184 |
return result |
| 185 |
|
| 186 |
|
| 187 |
def openshift_ldap_build_base_query(config): |
| 188 |
qry = {} |
| 189 |
if config.get("baseDN"): |
| 190 |
qry["base"] = config.get("baseDN") |
| 191 |
|
| 192 |
scope = determine_ldap_scope(config.get("scope")) |
| 193 |
if scope: |
| 194 |
qry["scope"] = scope |
| 195 |
|
| 196 |
pageSize = config.get("pageSize") |
| 197 |
if pageSize and int(pageSize) > 0: |
| 198 |
qry["sizelimit"] = int(pageSize) |
| 199 |
|
| 200 |
timeout = config.get("timeout") |
| 201 |
if timeout and int(timeout) > 0: |
| 202 |
qry["timeout"] = int(timeout) |
| 203 |
|
| 204 |
filter = config.get("filter") |
| 205 |
if filter: |
| 206 |
qry["filterstr"] = filter |
| 207 |
|
| 208 |
derefAlias = determine_deref_aliases(config.get("derefAliases")) |
| 209 |
if derefAlias: |
| 210 |
qry["derefAlias"] = derefAlias |
| 211 |
return qry |
| 212 |
|
| 213 |
|
| 214 |
def openshift_ldap_get_attribute_for_entry(entry, attribute): |
| 215 |
attributes = [attribute] |
| 216 |
if isinstance(attribute, list): |
| 217 |
attributes = attribute |
| 218 |
for k in attributes: |
| 219 |
if k.lower() == "dn": |
| 220 |
return entry[0] |
| 221 |
v = entry[1].get(k, None) |
| 222 |
if v: |
| 223 |
if isinstance(v, list): |
| 224 |
result = [] |
| 225 |
for x in v: |
| 226 |
if hasattr(x, "decode"): |
| 227 |
result.append(x.decode("utf-8")) |
| 228 |
else: |
| 229 |
result.append(x) |
| 230 |
return result |
| 231 |
else: |
| 232 |
return v.decode("utf-8") if hasattr(v, "decode") else v |
| 233 |
return "" |
| 234 |
|
| 235 |
|
| 236 |
def ldap_split_host_port(hostport): |
| 237 |
""" |
| 238 |
ldap_split_host_port splits a network address of the form "host:port", |
| 239 |
"host%zone:port", "[host]:port" or "[host%zone]:port" into host or |
| 240 |
host%zone and port. |
| 241 |
""" |
| 242 |
result = dict(scheme=None, netlocation=None, host=None, port=None) |
| 243 |
if not hostport: |
| 244 |
return result, None |
| 245 |
|
| 246 |
# Extract Scheme |
| 247 |
netlocation = hostport |
| 248 |
scheme_l = "://" |
| 249 |
if "://" in hostport: |
| 250 |
idx = hostport.find(scheme_l) |
| 251 |
result["scheme"] = hostport[:idx] |
| 252 |
netlocation = hostport[idx + len(scheme_l):] # fmt: skip |
| 253 |
result["netlocation"] = netlocation |
| 254 |
|
| 255 |
if netlocation[-1] == "]": |
| 256 |
# ipv6 literal (with no port) |
| 257 |
result["host"] = netlocation |
| 258 |
|
| 259 |
v = netlocation.rsplit(":", 1) |
| 260 |
if len(v) != 1: |
| 261 |
try: |
| 262 |
result["port"] = int(v[1]) |
| 263 |
except ValueError: |
| 264 |
return None, "Invalid value specified for port: %s" % v[1] |
| 265 |
result["host"] = v[0] |
| 266 |
return result, None |
| 267 |
|
| 268 |
|
| 269 |
def openshift_ldap_query_for_entries(connection, qry, unique_entry=True): |
| 270 |
# set deref alias (TODO: need to set a default value to reset for each transaction) |
| 271 |
derefAlias = qry.pop("derefAlias", None) |
| 272 |
if derefAlias: |
| 273 |
ldap.set_option(ldap.OPT_DEREF, derefAlias) |
| 274 |
try: |
| 275 |
result = connection.search_ext_s(**qry) |
| 276 |
if not result or len(result) == 0: |
| 277 |
return None, "Entry not found for base='{0}' and filter='{1}'".format( |
| 278 |
qry["base"], qry["filterstr"] |
| 279 |
) |
| 280 |
if len(result) > 1 and unique_entry: |
| 281 |
if qry.get("scope") == ldap.SCOPE_BASE: |
| 282 |
return None, "multiple entries found matching dn={0}: {1}".format( |
| 283 |
qry["base"], result |
| 284 |
) |
| 285 |
else: |
| 286 |
return None, "multiple entries found matching filter {0}: {1}".format( |
| 287 |
qry["filterstr"], result |
| 288 |
) |
| 289 |
return result, None |
| 290 |
except ldap.NO_SUCH_OBJECT: |
| 291 |
return ( |
| 292 |
None, |
| 293 |
"search for entry with base dn='{0}' refers to a non-existent entry".format( |
| 294 |
qry["base"] |
| 295 |
), |
| 296 |
) |
| 297 |
|
| 298 |
|
| 299 |
def openshift_equal_dn_objects(dn_obj, other_dn_obj): |
| 300 |
if len(dn_obj) != len(other_dn_obj): |
| 301 |
return False |
| 302 |
|
| 303 |
for k, v in enumerate(dn_obj): |
| 304 |
if len(v) != len(other_dn_obj[k]): |
| 305 |
return False |
| 306 |
for j, item in enumerate(v): |
| 307 |
if not (item == other_dn_obj[k][j]): |
| 308 |
return False |
| 309 |
return True |
| 310 |
|
| 311 |
|
| 312 |
def openshift_equal_dn(dn, other): |
| 313 |
dn_obj = ldap.dn.str2dn(dn) |
| 314 |
other_dn_obj = ldap.dn.str2dn(other) |
| 315 |
|
| 316 |
return openshift_equal_dn_objects(dn_obj, other_dn_obj) |
| 317 |
|
| 318 |
|
| 319 |
def openshift_ancestorof_dn(dn, other): |
| 320 |
dn_obj = ldap.dn.str2dn(dn) |
| 321 |
other_dn_obj = ldap.dn.str2dn(other) |
| 322 |
|
| 323 |
if len(dn_obj) >= len(other_dn_obj): |
| 324 |
return False |
| 325 |
# Take the last attribute from the other DN to compare against |
| 326 |
return openshift_equal_dn_objects( |
| 327 |
dn_obj, other_dn_obj[len(other_dn_obj) - len(dn_obj):] # fmt: skip |
| 328 |
) |
| 329 |
|
| 330 |
|
| 331 |
class OpenshiftLDAPQueryOnAttribute(object): |
| 332 |
def __init__(self, qry, attribute): |
| 333 |
# qry retrieves entries from an LDAP server |
| 334 |
self.qry = copy.deepcopy(qry) |
| 335 |
# query_attributes is the attribute for a specific filter that, when conjoined with the common filter, |
| 336 |
# retrieves the specific LDAP entry from the LDAP server. (e.g. "cn", when formatted with "aGroupName" |
| 337 |
# and conjoined with "objectClass=groupOfNames", becomes (&(objectClass=groupOfNames)(cn=aGroupName))") |
| 338 |
self.query_attribute = attribute |
| 339 |
|
| 340 |
@staticmethod |
| 341 |
def escape_filter(buffer): |
| 342 |
""" |
| 343 |
escapes from the provided LDAP filter string the special |
| 344 |
characters in the set '(', ')', '*', \\ and those out of the range 0 < c < 0x80, as defined in RFC4515. |
| 345 |
""" |
| 346 |
output = [] |
| 347 |
hex_string = "0123456789abcdef" |
| 348 |
for c in buffer: |
| 349 |
if ord(c) > 0x7F or c in ("(", ")", "\\", "*") or c == 0: |
| 350 |
first = ord(c) >> 4 |
| 351 |
second = ord(c) & 0xF |
| 352 |
output += ["\\", hex_string[first], hex_string[second]] |
| 353 |
else: |
| 354 |
output.append(c) |
| 355 |
return "".join(output) |
| 356 |
|
| 357 |
def build_request(self, ldapuid, attributes): |
| 358 |
params = copy.deepcopy(self.qry) |
| 359 |
if self.query_attribute.lower() == "dn": |
| 360 |
if ldapuid: |
| 361 |
if not openshift_equal_dn( |
| 362 |
ldapuid, params["base"] |
| 363 |
) and not openshift_ancestorof_dn(params["base"], ldapuid): |
| 364 |
return None, LDAP_SEARCH_OUT_OF_SCOPE_ERROR |
| 365 |
params["base"] = ldapuid |
| 366 |
params["scope"] = ldap.SCOPE_BASE |
| 367 |
# filter that returns all values |
| 368 |
params["filterstr"] = "(objectClass=*)" |
| 369 |
params["attrlist"] = attributes |
| 370 |
else: |
| 371 |
# Builds the query containing a filter that conjoins the common filter given |
| 372 |
# in the configuration with the specific attribute filter for which the attribute value is given |
| 373 |
specificFilter = "%s=%s" % ( |
| 374 |
self.escape_filter(self.query_attribute), |
| 375 |
self.escape_filter(ldapuid), |
| 376 |
) |
| 377 |
qry_filter = params.get("filterstr", None) |
| 378 |
if qry_filter: |
| 379 |
params["filterstr"] = "(&%s(%s))" % (qry_filter, specificFilter) |
| 380 |
params["attrlist"] = attributes |
| 381 |
return params, None |
| 382 |
|
| 383 |
def ldap_search(self, connection, ldapuid, required_attributes, unique_entry=True): |
| 384 |
query, error = self.build_request(ldapuid, required_attributes) |
| 385 |
if error: |
| 386 |
return None, error |
| 387 |
# set deref alias (TODO: need to set a default value to reset for each transaction) |
| 388 |
derefAlias = query.pop("derefAlias", None) |
| 389 |
if derefAlias: |
| 390 |
ldap.set_option(ldap.OPT_DEREF, derefAlias) |
| 391 |
|
| 392 |
try: |
| 393 |
result = connection.search_ext_s(**query) |
| 394 |
if not result or len(result) == 0: |
| 395 |
return None, "Entry not found for base='{0}' and filter='{1}'".format( |
| 396 |
query["base"], query["filterstr"] |
| 397 |
) |
| 398 |
if unique_entry: |
| 399 |
if len(result) > 1: |
| 400 |
return ( |
| 401 |
None, |
| 402 |
"Multiple Entries found matching search criteria: %s (%s)" |
| 403 |
% (query, result), |
| 404 |
) |
| 405 |
result = result[0] |
| 406 |
return result, None |
| 407 |
except ldap.NO_SUCH_OBJECT: |
| 408 |
return None, "Entry not found for base='{0}' and filter='{1}'".format( |
| 409 |
query["base"], query["filterstr"] |
| 410 |
) |
| 411 |
except Exception as err: |
| 412 |
return None, "Request %s failed due to: %s" % (query, err) |
| 413 |
|
| 414 |
|
| 415 |
class OpenshiftLDAPQuery(object): |
| 416 |
def __init__(self, qry): |
| 417 |
# Query retrieves entries from an LDAP server |
| 418 |
self.qry = qry |
| 419 |
|
| 420 |
def build_request(self, attributes): |
| 421 |
params = copy.deepcopy(self.qry) |
| 422 |
params["attrlist"] = attributes |
| 423 |
return params |
| 424 |
|
| 425 |
def ldap_search(self, connection, required_attributes): |
| 426 |
query = self.build_request(required_attributes) |
| 427 |
# set deref alias (TODO: need to set a default value to reset for each transaction) |
| 428 |
derefAlias = query.pop("derefAlias", None) |
| 429 |
if derefAlias: |
| 430 |
ldap.set_option(ldap.OPT_DEREF, derefAlias) |
| 431 |
|
| 432 |
try: |
| 433 |
result = connection.search_ext_s(**query) |
| 434 |
if not result or len(result) == 0: |
| 435 |
return None, "Entry not found for base='{0}' and filter='{1}'".format( |
| 436 |
query["base"], query["filterstr"] |
| 437 |
) |
| 438 |
return result, None |
| 439 |
except ldap.NO_SUCH_OBJECT: |
| 440 |
return ( |
| 441 |
None, |
| 442 |
"search for entry with base dn='{0}' refers to a non-existent entry".format( |
| 443 |
query["base"] |
| 444 |
), |
| 445 |
) |
| 446 |
|
| 447 |
|
| 448 |
class OpenshiftLDAPInterface(object): |
| 449 |
def __init__( |
| 450 |
self, |
| 451 |
connection, |
| 452 |
groupQuery, |
| 453 |
groupNameAttributes, |
| 454 |
groupMembershipAttributes, |
| 455 |
userQuery, |
| 456 |
userNameAttributes, |
| 457 |
config, |
| 458 |
): |
| 459 |
self.connection = connection |
| 460 |
self.groupQuery = copy.deepcopy(groupQuery) |
| 461 |
self.groupNameAttributes = groupNameAttributes |
| 462 |
self.groupMembershipAttributes = groupMembershipAttributes |
| 463 |
self.userQuery = copy.deepcopy(userQuery) |
| 464 |
self.userNameAttributes = userNameAttributes |
| 465 |
self.config = config |
| 466 |
|
| 467 |
self.tolerate_not_found = boolean( |
| 468 |
config.get("tolerateMemberNotFoundErrors", False) |
| 469 |
) |
| 470 |
self.tolerate_out_of_scope = boolean( |
| 471 |
config.get("tolerateMemberOutOfScopeErrors", False) |
| 472 |
) |
| 473 |
|
| 474 |
self.required_group_attributes = [self.groupQuery.query_attribute] |
| 475 |
for x in self.groupNameAttributes + self.groupMembershipAttributes: |
| 476 |
if x not in self.required_group_attributes: |
| 477 |
self.required_group_attributes.append(x) |
| 478 |
|
| 479 |
self.required_user_attributes = [self.userQuery.query_attribute] |
| 480 |
for x in self.userNameAttributes: |
| 481 |
if x not in self.required_user_attributes: |
| 482 |
self.required_user_attributes.append(x) |
| 483 |
|
| 484 |
self.cached_groups = {} |
| 485 |
self.cached_users = {} |
| 486 |
|
| 487 |
def get_group_entry(self, uid): |
| 488 |
""" |
| 489 |
get_group_entry returns an LDAP group entry for the given group UID by searching the internal cache |
| 490 |
of the LDAPInterface first, then sending an LDAP query if the cache did not contain the entry. |
| 491 |
""" |
| 492 |
if uid in self.cached_groups: |
| 493 |
return self.cached_groups.get(uid), None |
| 494 |
|
| 495 |
group, err = self.groupQuery.ldap_search( |
| 496 |
self.connection, uid, self.required_group_attributes |
| 497 |
) |
| 498 |
if err: |
| 499 |
return None, err |
| 500 |
self.cached_groups[uid] = group |
| 501 |
return group, None |
| 502 |
|
| 503 |
def get_user_entry(self, uid): |
| 504 |
""" |
| 505 |
get_user_entry returns an LDAP group entry for the given user UID by searching the internal cache |
| 506 |
of the LDAPInterface first, then sending an LDAP query if the cache did not contain the entry. |
| 507 |
""" |
| 508 |
if uid in self.cached_users: |
| 509 |
return self.cached_users.get(uid), None |
| 510 |
|
| 511 |
entry, err = self.userQuery.ldap_search( |
| 512 |
self.connection, uid, self.required_user_attributes |
| 513 |
) |
| 514 |
if err: |
| 515 |
return None, err |
| 516 |
self.cached_users[uid] = entry |
| 517 |
return entry, None |
| 518 |
|
| 519 |
def exists(self, ldapuid): |
| 520 |
group, error = self.get_group_entry(ldapuid) |
| 521 |
return bool(group), error |
| 522 |
|
| 523 |
def list_groups(self): |
| 524 |
group_qry = copy.deepcopy(self.groupQuery.qry) |
| 525 |
group_qry["attrlist"] = self.required_group_attributes |
| 526 |
|
| 527 |
groups, err = openshift_ldap_query_for_entries( |
| 528 |
connection=self.connection, qry=group_qry, unique_entry=False |
| 529 |
) |
| 530 |
if err: |
| 531 |
return None, err |
| 532 |
|
| 533 |
group_uids = [] |
| 534 |
for entry in groups: |
| 535 |
uid = openshift_ldap_get_attribute_for_entry( |
| 536 |
entry, self.groupQuery.query_attribute |
| 537 |
) |
| 538 |
if not uid: |
| 539 |
return None, "Unable to find LDAP group uid for entry %s" % entry |
| 540 |
self.cached_groups[uid] = entry |
| 541 |
group_uids.append(uid) |
| 542 |
return group_uids, None |
| 543 |
|
| 544 |
def extract_members(self, uid): |
| 545 |
""" |
| 546 |
returns the LDAP member entries for a group specified with a ldapGroupUID |
| 547 |
""" |
| 548 |
# Get group entry from LDAP |
| 549 |
group, err = self.get_group_entry(uid) |
| 550 |
if err: |
| 551 |
return None, err |
| 552 |
|
| 553 |
# Extract member UIDs from group entry |
| 554 |
member_uids = [] |
| 555 |
for attribute in self.groupMembershipAttributes: |
| 556 |
member_uids += openshift_ldap_get_attribute_for_entry(group, attribute) |
| 557 |
|
| 558 |
members = [] |
| 559 |
for user_uid in member_uids: |
| 560 |
entry, err = self.get_user_entry(user_uid) |
| 561 |
if err: |
| 562 |
if self.tolerate_not_found and err.startswith("Entry not found"): |
| 563 |
continue |
| 564 |
elif err == LDAP_SEARCH_OUT_OF_SCOPE_ERROR: |
| 565 |
continue |
| 566 |
return None, err |
| 567 |
members.append(entry) |
| 568 |
|
| 569 |
return members, None |
| 570 |
|
| 571 |
|
| 572 |
class OpenshiftLDAPRFC2307(object): |
| 573 |
def __init__(self, config, ldap_connection): |
| 574 |
self.config = config |
| 575 |
self.ldap_interface = self.create_ldap_interface(ldap_connection) |
| 576 |
|
| 577 |
def create_ldap_interface(self, connection): |
| 578 |
segment = self.config.get("rfc2307") |
| 579 |
groups_base_qry = openshift_ldap_build_base_query(segment["groupsQuery"]) |
| 580 |
users_base_qry = openshift_ldap_build_base_query(segment["usersQuery"]) |
| 581 |
|
| 582 |
groups_query = OpenshiftLDAPQueryOnAttribute( |
| 583 |
groups_base_qry, segment["groupUIDAttribute"] |
| 584 |
) |
| 585 |
users_query = OpenshiftLDAPQueryOnAttribute( |
| 586 |
users_base_qry, segment["userUIDAttribute"] |
| 587 |
) |
| 588 |
|
| 589 |
params = dict( |
| 590 |
connection=connection, |
| 591 |
groupQuery=groups_query, |
| 592 |
groupNameAttributes=segment["groupNameAttributes"], |
| 593 |
groupMembershipAttributes=segment["groupMembershipAttributes"], |
| 594 |
userQuery=users_query, |
| 595 |
userNameAttributes=segment["userNameAttributes"], |
| 596 |
config=segment, |
| 597 |
) |
| 598 |
return OpenshiftLDAPInterface(**params) |
| 599 |
|
| 600 |
def get_username_for_entry(self, entry): |
| 601 |
username = openshift_ldap_get_attribute_for_entry( |
| 602 |
entry, self.ldap_interface.userNameAttributes |
| 603 |
) |
| 604 |
if not username: |
| 605 |
return ( |
| 606 |
None, |
| 607 |
"The user entry (%s) does not map to a OpenShift User name with the given mapping" |
| 608 |
% entry, |
| 609 |
) |
| 610 |
return username, None |
| 611 |
|
| 612 |
def get_group_name_for_uid(self, uid): |
| 613 |
# Get name from User defined mapping |
| 614 |
groupuid_name_mapping = self.config.get("groupUIDNameMapping") |
| 615 |
if groupuid_name_mapping and uid in groupuid_name_mapping: |
| 616 |
return groupuid_name_mapping.get(uid), None |
| 617 |
elif self.ldap_interface.groupNameAttributes: |
| 618 |
group, err = self.ldap_interface.get_group_entry(uid) |
| 619 |
if err: |
| 620 |
return None, err |
| 621 |
group_name = openshift_ldap_get_attribute_for_entry( |
| 622 |
group, self.ldap_interface.groupNameAttributes |
| 623 |
) |
| 624 |
if not group_name: |
| 625 |
error = ( |
| 626 |
"The group entry (%s) does not map to an OpenShift Group name with the given name attribute (%s)" |
| 627 |
% (group, self.ldap_interface.groupNameAttributes) |
| 628 |
) |
| 629 |
return None, error |
| 630 |
if isinstance(group_name, list): |
| 631 |
group_name = group_name[0] |
| 632 |
return group_name, None |
| 633 |
else: |
| 634 |
return None, "No OpenShift Group name defined for LDAP group UID: %s" % uid |
| 635 |
|
| 636 |
def is_ldapgroup_exists(self, uid): |
| 637 |
group, err = self.ldap_interface.get_group_entry(uid) |
| 638 |
if err: |
| 639 |
if ( |
| 640 |
err == LDAP_SEARCH_OUT_OF_SCOPE_ERROR |
| 641 |
or err.startswith("Entry not found") |
| 642 |
or "non-existent entry" in err |
| 643 |
): |
| 644 |
return False, None |
| 645 |
return False, err |
| 646 |
if group: |
| 647 |
return True, None |
| 648 |
return False, None |
| 649 |
|
| 650 |
def list_groups(self): |
| 651 |
return self.ldap_interface.list_groups() |
| 652 |
|
| 653 |
def extract_members(self, uid): |
| 654 |
return self.ldap_interface.extract_members(uid) |
| 655 |
|
| 656 |
|
| 657 |
class OpenshiftLDAP_ADInterface(object): |
| 658 |
def __init__(self, connection, user_query, group_member_attr, user_name_attr): |
| 659 |
self.connection = connection |
| 660 |
self.userQuery = user_query |
| 661 |
self.groupMembershipAttributes = group_member_attr |
| 662 |
self.userNameAttributes = user_name_attr |
| 663 |
|
| 664 |
self.required_user_attributes = self.userNameAttributes or [] |
| 665 |
for attr in self.groupMembershipAttributes: |
| 666 |
if attr not in self.required_user_attributes: |
| 667 |
self.required_user_attributes.append(attr) |
| 668 |
|
| 669 |
self.cache = {} |
| 670 |
self.cache_populated = False |
| 671 |
|
| 672 |
def is_entry_present(self, cache_item, entry): |
| 673 |
for item in cache_item: |
| 674 |
if item[0] == entry[0]: |
| 675 |
return True |
| 676 |
return False |
| 677 |
|
| 678 |
def populate_cache(self): |
| 679 |
if not self.cache_populated: |
| 680 |
self.cache_populated = True |
| 681 |
entries, err = self.userQuery.ldap_search( |
| 682 |
self.connection, self.required_user_attributes |
| 683 |
) |
| 684 |
if err: |
| 685 |
return err |
| 686 |
|
| 687 |
for entry in entries: |
| 688 |
for group_attr in self.groupMembershipAttributes: |
| 689 |
uids = openshift_ldap_get_attribute_for_entry(entry, group_attr) |
| 690 |
if not isinstance(uids, list): |
| 691 |
uids = [uids] |
| 692 |
for uid in uids: |
| 693 |
if uid not in self.cache: |
| 694 |
self.cache[uid] = [] |
| 695 |
if not self.is_entry_present(self.cache[uid], entry): |
| 696 |
self.cache[uid].append(entry) |
| 697 |
return None |
| 698 |
|
| 699 |
def list_groups(self): |
| 700 |
err = self.populate_cache() |
| 701 |
if err: |
| 702 |
return None, err |
| 703 |
result = [] |
| 704 |
if self.cache: |
| 705 |
result = self.cache.keys() |
| 706 |
return result, None |
| 707 |
|
| 708 |
def extract_members(self, uid): |
| 709 |
# ExtractMembers returns the LDAP member entries for a group specified with a ldapGroupUID |
| 710 |
# if we already have it cached, return the cached value |
| 711 |
if uid in self.cache: |
| 712 |
return self.cache[uid], None |
| 713 |
|
| 714 |
# This happens in cases where we did not list out every group. |
| 715 |
# In that case, we're going to be asked about specific groups. |
| 716 |
users_in_group = [] |
| 717 |
for attr in self.groupMembershipAttributes: |
| 718 |
query_on_attribute = OpenshiftLDAPQueryOnAttribute(self.userQuery.qry, attr) |
| 719 |
entries, error = query_on_attribute.ldap_search( |
| 720 |
self.connection, uid, self.required_user_attributes, unique_entry=False |
| 721 |
) |
| 722 |
if error and "not found" not in error: |
| 723 |
return None, error |
| 724 |
if not entries: |
| 725 |
continue |
| 726 |
|
| 727 |
for entry in entries: |
| 728 |
if not self.is_entry_present(users_in_group, entry): |
| 729 |
users_in_group.append(entry) |
| 730 |
|
| 731 |
self.cache[uid] = users_in_group |
| 732 |
return users_in_group, None |
| 733 |
|
| 734 |
|
| 735 |
class OpenshiftLDAPActiveDirectory(object): |
| 736 |
def __init__(self, config, ldap_connection): |
| 737 |
self.config = config |
| 738 |
self.ldap_interface = self.create_ldap_interface(ldap_connection) |
| 739 |
|
| 740 |
def create_ldap_interface(self, connection): |
| 741 |
segment = self.config.get("activeDirectory") |
| 742 |
base_query = openshift_ldap_build_base_query(segment["usersQuery"]) |
| 743 |
user_query = OpenshiftLDAPQuery(base_query) |
| 744 |
|
| 745 |
return OpenshiftLDAP_ADInterface( |
| 746 |
connection=connection, |
| 747 |
user_query=user_query, |
| 748 |
group_member_attr=segment["groupMembershipAttributes"], |
| 749 |
user_name_attr=segment["userNameAttributes"], |
| 750 |
) |
| 751 |
|
| 752 |
def get_username_for_entry(self, entry): |
| 753 |
username = openshift_ldap_get_attribute_for_entry( |
| 754 |
entry, self.ldap_interface.userNameAttributes |
| 755 |
) |
| 756 |
if not username: |
| 757 |
return ( |
| 758 |
None, |
| 759 |
"The user entry (%s) does not map to a OpenShift User name with the given mapping" |
| 760 |
% entry, |
| 761 |
) |
| 762 |
return username, None |
| 763 |
|
| 764 |
def get_group_name_for_uid(self, uid): |
| 765 |
return uid, None |
| 766 |
|
| 767 |
def is_ldapgroup_exists(self, uid): |
| 768 |
members, error = self.extract_members(uid) |
| 769 |
if error: |
| 770 |
return False, error |
| 771 |
exists = members and len(members) > 0 |
| 772 |
return exists, None |
| 773 |
|
| 774 |
def list_groups(self): |
| 775 |
return self.ldap_interface.list_groups() |
| 776 |
|
| 777 |
def extract_members(self, uid): |
| 778 |
return self.ldap_interface.extract_members(uid) |
| 779 |
|
| 780 |
|
| 781 |
class OpenshiftLDAP_AugmentedADInterface(OpenshiftLDAP_ADInterface): |
| 782 |
def __init__( |
| 783 |
self, |
| 784 |
connection, |
| 785 |
user_query, |
| 786 |
group_member_attr, |
| 787 |
user_name_attr, |
| 788 |
group_qry, |
| 789 |
group_name_attr, |
| 790 |
): |
| 791 |
super(OpenshiftLDAP_AugmentedADInterface, self).__init__( |
| 792 |
connection, user_query, group_member_attr, user_name_attr |
| 793 |
) |
| 794 |
self.groupQuery = copy.deepcopy(group_qry) |
| 795 |
self.groupNameAttributes = group_name_attr |
| 796 |
|
| 797 |
self.required_group_attributes = [self.groupQuery.query_attribute] |
| 798 |
for x in self.groupNameAttributes: |
| 799 |
if x not in self.required_group_attributes: |
| 800 |
self.required_group_attributes.append(x) |
| 801 |
|
| 802 |
self.cached_groups = {} |
| 803 |
|
| 804 |
def get_group_entry(self, uid): |
| 805 |
""" |
| 806 |
get_group_entry returns an LDAP group entry for the given group UID by searching the internal cache |
| 807 |
of the LDAPInterface first, then sending an LDAP query if the cache did not contain the entry. |
| 808 |
""" |
| 809 |
if uid in self.cached_groups: |
| 810 |
return self.cached_groups.get(uid), None |
| 811 |
|
| 812 |
group, err = self.groupQuery.ldap_search( |
| 813 |
self.connection, uid, self.required_group_attributes |
| 814 |
) |
| 815 |
if err: |
| 816 |
return None, err |
| 817 |
self.cached_groups[uid] = group |
| 818 |
return group, None |
| 819 |
|
| 820 |
def exists(self, ldapuid): |
| 821 |
# Get group members |
| 822 |
members, error = self.extract_members(ldapuid) |
| 823 |
if error: |
| 824 |
return False, error |
| 825 |
group_exists = bool(members) |
| 826 |
|
| 827 |
# Check group Existence |
| 828 |
entry, error = self.get_group_entry(ldapuid) |
| 829 |
if error: |
| 830 |
if "not found" in error: |
| 831 |
return False, None |
| 832 |
else: |
| 833 |
return False, error |
| 834 |
else: |
| 835 |
return group_exists and bool(entry), None |
| 836 |
|
| 837 |
|
| 838 |
class OpenshiftLDAPAugmentedActiveDirectory(OpenshiftLDAPRFC2307): |
| 839 |
def __init__(self, config, ldap_connection): |
| 840 |
self.config = config |
| 841 |
self.ldap_interface = self.create_ldap_interface(ldap_connection) |
| 842 |
|
| 843 |
def create_ldap_interface(self, connection): |
| 844 |
segment = self.config.get("augmentedActiveDirectory") |
| 845 |
user_base_query = openshift_ldap_build_base_query(segment["usersQuery"]) |
| 846 |
groups_base_qry = openshift_ldap_build_base_query(segment["groupsQuery"]) |
| 847 |
|
| 848 |
user_query = OpenshiftLDAPQuery(user_base_query) |
| 849 |
groups_query = OpenshiftLDAPQueryOnAttribute( |
| 850 |
groups_base_qry, segment["groupUIDAttribute"] |
| 851 |
) |
| 852 |
|
| 853 |
return OpenshiftLDAP_AugmentedADInterface( |
| 854 |
connection=connection, |
| 855 |
user_query=user_query, |
| 856 |
group_member_attr=segment["groupMembershipAttributes"], |
| 857 |
user_name_attr=segment["userNameAttributes"], |
| 858 |
group_qry=groups_query, |
| 859 |
group_name_attr=segment["groupNameAttributes"], |
| 860 |
) |
| 861 |
|
| 862 |
def is_ldapgroup_exists(self, uid): |
| 863 |
return self.ldap_interface.exists(uid) |