blob: d12f0085e6ee993efc42c4d59b65a4b0c31dbc4f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# python3 library
# Startdate: 2021-06-21
# Dependencies:
# req-devuan: python3-ldap3
# reference: https://github.com/ArtemAngelchev/flask-basicauth-ldap/blob/master/flask_basicauth_ldap.py
import ldap3
from ldap3.core.exceptions import LDAPBindError, LDAPPasswordIsMandatoryError
def authenticated_user(server_uri, user_format, username, password):
user = user_format.replace("%s",username)
print(f"server_uri: {server_uri}")
print(f"username: {username}")
print(f"user_format: {user_format}")
print(f"user: {user}")
try:
server = ldap3.Server(server_uri)
conn = ldap3.Connection(server, auto_bind=True, user=user, password=password)
return conn
except LDAPBindError as e:
if 'invalidCredentials' in str(e):
print("Invalid credentials.")
return False
else:
raise e
#except (LDAPPasswordIsMandatoryError, LDAPBindError):
# print("Either an ldap password is required, or we had another bind error.")
# return False
return False
def list_ldap_servers_for_domain(domain):
# return list of hostnames from the _ldap._tcp.{domain} SRV lookup
try:
import dns
import dns.resolver
except:
print("Need python3-dns installed for dns lookups.")
return [domain]
namelist = []
try:
query = dns.resolver.query(f"_ldap._tcp.{domain}","SRV")
except dns.resolver.NXDOMAIN:
# no records exist that match the request, so we were probably given a specific hostname, and an empty query will trigger the logic below that will add the original domain to the list.
query = []
for i in query:
namelist.append(i.target.to_text().rstrip("."))
if not len(namelist):
namelist.append(domain)
return namelist
|