| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338 |
- from __future__ import annotations
- from typing import Any
- from flask_babel import gettext as _
- from ldap3 import (
- ALL,
- NTLM,
- SIMPLE,
- SUBTREE,
- Connection,
- Server,
- Tls,
- core,
- )
- from ldap3.utils.conv import escape_filter_chars
- from loguru import logger
- # ---------------------------------------------------------------------------
- # Internal helpers
- # ---------------------------------------------------------------------------
- def _make_server(host: str, port: int, use_ssl: bool) -> Server:
- tls = Tls(validate=0) if use_ssl else None # 0 = ssl.CERT_NONE
- return Server(host, port=port, use_ssl=use_ssl, tls=tls, get_info=ALL)
- def _connect(cfg: dict) -> Connection:
- """Return an authenticated & bound ldap3 Connection or raise."""
- server = _make_server(cfg["host"], int(cfg["port"]), cfg["use_ssl"])
- auth_method = NTLM if cfg["auth_type"] == "NTLM" else SIMPLE
- conn = Connection(
- server,
- user=cfg["bind_dn"],
- password=cfg["bind_password"],
- authentication=auth_method,
- auto_bind=True,
- raise_exceptions=True,
- )
- return conn
- # ---------------------------------------------------------------------------
- # Public API
- # ---------------------------------------------------------------------------
- def authenticate_user(cfg: dict, username: str, password: str) -> dict:
- """Verify *username*/*password* against the directory (end-user login).
- Resolves the user's DN with the service bind account and then attempts a
- second bind as that DN with the supplied password. Used by the captive
- portal, which authenticates network users rather than administrators.
- """
- username = (
- (username or "").strip().replace("*", "").replace("(", "").replace(")", "")
- )
- if not username or not password:
- return {"status": "error", "message": _("Usuario y contraseña requeridos.")}
- lookup_username = username.rsplit("\\", 1)[-1]
- escaped_username = _escape_ldap_filter_value(lookup_username)
- try:
- conn = _connect(cfg)
- except Exception:
- logger.exception("Error al conectar con LDAP para autenticar usuario")
- return {
- "status": "error",
- "message": _("Error al conectar con el servidor LDAP"),
- }
- try:
- conn.search(
- cfg["base_dn"],
- "(&(objectClass=person)(|"
- f"(sAMAccountName={escaped_username})"
- f"(userPrincipalName={escaped_username})))",
- attributes=["cn"],
- )
- if not conn.entries:
- return {"status": "error", "message": _("Usuario no encontrado.")}
- user_dn = conn.entries[0].entry_dn
- except Exception:
- logger.exception("Error al buscar usuario LDAP para autenticación")
- return {"status": "error", "message": _("Error al autenticar contra LDAP")}
- finally:
- conn.unbind()
- try:
- server = _make_server(cfg["host"], int(cfg["port"]), cfg["use_ssl"])
- auth_method = NTLM if cfg["auth_type"] == "NTLM" else SIMPLE
- bind_user = user_dn
- if auth_method == NTLM:
- domain = cfg["bind_dn"].split("\\", 1)[0] if "\\" in cfg["bind_dn"] else ""
- bind_user = (
- username
- if "\\" in username or "@" in username or not domain
- else f"{domain}\\{username}"
- )
- user_conn = Connection(
- server,
- user=bind_user,
- password=password,
- authentication=auth_method,
- auto_bind=True,
- raise_exceptions=True,
- )
- user_conn.unbind()
- return {"status": "success", "username": username, "dn": user_dn}
- except core.exceptions.LDAPBindError:
- return {"status": "error", "message": _("Usuario o contraseña incorrectos.")}
- except Exception:
- logger.exception("Error de autenticación LDAP de usuario final")
- return {"status": "error", "message": _("Error al autenticar contra LDAP")}
- def test_connection(cfg: dict) -> dict:
- """Try to bind with the provided settings. Returns status/message dict."""
- try:
- conn = _connect(cfg)
- conn.unbind()
- return {
- "status": "success",
- "message": _("Conexión exitosa al servidor LDAP/AD."),
- }
- except core.exceptions.LDAPBindError:
- logger.exception("LDAP bind falló")
- return {"status": "error", "message": _("Error de autenticación LDAP")}
- except Exception:
- logger.exception("Error de conexión LDAP")
- return {
- "status": "error",
- "message": _("Error al conectar con el servidor LDAP"),
- }
- def _paged_count(cfg: dict, object_class: str) -> int:
- search_filter = f"(objectClass={object_class})"
- conn = _connect(cfg)
- count = 0
- try:
- for entry in conn.extend.standard.paged_search(
- search_base=cfg["base_dn"],
- search_filter=search_filter,
- search_scope=SUBTREE,
- attributes=["cn"],
- paged_size=1000,
- generator=True,
- ):
- if isinstance(entry, dict) and entry.get("type") == "searchResEntry":
- count += 1
- return count
- finally:
- conn.unbind()
- def get_stats(cfg: dict) -> dict:
- """Return total user and group counts from the directory."""
- try:
- user_count = _paged_count(cfg, "person")
- group_count = _paged_count(cfg, "group")
- return {"status": "success", "users": user_count, "groups": group_count}
- except Exception as exc:
- logger.error(f"Error al obtener estadísticas LDAP: {exc}")
- return {
- "status": "error",
- "message": _("Error al obtener estadísticas LDAP"),
- "users": 0,
- "groups": 0,
- }
- def _escape_ldap_filter_value(value: str) -> str:
- """Escape a user-controlled string for safe LDAP filtering."""
- return escape_filter_chars(value or "")
- def search_users(cfg: dict, query: str, limit: int = 50) -> dict:
- """Search users whose cn, sAMAccountName or mail matches *query*."""
- query = query.strip().replace("*", "").replace("(", "").replace(")", "")
- escaped_query = _escape_ldap_filter_value(query)
- filter_str = (
- f"(&(objectClass=person)"
- f"(|(cn=*{escaped_query}*)(sAMAccountName=*{escaped_query}*)(mail=*{escaped_query}*)(displayName=*{escaped_query}*)))"
- )
- try:
- conn = _connect(cfg)
- conn.search(
- cfg["base_dn"],
- filter_str,
- attributes=[
- "cn",
- "sAMAccountName",
- "mail",
- "displayName",
- "department",
- "title",
- ],
- size_limit=limit,
- )
- users = []
- for entry in conn.entries:
- users.append(
- {
- "cn": _val(entry, "cn"),
- "username": _val(entry, "sAMAccountName"),
- "email": _val(entry, "mail"),
- "display_name": _val(entry, "displayName"),
- "department": _val(entry, "department"),
- "title": _val(entry, "title"),
- "dn": entry.entry_dn,
- }
- )
- conn.unbind()
- return {"status": "success", "results": users, "total": len(users)}
- except Exception as exc:
- logger.error(f"Error al buscar usuarios LDAP: {exc}")
- return {
- "status": "error",
- "message": _("Error al buscar usuarios LDAP"),
- "results": [],
- "total": 0,
- }
- def search_groups(cfg: dict, query: str, limit: int = 50) -> dict:
- """Search groups whose cn matches *query*.
- If the query is empty, return all groups under the base DN.
- """
- query = query.strip().replace("*", "").replace("(", "").replace(")", "")
- if query:
- escaped_query = _escape_ldap_filter_value(query)
- filter_str = f"(&(objectClass=group)(cn=*{escaped_query}*))"
- else:
- filter_str = "(objectClass=group)"
- try:
- conn = _connect(cfg)
- conn.search(
- cfg["base_dn"],
- filter_str,
- attributes=["cn", "description", "member"],
- size_limit=limit,
- )
- groups = []
- for entry in conn.entries:
- members_raw = entry["member"].values if "member" in entry else []
- groups.append(
- {
- "cn": _val(entry, "cn"),
- "description": _val(entry, "description"),
- "member_count": len(members_raw),
- "dn": entry.entry_dn,
- }
- )
- conn.unbind()
- return {"status": "success", "results": groups, "total": len(groups)}
- except Exception as exc:
- logger.error(f"Error al buscar grupos LDAP: {exc}")
- return {
- "status": "error",
- "message": _("Error al buscar grupos LDAP"),
- "results": [],
- "total": 0,
- }
- def get_user_groups(cfg: dict, username: str) -> dict:
- """Return the groups that *username* (sAMAccountName) belongs to."""
- username = username.strip().replace("*", "").replace("(", "").replace(")", "")
- escaped_username = _escape_ldap_filter_value(username)
- try:
- conn = _connect(cfg)
- # Find the user DN first
- conn.search(
- cfg["base_dn"],
- f"(&(objectClass=person)(sAMAccountName={escaped_username}))",
- attributes=["distinguishedName", "memberOf", "cn", "displayName"],
- )
- if not conn.entries:
- conn.unbind()
- return {
- "status": "error",
- "message": _("Usuario no encontrado."),
- "groups": [],
- "user": None,
- }
- entry = conn.entries[0]
- member_of = entry["memberOf"].values if "memberOf" in entry else []
- groups = []
- for dn in member_of:
- cn = _cn_from_dn(dn)
- groups.append({"cn": cn, "dn": dn})
- conn.unbind()
- return {
- "status": "success",
- "user": {
- "cn": _val(entry, "cn"),
- "display_name": _val(entry, "displayName"),
- "dn": entry.entry_dn,
- },
- "groups": groups,
- "total": len(groups),
- }
- except Exception as exc:
- logger.error(f"Error al obtener grupos del usuario LDAP: {exc}")
- return {
- "status": "error",
- "message": _("Error al obtener grupos del usuario"),
- "groups": [],
- "user": None,
- }
- # ---------------------------------------------------------------------------
- # Tiny helpers
- # ---------------------------------------------------------------------------
- def _val(entry: Any, attr: str, default: str = "") -> str:
- try:
- v = entry[attr].value
- return str(v) if v is not None else default
- except Exception:
- return default
- def _cn_from_dn(dn: str) -> str:
- """Extract the CN value from a Distinguished Name string."""
- for part in dn.split(","):
- part = part.strip()
- if part.upper().startswith("CN="):
- return part[3:]
- return dn
|