forked from ungleich-public/ungleich-user
LDAPSERVER was documented as a space separated list, but the whole string went into a single ldap3.Server. Logins worked (python-ldap accepts lists), while registration and every write would have failed with more than one URI. settings.LDAP_SERVERS is now the split list, used through one ldap3 ServerPool per process: requests go to the first reachable server, a server that is down is skipped for 60s, connections time out after 5s, and with all servers down the pool gives up after two passes instead of retrying forever.
309 lines
11 KiB
Python
309 lines
11 KiB
Python
import base64
|
|
import hashlib
|
|
import random
|
|
|
|
import ldap3
|
|
import ldap3.utils.config
|
|
from django.conf import settings
|
|
from ldap3.utils.conv import escape_filter_chars
|
|
from ldap3.utils.dn import escape_rdn
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
# Seconds to wait for a TCP connection, and to skip a server that failed.
|
|
LDAP_CONNECT_TIMEOUT = 5
|
|
LDAP_OFFLINE_RETRY = 60
|
|
# How many times to cycle through all servers before giving up
|
|
# (ldap3's active=True would retry forever when all are down).
|
|
LDAP_POOL_PASSES = 2
|
|
# Pause between passes (ldap3 defaults to 10s, which stalls requests).
|
|
ldap3.utils.config.set_config_parameter('POOLING_LOOP_TIMEOUT', 1)
|
|
|
|
_pools = {}
|
|
|
|
|
|
def get_server_pool(uris):
|
|
"""
|
|
One ldap3 ServerPool per process (per list of URIs): connections go to
|
|
the first reachable server, and a server that is down is skipped for
|
|
LDAP_OFFLINE_RETRY seconds instead of costing a timeout every request.
|
|
"""
|
|
key = tuple(uris)
|
|
if key not in _pools:
|
|
_pools[key] = ldap3.ServerPool(
|
|
[ldap3.Server(uri, connect_timeout=LDAP_CONNECT_TIMEOUT) for uri in uris],
|
|
ldap3.FIRST, active=LDAP_POOL_PASSES, exhaust=LDAP_OFFLINE_RETRY,
|
|
)
|
|
return _pools[key]
|
|
|
|
|
|
class LdapManager:
|
|
__instance = None
|
|
def __new__(cls):
|
|
if LdapManager.__instance is None:
|
|
LdapManager.__instance = object.__new__(cls)
|
|
return LdapManager.__instance
|
|
|
|
def __init__(self):
|
|
"""
|
|
Initialize the LDAP subsystem.
|
|
"""
|
|
self.rng = random.SystemRandom()
|
|
self.server = get_server_pool(settings.LDAP_SERVERS)
|
|
|
|
|
|
def get_admin_conn(self):
|
|
"""
|
|
Return a bound :class:`ldap3.Connection` instance which has write
|
|
permissions on the dn in which the user accounts reside.
|
|
"""
|
|
conn = self.get_conn(user=settings.LDAP_ADMIN_DN,
|
|
password=settings.LDAP_ADMIN_PASSWORD,
|
|
raise_exceptions=True)
|
|
conn.bind()
|
|
return conn
|
|
|
|
|
|
def get_conn(self, **kwargs):
|
|
"""
|
|
Return an unbound :class:`ldap3.Connection` which talks to the configured
|
|
LDAP server.
|
|
|
|
The *kwargs* are passed to the constructor of :class:`ldap3.Connection` and
|
|
can be used to set *user*, *password* and other useful arguments.
|
|
"""
|
|
conn = ldap3.Connection(self.server, **kwargs)
|
|
if settings.LDAP_USE_TLS:
|
|
conn.open()
|
|
conn.start_tls()
|
|
return conn
|
|
|
|
|
|
def _ssha_password(self, password):
|
|
"""
|
|
Apply the SSHA password hashing scheme to the given *password*.
|
|
*password* must be a :class:`bytes` object, containing the utf-8
|
|
encoded password.
|
|
|
|
Return a :class:`bytes` object containing ``ascii``-compatible data
|
|
which can be used as LDAP value, e.g. after armoring it once more using
|
|
base64 or decoding it to unicode from ``ascii``.
|
|
"""
|
|
SALT_BYTES = 15
|
|
|
|
sha1 = hashlib.sha1()
|
|
salt = self.rng.getrandbits(SALT_BYTES * 8).to_bytes(SALT_BYTES,
|
|
"little")
|
|
sha1.update(password)
|
|
sha1.update(salt)
|
|
|
|
digest = sha1.digest()
|
|
passwd = b"{SSHA}" + base64.b64encode(digest + salt)
|
|
return passwd
|
|
|
|
|
|
def hash_password(self, password):
|
|
"""Return the {SSHA} hash of *password* (str) as an ascii str."""
|
|
return self._ssha_password(password.encode("utf-8")).decode("ascii")
|
|
|
|
def username_taken(self, uid):
|
|
"""True if *uid* exists anywhere in the tree (customers, users, ...)."""
|
|
exists, _ = self.check_user_exists(
|
|
uid=uid, attributes=["uid"],
|
|
search_base=settings.ENTIRE_SEARCH_BASE
|
|
)
|
|
return bool(exists)
|
|
|
|
def create_user(self, user, password_hash, firstname, lastname, email):
|
|
"""Create a customer entry. *password_hash* comes from hash_password()."""
|
|
if self.username_taken(user):
|
|
raise Exception("The username {} is already taken.".format(user))
|
|
uidNumber = self._next_uid_number()
|
|
logger.debug("uidNumber={uidNumber}".format(uidNumber=uidNumber))
|
|
conn = self.get_admin_conn()
|
|
try:
|
|
uid = user # user.encode("utf-8")
|
|
conn.add("uid={uid},{customer_dn}".format(
|
|
uid=escape_rdn(uid), customer_dn=settings.LDAP_CUSTOMER_DN
|
|
),
|
|
["inetOrgPerson", "posixAccount", "ldapPublickey"],
|
|
{
|
|
"uid": [uid],
|
|
"sn": [lastname.encode("utf-8")],
|
|
"givenName": [firstname.encode("utf-8")],
|
|
"cn": [uid],
|
|
"displayName": ["{} {}".format(firstname, lastname).encode("utf-8")],
|
|
"uidNumber": [str(uidNumber)],
|
|
"gidNumber": [str(settings.LDAP_CUSTOMER_GROUP_ID)],
|
|
"loginShell": ["/bin/bash"],
|
|
"homeDirectory": ["/home/{}".format(user).encode("utf-8")],
|
|
"mail": email.encode("utf-8"),
|
|
"userPassword": [password_hash.encode("ascii")]
|
|
}
|
|
)
|
|
logger.debug('Created user %s %s' % (user.encode('utf-8'),
|
|
uidNumber))
|
|
except Exception as ex:
|
|
logger.debug('Could not create user %s' % user.encode('utf-8'))
|
|
logger.error("Exception: " + str(ex))
|
|
raise Exception(ex)
|
|
finally:
|
|
conn.unbind()
|
|
|
|
|
|
def change_password(self, uid, new_password):
|
|
"""
|
|
Changes the password of the user identified by user_dn
|
|
|
|
:param uid: str The uid that identifies the user
|
|
:param new_password: str The new password string
|
|
:return: True if password was changed successfully False otherwise
|
|
"""
|
|
conn = self.get_admin_conn()
|
|
|
|
# Make sure the user exists first to change his/her details
|
|
user_exists, entries = self.check_user_exists(
|
|
uid=uid,
|
|
search_base=settings.ENTIRE_SEARCH_BASE
|
|
)
|
|
return_val = False
|
|
if user_exists:
|
|
try:
|
|
return_val = conn.modify(
|
|
entries[0].entry_dn,
|
|
{
|
|
"userpassword": (
|
|
ldap3.MODIFY_REPLACE,
|
|
[self._ssha_password(new_password.encode("utf-8"))]
|
|
)
|
|
}
|
|
)
|
|
except Exception as ex:
|
|
logger.error("Exception: " + str(ex))
|
|
else:
|
|
logger.error("User {} not found".format(uid))
|
|
|
|
conn.unbind()
|
|
return return_val
|
|
|
|
def change_user_details(self, uid, details):
|
|
"""
|
|
Updates the user details as per given values in kwargs of the user
|
|
identified by user_dn.
|
|
|
|
Assumes that all attributes passed in kwargs are valid.
|
|
|
|
:param uid: str The uid that identifies the user
|
|
:param details: dict A dictionary containing the new values
|
|
:return: True if user details were updated successfully False otherwise
|
|
"""
|
|
conn = self.get_admin_conn()
|
|
|
|
# Make sure the user exists first to change his/her details
|
|
user_exists, entries = self.check_user_exists(
|
|
uid=uid,
|
|
search_base=settings.ENTIRE_SEARCH_BASE
|
|
)
|
|
|
|
return_val = False
|
|
if user_exists:
|
|
details_dict = {k: (ldap3.MODIFY_REPLACE, [v.encode("utf-8")]) for
|
|
k, v in details.items()}
|
|
try:
|
|
return_val = conn.modify(entries[0].entry_dn, details_dict)
|
|
msg = "success"
|
|
except Exception as ex:
|
|
msg = str(ex)
|
|
logger.error("Exception: " + msg)
|
|
finally:
|
|
conn.unbind()
|
|
else:
|
|
msg = "User {} not found".format(uid)
|
|
logger.error(msg)
|
|
conn.unbind()
|
|
return return_val, msg
|
|
|
|
def check_user_exists(self, uid, search_filter="", attributes=None,
|
|
search_base=settings.LDAP_CUSTOMER_DN):
|
|
"""
|
|
Check if the user with the given uid exists in the customer group.
|
|
|
|
:param uid: str representing the user
|
|
:param search_filter: str representing the filter condition to find
|
|
users. If its empty, the search finds the user with
|
|
the given uid.
|
|
:param attributes: list A list of str representing all the attributes
|
|
to be obtained in the result entries
|
|
:param search_base: str
|
|
:return: tuple (bool, [ldap3.abstract.entry.Entry ..])
|
|
A bool indicating if the user exists
|
|
A list of all entries obtained in the search
|
|
"""
|
|
conn = self.get_admin_conn()
|
|
entries = []
|
|
try:
|
|
result = conn.search(
|
|
search_base=search_base,
|
|
search_filter=search_filter if len(search_filter)> 0 else
|
|
'(uid={uid})'.format(uid=escape_filter_chars(uid)),
|
|
attributes=attributes
|
|
)
|
|
entries = conn.entries
|
|
finally:
|
|
conn.unbind()
|
|
return result, entries
|
|
|
|
def delete_user(self, uid):
|
|
"""
|
|
Deletes the user with the given uid from ldap
|
|
|
|
:param uid: str representing the user
|
|
:return: True if the delete was successful False otherwise
|
|
"""
|
|
conn = self.get_admin_conn()
|
|
try:
|
|
return_val = conn.delete(
|
|
("uid={uid}," + settings.LDAP_CUSTOMER_DN).format(uid=escape_rdn(uid)),
|
|
)
|
|
msg = "success"
|
|
except Exception as ex:
|
|
msg = str(ex)
|
|
logger.error("Exception: " + msg)
|
|
return_val = False
|
|
finally:
|
|
conn.unbind()
|
|
return return_val, msg
|
|
|
|
def _next_uid_number(self):
|
|
"""
|
|
Return the next free uidNumber: one above the highest uidNumber in
|
|
the whole tree, and above LDAP_DEFAULT_START_UID.
|
|
|
|
Read from LDAP on every call (paged, so server size limits don't cut
|
|
it short) instead of a local file, so it works with several replicas
|
|
and survives restarts. Two registrations activated at the very same
|
|
moment could still pick the same number.
|
|
"""
|
|
highest = settings.LDAP_DEFAULT_START_UID
|
|
conn = self.get_admin_conn()
|
|
try:
|
|
results = conn.extend.standard.paged_search(
|
|
search_base=settings.ENTIRE_SEARCH_BASE,
|
|
search_filter='(&(objectClass=posixAccount)(uidNumber=*))',
|
|
attributes=['uidNumber'],
|
|
paged_size=500,
|
|
generator=True,
|
|
)
|
|
for result in results:
|
|
if result.get('type') != 'searchResEntry':
|
|
continue
|
|
value = result['attributes'].get('uidNumber')
|
|
if isinstance(value, list):
|
|
value = value[0] if value else None
|
|
if value is not None:
|
|
highest = max(highest, int(value))
|
|
finally:
|
|
conn.unbind()
|
|
return highest + 1
|