ldap_service.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. from __future__ import annotations
  2. from typing import Any
  3. from flask_babel import gettext as _
  4. from ldap3 import (
  5. ALL,
  6. NTLM,
  7. SIMPLE,
  8. SUBTREE,
  9. Connection,
  10. Server,
  11. Tls,
  12. core,
  13. )
  14. from ldap3.utils.conv import escape_filter_chars
  15. from loguru import logger
  16. # ---------------------------------------------------------------------------
  17. # Internal helpers
  18. # ---------------------------------------------------------------------------
  19. def _make_server(host: str, port: int, use_ssl: bool) -> Server:
  20. tls = Tls(validate=0) if use_ssl else None # 0 = ssl.CERT_NONE
  21. return Server(host, port=port, use_ssl=use_ssl, tls=tls, get_info=ALL)
  22. def _connect(cfg: dict) -> Connection:
  23. """Return an authenticated & bound ldap3 Connection or raise."""
  24. server = _make_server(cfg["host"], int(cfg["port"]), cfg["use_ssl"])
  25. auth_method = NTLM if cfg["auth_type"] == "NTLM" else SIMPLE
  26. conn = Connection(
  27. server,
  28. user=cfg["bind_dn"],
  29. password=cfg["bind_password"],
  30. authentication=auth_method,
  31. auto_bind=True,
  32. raise_exceptions=True,
  33. )
  34. return conn
  35. # ---------------------------------------------------------------------------
  36. # Public API
  37. # ---------------------------------------------------------------------------
  38. def authenticate_user(cfg: dict, username: str, password: str) -> dict:
  39. """Verify *username*/*password* against the directory (end-user login).
  40. Resolves the user's DN with the service bind account and then attempts a
  41. second bind as that DN with the supplied password. Used by the captive
  42. portal, which authenticates network users rather than administrators.
  43. """
  44. username = (
  45. (username or "").strip().replace("*", "").replace("(", "").replace(")", "")
  46. )
  47. if not username or not password:
  48. return {"status": "error", "message": _("Usuario y contraseña requeridos.")}
  49. lookup_username = username.rsplit("\\", 1)[-1]
  50. escaped_username = _escape_ldap_filter_value(lookup_username)
  51. try:
  52. conn = _connect(cfg)
  53. except Exception:
  54. logger.exception("Error al conectar con LDAP para autenticar usuario")
  55. return {
  56. "status": "error",
  57. "message": _("Error al conectar con el servidor LDAP"),
  58. }
  59. try:
  60. conn.search(
  61. cfg["base_dn"],
  62. "(&(objectClass=person)(|"
  63. f"(sAMAccountName={escaped_username})"
  64. f"(userPrincipalName={escaped_username})))",
  65. attributes=["cn"],
  66. )
  67. if not conn.entries:
  68. return {"status": "error", "message": _("Usuario no encontrado.")}
  69. user_dn = conn.entries[0].entry_dn
  70. except Exception:
  71. logger.exception("Error al buscar usuario LDAP para autenticación")
  72. return {"status": "error", "message": _("Error al autenticar contra LDAP")}
  73. finally:
  74. conn.unbind()
  75. try:
  76. server = _make_server(cfg["host"], int(cfg["port"]), cfg["use_ssl"])
  77. auth_method = NTLM if cfg["auth_type"] == "NTLM" else SIMPLE
  78. bind_user = user_dn
  79. if auth_method == NTLM:
  80. domain = cfg["bind_dn"].split("\\", 1)[0] if "\\" in cfg["bind_dn"] else ""
  81. bind_user = (
  82. username
  83. if "\\" in username or "@" in username or not domain
  84. else f"{domain}\\{username}"
  85. )
  86. user_conn = Connection(
  87. server,
  88. user=bind_user,
  89. password=password,
  90. authentication=auth_method,
  91. auto_bind=True,
  92. raise_exceptions=True,
  93. )
  94. user_conn.unbind()
  95. return {"status": "success", "username": username, "dn": user_dn}
  96. except core.exceptions.LDAPBindError:
  97. return {"status": "error", "message": _("Usuario o contraseña incorrectos.")}
  98. except Exception:
  99. logger.exception("Error de autenticación LDAP de usuario final")
  100. return {"status": "error", "message": _("Error al autenticar contra LDAP")}
  101. def test_connection(cfg: dict) -> dict:
  102. """Try to bind with the provided settings. Returns status/message dict."""
  103. try:
  104. conn = _connect(cfg)
  105. conn.unbind()
  106. return {
  107. "status": "success",
  108. "message": _("Conexión exitosa al servidor LDAP/AD."),
  109. }
  110. except core.exceptions.LDAPBindError:
  111. logger.exception("LDAP bind falló")
  112. return {"status": "error", "message": _("Error de autenticación LDAP")}
  113. except Exception:
  114. logger.exception("Error de conexión LDAP")
  115. return {
  116. "status": "error",
  117. "message": _("Error al conectar con el servidor LDAP"),
  118. }
  119. def _paged_count(cfg: dict, object_class: str) -> int:
  120. search_filter = f"(objectClass={object_class})"
  121. conn = _connect(cfg)
  122. count = 0
  123. try:
  124. for entry in conn.extend.standard.paged_search(
  125. search_base=cfg["base_dn"],
  126. search_filter=search_filter,
  127. search_scope=SUBTREE,
  128. attributes=["cn"],
  129. paged_size=1000,
  130. generator=True,
  131. ):
  132. if isinstance(entry, dict) and entry.get("type") == "searchResEntry":
  133. count += 1
  134. return count
  135. finally:
  136. conn.unbind()
  137. def get_stats(cfg: dict) -> dict:
  138. """Return total user and group counts from the directory."""
  139. try:
  140. user_count = _paged_count(cfg, "person")
  141. group_count = _paged_count(cfg, "group")
  142. return {"status": "success", "users": user_count, "groups": group_count}
  143. except Exception as exc:
  144. logger.error(f"Error al obtener estadísticas LDAP: {exc}")
  145. return {
  146. "status": "error",
  147. "message": _("Error al obtener estadísticas LDAP"),
  148. "users": 0,
  149. "groups": 0,
  150. }
  151. def _escape_ldap_filter_value(value: str) -> str:
  152. """Escape a user-controlled string for safe LDAP filtering."""
  153. return escape_filter_chars(value or "")
  154. def search_users(cfg: dict, query: str, limit: int = 50) -> dict:
  155. """Search users whose cn, sAMAccountName or mail matches *query*."""
  156. query = query.strip().replace("*", "").replace("(", "").replace(")", "")
  157. escaped_query = _escape_ldap_filter_value(query)
  158. filter_str = (
  159. f"(&(objectClass=person)"
  160. f"(|(cn=*{escaped_query}*)(sAMAccountName=*{escaped_query}*)(mail=*{escaped_query}*)(displayName=*{escaped_query}*)))"
  161. )
  162. try:
  163. conn = _connect(cfg)
  164. conn.search(
  165. cfg["base_dn"],
  166. filter_str,
  167. attributes=[
  168. "cn",
  169. "sAMAccountName",
  170. "mail",
  171. "displayName",
  172. "department",
  173. "title",
  174. ],
  175. size_limit=limit,
  176. )
  177. users = []
  178. for entry in conn.entries:
  179. users.append(
  180. {
  181. "cn": _val(entry, "cn"),
  182. "username": _val(entry, "sAMAccountName"),
  183. "email": _val(entry, "mail"),
  184. "display_name": _val(entry, "displayName"),
  185. "department": _val(entry, "department"),
  186. "title": _val(entry, "title"),
  187. "dn": entry.entry_dn,
  188. }
  189. )
  190. conn.unbind()
  191. return {"status": "success", "results": users, "total": len(users)}
  192. except Exception as exc:
  193. logger.error(f"Error al buscar usuarios LDAP: {exc}")
  194. return {
  195. "status": "error",
  196. "message": _("Error al buscar usuarios LDAP"),
  197. "results": [],
  198. "total": 0,
  199. }
  200. def search_groups(cfg: dict, query: str, limit: int = 50) -> dict:
  201. """Search groups whose cn matches *query*.
  202. If the query is empty, return all groups under the base DN.
  203. """
  204. query = query.strip().replace("*", "").replace("(", "").replace(")", "")
  205. if query:
  206. escaped_query = _escape_ldap_filter_value(query)
  207. filter_str = f"(&(objectClass=group)(cn=*{escaped_query}*))"
  208. else:
  209. filter_str = "(objectClass=group)"
  210. try:
  211. conn = _connect(cfg)
  212. conn.search(
  213. cfg["base_dn"],
  214. filter_str,
  215. attributes=["cn", "description", "member"],
  216. size_limit=limit,
  217. )
  218. groups = []
  219. for entry in conn.entries:
  220. members_raw = entry["member"].values if "member" in entry else []
  221. groups.append(
  222. {
  223. "cn": _val(entry, "cn"),
  224. "description": _val(entry, "description"),
  225. "member_count": len(members_raw),
  226. "dn": entry.entry_dn,
  227. }
  228. )
  229. conn.unbind()
  230. return {"status": "success", "results": groups, "total": len(groups)}
  231. except Exception as exc:
  232. logger.error(f"Error al buscar grupos LDAP: {exc}")
  233. return {
  234. "status": "error",
  235. "message": _("Error al buscar grupos LDAP"),
  236. "results": [],
  237. "total": 0,
  238. }
  239. def get_user_groups(cfg: dict, username: str) -> dict:
  240. """Return the groups that *username* (sAMAccountName) belongs to."""
  241. username = username.strip().replace("*", "").replace("(", "").replace(")", "")
  242. escaped_username = _escape_ldap_filter_value(username)
  243. try:
  244. conn = _connect(cfg)
  245. # Find the user DN first
  246. conn.search(
  247. cfg["base_dn"],
  248. f"(&(objectClass=person)(sAMAccountName={escaped_username}))",
  249. attributes=["distinguishedName", "memberOf", "cn", "displayName"],
  250. )
  251. if not conn.entries:
  252. conn.unbind()
  253. return {
  254. "status": "error",
  255. "message": _("Usuario no encontrado."),
  256. "groups": [],
  257. "user": None,
  258. }
  259. entry = conn.entries[0]
  260. member_of = entry["memberOf"].values if "memberOf" in entry else []
  261. groups = []
  262. for dn in member_of:
  263. cn = _cn_from_dn(dn)
  264. groups.append({"cn": cn, "dn": dn})
  265. conn.unbind()
  266. return {
  267. "status": "success",
  268. "user": {
  269. "cn": _val(entry, "cn"),
  270. "display_name": _val(entry, "displayName"),
  271. "dn": entry.entry_dn,
  272. },
  273. "groups": groups,
  274. "total": len(groups),
  275. }
  276. except Exception as exc:
  277. logger.error(f"Error al obtener grupos del usuario LDAP: {exc}")
  278. return {
  279. "status": "error",
  280. "message": _("Error al obtener grupos del usuario"),
  281. "groups": [],
  282. "user": None,
  283. }
  284. # ---------------------------------------------------------------------------
  285. # Tiny helpers
  286. # ---------------------------------------------------------------------------
  287. def _val(entry: Any, attr: str, default: str = "") -> str:
  288. try:
  289. v = entry[attr].value
  290. return str(v) if v is not None else default
  291. except Exception:
  292. return default
  293. def _cn_from_dn(dn: str) -> str:
  294. """Extract the CN value from a Distinguished Name string."""
  295. for part in dn.split(","):
  296. part = part.strip()
  297. if part.upper().startswith("CN="):
  298. return part[3:]
  299. return dn