ldap_service.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. """LDAP authentication service for BamBuddy (#794).
  2. Supports:
  3. - LDAP bind authentication (simple bind with user's credentials)
  4. - StartTLS, LDAPS, and plaintext connections
  5. - User search with configurable filter
  6. - Group membership resolution for role mapping
  7. """
  8. from __future__ import annotations
  9. import json
  10. import logging
  11. from dataclasses import dataclass
  12. from ldap3 import ALL, SUBTREE, Connection, Server, Tls
  13. from ldap3.core.exceptions import LDAPObjectClassError
  14. logger = logging.getLogger(__name__)
  15. @dataclass
  16. class LDAPUserInfo:
  17. """User information retrieved from LDAP after successful authentication."""
  18. username: str
  19. email: str | None
  20. display_name: str | None
  21. groups: list[str] # List of group DNs the user belongs to
  22. @dataclass
  23. class LDAPSearchResult:
  24. """A directory user returned by the admin search endpoint (no auth performed)."""
  25. username: str
  26. email: str | None
  27. display_name: str | None
  28. dn: str
  29. @dataclass
  30. class LDAPConfig:
  31. """LDAP configuration parsed from settings."""
  32. server_url: str
  33. bind_dn: str
  34. bind_password: str
  35. search_base: str
  36. user_filter: str # e.g. "(sAMAccountName={username})"
  37. security: str # "none", "starttls", "ldaps"
  38. group_mapping: dict[str, str] # LDAP group DN -> BamBuddy group name
  39. auto_provision: bool
  40. ca_cert_path: str # Path to CA certificate file (empty = skip verification)
  41. default_group: str # Fallback BamBuddy group assigned when user has no mapped groups (empty = no fallback)
  42. def parse_ldap_config(settings: dict[str, str]) -> LDAPConfig | None:
  43. """Parse LDAP config from settings key-value pairs. Returns None if LDAP not enabled."""
  44. if settings.get("ldap_enabled", "false").lower() != "true":
  45. return None
  46. server_url = settings.get("ldap_server_url", "").strip()
  47. if not server_url:
  48. return None
  49. group_mapping_raw = settings.get("ldap_group_mapping", "")
  50. try:
  51. group_mapping = json.loads(group_mapping_raw) if group_mapping_raw else {}
  52. except json.JSONDecodeError:
  53. group_mapping = {}
  54. return LDAPConfig(
  55. server_url=server_url,
  56. bind_dn=settings.get("ldap_bind_dn", "").strip(),
  57. bind_password=settings.get("ldap_bind_password", ""),
  58. search_base=settings.get("ldap_search_base", "").strip(),
  59. user_filter=settings.get("ldap_user_filter", "(sAMAccountName={username})").strip(),
  60. security=settings.get("ldap_security", "starttls").strip(),
  61. group_mapping=group_mapping if isinstance(group_mapping, dict) else {},
  62. auto_provision=settings.get("ldap_auto_provision", "false").lower() == "true",
  63. ca_cert_path=settings.get("ldap_ca_cert_path", "").strip(),
  64. default_group=settings.get("ldap_default_group", "").strip(),
  65. )
  66. def _create_server(config: LDAPConfig) -> Server:
  67. """Create an ldap3 Server instance from config.
  68. Always uses TLS — either LDAPS (TLS from start) or StartTLS (upgrade after connect).
  69. Plaintext LDAP is not supported.
  70. """
  71. import ssl
  72. use_ssl = config.security == "ldaps" or config.server_url.startswith("ldaps://")
  73. if config.ca_cert_path:
  74. tls = Tls(validate=ssl.CERT_REQUIRED, ca_certs_file=config.ca_cert_path)
  75. else:
  76. tls = Tls(validate=ssl.CERT_NONE)
  77. return Server(config.server_url, use_ssl=use_ssl, tls=tls, get_info=ALL, connect_timeout=10)
  78. def _open_service_connection(config: LDAPConfig, server: Server, *, check_names: bool = True) -> Connection:
  79. """Open and bind a service-account LDAP connection. Raises on failure.
  80. `check_names` toggles ldap3's client-side attribute-name validation. The
  81. default keeps it on so typos in `user_filter` fail loudly. The fuzzy
  82. directory search disables it because its fixed OR filter spans both AD-only
  83. (sAMAccountName, displayName) and OpenLDAP-only attribute names — without
  84. this bypass ldap3 throws `LDAPAttributeError` before any request is sent
  85. on a directory whose schema doesn't define one of the names.
  86. """
  87. conn = Connection(
  88. server,
  89. user=config.bind_dn,
  90. password=config.bind_password,
  91. auto_bind=False,
  92. raise_exceptions=True,
  93. read_only=True,
  94. check_names=check_names,
  95. )
  96. conn.open()
  97. if config.security == "starttls" and not config.server_url.startswith("ldaps://"):
  98. conn.start_tls()
  99. conn.bind()
  100. return conn
  101. def _pick_canonical_username(entry, fallback: str) -> str:
  102. """Prefer sAMAccountName, then uid, then the supplied fallback."""
  103. if hasattr(entry, "sAMAccountName") and entry.sAMAccountName:
  104. return str(entry.sAMAccountName)
  105. if hasattr(entry, "uid") and entry.uid:
  106. return str(entry.uid)
  107. return fallback
  108. def _extract_user_info(
  109. service_conn: Connection, config: LDAPConfig, user_entry, fallback_username: str
  110. ) -> LDAPUserInfo:
  111. """Build an LDAPUserInfo from an already-fetched directory entry.
  112. Collects memberOf groups, POSIX memberUid groups, and the primary
  113. gidNumber group; dedups DNs case-insensitively. Uses the supplied
  114. service-bound connection to resolve POSIX groups.
  115. """
  116. email = str(user_entry.mail) if hasattr(user_entry, "mail") and user_entry.mail else None
  117. display_name = (
  118. str(user_entry.displayName) if hasattr(user_entry, "displayName") and user_entry.displayName else None
  119. )
  120. # Collect groups from memberOf attribute (Active Directory / groupOfNames)
  121. groups = [str(g) for g in user_entry.memberOf] if hasattr(user_entry, "memberOf") and user_entry.memberOf else []
  122. canonical_username = _pick_canonical_username(user_entry, fallback_username)
  123. # Also search for POSIX groups, both the memberUid kind and the primary
  124. # gidNumber kind. Both filters name the posixGroup object class, and ldap3
  125. # validates that name against the schema it fetched at connect time
  126. # (get_info=ALL) before it builds the request — so on a directory that
  127. # publishes a schema without posixGroup it raises client-side and nothing is
  128. # ever sent. A directory with no posixGroup class has no posixGroup entries,
  129. # which is exactly the answer the searches would have returned, so the
  130. # correct response is to carry on with the memberOf groups collected above.
  131. #
  132. # Left uncaught, that exception escaped authenticate_ldap_user, and the login
  133. # route reports any LDAP error as "Incorrect username or password" — so an
  134. # lldap user, whose accounts carry posixAccount but whose directory defines
  135. # no group classes beyond groupOfNames, could never log in and had nothing
  136. # but a wrong-password message to go on (#2769). This predates the primary
  137. # gidNumber lookup: the memberUid filter has named the class since #794.
  138. try:
  139. posix_filter = f"(&(objectClass=posixGroup)(memberUid={_ldap_escape(canonical_username)}))"
  140. service_conn.search(
  141. search_base=config.search_base,
  142. search_filter=posix_filter,
  143. search_scope=SUBTREE,
  144. attributes=["cn"],
  145. )
  146. for entry in service_conn.entries:
  147. groups.append(str(entry.entry_dn))
  148. # POSIX primary group: user's gidNumber matches a posixGroup's gidNumber.
  149. # Standard Unix semantics treat this as full group membership, so we need
  150. # to resolve it to a group DN alongside the memberUid results.
  151. if hasattr(user_entry, "gidNumber") and user_entry.gidNumber:
  152. primary_gid = str(user_entry.gidNumber)
  153. primary_filter = f"(&(objectClass=posixGroup)(gidNumber={_ldap_escape(primary_gid)}))"
  154. service_conn.search(
  155. search_base=config.search_base,
  156. search_filter=primary_filter,
  157. search_scope=SUBTREE,
  158. attributes=["cn"],
  159. )
  160. for entry in service_conn.entries:
  161. groups.append(str(entry.entry_dn))
  162. except LDAPObjectClassError:
  163. # Logged once per authentication, at info: it is the explanation for a
  164. # user's POSIX groups being absent from their mapping, and it is not an
  165. # error the operator can or should act on.
  166. logger.info(
  167. "Directory publishes no posixGroup object class; skipping POSIX group lookup "
  168. "(memberOf groups are unaffected)"
  169. )
  170. # Dedupe group DNs (user may be in a group via both memberUid and primary gidNumber).
  171. # Case-insensitive comparison — LDAP DNs are case-insensitive by spec.
  172. seen_lower: set[str] = set()
  173. deduped_groups: list[str] = []
  174. for g in groups:
  175. key = g.lower()
  176. if key not in seen_lower:
  177. seen_lower.add(key)
  178. deduped_groups.append(g)
  179. return LDAPUserInfo(
  180. username=canonical_username,
  181. email=email,
  182. display_name=display_name,
  183. groups=deduped_groups,
  184. )
  185. def authenticate_ldap_user(config: LDAPConfig, username: str, password: str) -> LDAPUserInfo | None:
  186. """Authenticate a user via LDAP bind.
  187. 1. Bind with service account to search for the user DN
  188. 2. Attempt bind with the user's DN and provided password
  189. 3. On success, retrieve user attributes and group memberships
  190. Returns LDAPUserInfo on success, None on failure.
  191. """
  192. if not password:
  193. return None
  194. server = _create_server(config)
  195. try:
  196. service_conn = _open_service_connection(config, server)
  197. except Exception as e:
  198. logger.warning("LDAP service account bind failed: %s", e)
  199. return None
  200. try:
  201. # Search for the user
  202. search_filter = config.user_filter.replace("{username}", _ldap_escape(username))
  203. service_conn.search(
  204. search_base=config.search_base,
  205. search_filter=search_filter,
  206. search_scope=SUBTREE,
  207. attributes=["*"],
  208. )
  209. if not service_conn.entries:
  210. logger.info("LDAP user not found: %s", username)
  211. return None
  212. user_entry = service_conn.entries[0]
  213. user_dn = str(user_entry.entry_dn)
  214. # Step 2: Bind as the user to verify password
  215. try:
  216. user_conn = Connection(
  217. server,
  218. user=user_dn,
  219. password=password,
  220. auto_bind=False,
  221. raise_exceptions=True,
  222. read_only=True,
  223. )
  224. user_conn.open()
  225. if config.security == "starttls" and not config.server_url.startswith("ldaps://"):
  226. user_conn.start_tls()
  227. user_conn.bind()
  228. user_conn.unbind()
  229. except Exception as e:
  230. logger.info("LDAP bind failed for user %s: %s", username, e)
  231. return None
  232. info = _extract_user_info(service_conn, config, user_entry, username)
  233. # Don't log the raw DN — its leaf CN is the user's real name (PII, #2681).
  234. # The username + group count is enough to confirm a successful auth; the
  235. # support-bundle sanitizer also redacts any DN that slips through (e.g. an
  236. # ldap3 exception string), but keeping it out of the log at the source is
  237. # the primary hygiene per the "no private data in logs" rule.
  238. logger.info(
  239. "LDAP authentication successful for user: %s (groups: %d)",
  240. info.username,
  241. len(info.groups),
  242. )
  243. return info
  244. finally:
  245. service_conn.unbind()
  246. def lookup_ldap_user(config: LDAPConfig, username: str) -> LDAPUserInfo | None:
  247. """Look up a directory user by exact username via the service-account bind.
  248. Performs no password verification — intended for the admin manual-provision
  249. flow, where the caller has already been authenticated as a BamBuddy admin
  250. and now needs the directory attributes (email, display name, group DNs)
  251. to create the user.
  252. Uses the same `user_filter` template that the login path uses, so anything
  253. that logs in successfully via auto-provision is also resolvable here.
  254. """
  255. server = _create_server(config)
  256. try:
  257. service_conn = _open_service_connection(config, server)
  258. except Exception as e:
  259. logger.warning("LDAP service account bind failed during lookup: %s", e)
  260. raise
  261. try:
  262. search_filter = config.user_filter.replace("{username}", _ldap_escape(username))
  263. service_conn.search(
  264. search_base=config.search_base,
  265. search_filter=search_filter,
  266. search_scope=SUBTREE,
  267. attributes=["*"],
  268. )
  269. if not service_conn.entries:
  270. logger.info("LDAP lookup: user not found: %s", username)
  271. return None
  272. return _extract_user_info(service_conn, config, service_conn.entries[0], username)
  273. finally:
  274. service_conn.unbind()
  275. def search_ldap_users(config: LDAPConfig, query: str, limit: int = 25) -> list[LDAPSearchResult]:
  276. """Fuzzy search the directory for users matching `query`.
  277. Uses a fixed OR filter across sAMAccountName, uid, mail, displayName, and
  278. cn — covering both Active Directory and OpenLDAP layouts. The query is
  279. RFC-4515 escaped so a typed `*` doesn't enumerate the whole directory.
  280. Returns up to `limit` results (default 25). Service-bind failures raise so
  281. the caller can surface a 503; "no matches" returns an empty list.
  282. Callers should enforce a minimum query length (≥2 chars) — short queries
  283. against a large directory are wasteful and effectively unbounded.
  284. """
  285. query = query.strip()
  286. if len(query) < 2:
  287. return []
  288. escaped = _ldap_escape(query)
  289. search_filter = (
  290. f"(|(sAMAccountName=*{escaped}*)(uid=*{escaped}*)(mail=*{escaped}*)(displayName=*{escaped}*)(cn=*{escaped}*))"
  291. )
  292. server = _create_server(config)
  293. try:
  294. # check_names=False so OpenLDAP directories (no sAMAccountName/displayName
  295. # in schema) don't reject the cross-schema OR filter — see helper docstring.
  296. service_conn = _open_service_connection(config, server, check_names=False)
  297. except Exception as e:
  298. logger.warning("LDAP service account bind failed during search: %s", e)
  299. raise
  300. try:
  301. # attributes=["*"] requests all user attributes. We can't enumerate the
  302. # AD/OpenLDAP-specific names (sAMAccountName, displayName) explicitly
  303. # because ldap3 validates the attribute list against the server schema
  304. # even with check_names=False — and OpenLDAP rejects the AD names. The
  305. # `*` wildcard is hardcoded in ldap3's ATTRIBUTES_EXCLUDED_FROM_CHECK so
  306. # it bypasses that validation, and the server returns whatever it has.
  307. service_conn.search(
  308. search_base=config.search_base,
  309. search_filter=search_filter,
  310. search_scope=SUBTREE,
  311. attributes=["*"],
  312. size_limit=limit,
  313. )
  314. results: list[LDAPSearchResult] = []
  315. for entry in service_conn.entries:
  316. username = _pick_canonical_username(entry, "")
  317. if not username and hasattr(entry, "cn") and entry.cn:
  318. # Last resort — some OpenLDAP layouts only have cn
  319. username = str(entry.cn)
  320. if not username:
  321. continue
  322. email = str(entry.mail) if hasattr(entry, "mail") and entry.mail else None
  323. display_name = str(entry.displayName) if hasattr(entry, "displayName") and entry.displayName else None
  324. results.append(
  325. LDAPSearchResult(
  326. username=username,
  327. email=email,
  328. display_name=display_name,
  329. dn=str(entry.entry_dn),
  330. )
  331. )
  332. logger.info("LDAP directory search for %r returned %d result(s)", query, len(results))
  333. return results
  334. finally:
  335. service_conn.unbind()
  336. def resolve_group_mapping(ldap_groups: list[str], group_mapping: dict[str, str]) -> list[str]:
  337. """Map LDAP group DNs to BamBuddy group names.
  338. Returns list of BamBuddy group names that the user should be added to.
  339. Comparison is case-insensitive on the LDAP group DN.
  340. """
  341. if not group_mapping:
  342. return []
  343. # Build case-insensitive lookup
  344. mapping_lower = {k.lower(): v for k, v in group_mapping.items()}
  345. result = []
  346. for ldap_group in ldap_groups:
  347. bambuddy_group = mapping_lower.get(ldap_group.lower())
  348. if bambuddy_group:
  349. result.append(bambuddy_group)
  350. return result
  351. def test_ldap_connection(config: LDAPConfig) -> tuple[bool, str]:
  352. """Test LDAP connection and service account bind.
  353. Returns (success, message).
  354. """
  355. try:
  356. server = _create_server(config)
  357. conn = Connection(
  358. server,
  359. user=config.bind_dn,
  360. password=config.bind_password,
  361. auto_bind=False,
  362. raise_exceptions=True,
  363. read_only=True,
  364. )
  365. conn.open()
  366. if config.security == "starttls" and not config.server_url.startswith("ldaps://"):
  367. conn.start_tls()
  368. conn.bind()
  369. # Try a search to verify search base
  370. conn.search(
  371. search_base=config.search_base,
  372. search_filter="(objectClass=*)",
  373. search_scope=SUBTREE,
  374. size_limit=1,
  375. )
  376. conn.unbind()
  377. return True, "LDAP connection successful"
  378. except Exception as e:
  379. return False, f"LDAP connection failed: {e}"
  380. def _ldap_escape(value: str) -> str:
  381. """Escape special characters in LDAP search filter values (RFC 4515)."""
  382. replacements = {
  383. "\\": "\\5c",
  384. "*": "\\2a",
  385. "(": "\\28",
  386. ")": "\\29",
  387. "\x00": "\\00",
  388. }
  389. for char, escaped in replacements.items():
  390. value = value.replace(char, escaped)
  391. return value