Debian Codegraph @

ansible_collections/microsoft/ad/plugins/plugin_utils/_ldap/_lookup.py

raw
1 # Copyright: (c) 2023, Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # FOR INTERNAL COLLECTION USE ONLY
5 # The interfaces in this file are meant for use within this collection
6 # and may not remain stable to outside uses. Changes may be made in ANY release, even a bugfix release.
7 # See also: https://github.com/ansible/community/issues/539#issuecomment-780839686
8 # Please open an issue if you have questions about this.
9
10 import typing as t
11
12 # dnspython is used for dynamic server lookups
13 try:
14 import dns.resolver
15
16 HAS_DNSPYTHON = True
17 except Exception:
18 HAS_DNSPYTHON = False
19
20
21 # krb5 is used to retrieve the default realm for dynamic server lookups.
22 try:
23 import krb5
24
25 HAS_KRB5 = True
26 except Exception:
27 HAS_KRB5 = False
28
29
30 class SrvRecord(t.NamedTuple):
31 target: str
32 port: int
33 weight: int
34 priority: int
35
36 @classmethod
37 def lookup(
38 cls,
39 service: str,
40 proto: str,
41 name: str,
42 ) -> t.List["SrvRecord"]:
43 """Performs an SRV lookup.
44
45 Args:
46 service: The SRV service.
47 proto: The SRV protocol.
48 name: The SRV name.
49
50 Returns:
51 List[SrvRecord]: A list of records ordered by priority and weight.
52 """
53 record = f"_{service}._{proto}.{name}"
54
55 answers: t.List[SrvRecord] = []
56 for answer in dns.resolver.resolve(record, "SRV"):
57 answers.append(
58 SrvRecord(
59 target=str(answer.target),
60 port=answer.port,
61 weight=answer.weight,
62 priority=answer.priority,
63 )
64 )
65
66 # Sorts the array by lowest priority then highest weight.
67 return sorted(answers, key=lambda a: (a.priority, -a.weight))
68
69
70 def lookup_ldap_server() -> t.Tuple[str, int]:
71 """Attempts to lookup LDAP server.
72
73 Attempts to lookup LDAP server based on the current Kerberos host
74 configuration. Will them perform an SRV lookup for
75 '_ldap._tcp.dc._msdcs.{realm}' to get the LDAP server hostname nad port.
76
77 Returns:
78 Tuple[str, int]: The LDAP hostname and port.
79
80 Raises:
81 ImportError: Missing krb5 or dnspython.
82 krb5.Krb5Error: Kerberos configuration problem
83 dns.exception.DNSException: DNS lookup error.
84 """
85 required_libs = [(HAS_KRB5, "krb5"), (HAS_DNSPYTHON, "dnspython")]
86 missing_libs = [lib for present, lib in required_libs if not present]
87 if missing_libs:
88 raise ImportError(f"Cannot lookup server without the python libraries {', '.join(missing_libs)}")
89
90 ctx = krb5.init_context()
91 default_realm = krb5.get_default_realm(ctx).decode("utf-8")
92 answer = SrvRecord.lookup("ldap", "tcp", f"dc._msdcs.{default_realm}")[0]
93 return answer.target, answer.port