ser2netweb 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. ser2netweb/__init__.py +20 -0
  2. ser2netweb/__main__.py +6 -0
  3. ser2netweb/accounts.py +503 -0
  4. ser2netweb/cli.py +489 -0
  5. ser2netweb/clock.py +128 -0
  6. ser2netweb/config.py +4491 -0
  7. ser2netweb/console.py +181 -0
  8. ser2netweb/datalock.py +181 -0
  9. ser2netweb/engine/__init__.py +0 -0
  10. ser2netweb/engine/access.py +173 -0
  11. ser2netweb/engine/bindhint.py +115 -0
  12. ser2netweb/engine/bridge.py +1928 -0
  13. ser2netweb/engine/cluster.py +1140 -0
  14. ser2netweb/engine/modbus.py +530 -0
  15. ser2netweb/engine/modbus_gateway.py +1465 -0
  16. ser2netweb/engine/mqtt_pub.py +632 -0
  17. ser2netweb/engine/netguard.py +805 -0
  18. ser2netweb/engine/netinfo.py +199 -0
  19. ser2netweb/engine/portdiag.py +414 -0
  20. ser2netweb/engine/portlist.py +471 -0
  21. ser2netweb/engine/protocols/__init__.py +28 -0
  22. ser2netweb/engine/protocols/base.py +117 -0
  23. ser2netweb/engine/protocols/raw.py +12 -0
  24. ser2netweb/engine/protocols/rfc2217.py +586 -0
  25. ser2netweb/engine/protocols/telnet.py +172 -0
  26. ser2netweb/engine/serial_compat.py +598 -0
  27. ser2netweb/engine/serial_io.py +210 -0
  28. ser2netweb/engine/serial_link.py +414 -0
  29. ser2netweb/engine/sockopts.py +103 -0
  30. ser2netweb/engine/sparkplug.py +538 -0
  31. ser2netweb/engine/sparkplug_node.py +550 -0
  32. ser2netweb/engine/supervisor.py +533 -0
  33. ser2netweb/engine/tls.py +232 -0
  34. ser2netweb/envvars.py +57 -0
  35. ser2netweb/explain.py +117 -0
  36. ser2netweb/healthcheck.py +78 -0
  37. ser2netweb/i18n.py +110 -0
  38. ser2netweb/importer.py +550 -0
  39. ser2netweb/layout.py +118 -0
  40. ser2netweb/licences.py +86 -0
  41. ser2netweb/locale/tr.json +1569 -0
  42. ser2netweb/logsetup.py +253 -0
  43. ser2netweb/logtext.py +23 -0
  44. ser2netweb/notify.py +761 -0
  45. ser2netweb/optional.py +76 -0
  46. ser2netweb/reload.py +295 -0
  47. ser2netweb/runtime.py +762 -0
  48. ser2netweb/sdnotify.py +85 -0
  49. ser2netweb/ser2net_import.py +2001 -0
  50. ser2netweb/signins.py +98 -0
  51. ser2netweb/standalone.py +154 -0
  52. ser2netweb/state.py +1457 -0
  53. ser2netweb/storage.py +130 -0
  54. ser2netweb/textfold.py +51 -0
  55. ser2netweb/tlsreload.py +37 -0
  56. ser2netweb/watchdog.py +201 -0
  57. ser2netweb/web/__init__.py +0 -0
  58. ser2netweb/web/api.py +793 -0
  59. ser2netweb/web/auth.py +699 -0
  60. ser2netweb/web/certinfo.py +144 -0
  61. ser2netweb/web/httpguard.py +413 -0
  62. ser2netweb/web/ldap_auth.py +556 -0
  63. ser2netweb/web/oidc_auth.py +330 -0
  64. ser2netweb/web/proxy.py +398 -0
  65. ser2netweb/web/routes/__init__.py +78 -0
  66. ser2netweb/web/routes/cluster.py +669 -0
  67. ser2netweb/web/routes/common.py +359 -0
  68. ser2netweb/web/routes/console.py +451 -0
  69. ser2netweb/web/routes/forms.py +853 -0
  70. ser2netweb/web/routes/login.py +573 -0
  71. ser2netweb/web/routes/mappings.py +470 -0
  72. ser2netweb/web/routes/ops.py +374 -0
  73. ser2netweb/web/routes/settings.py +2135 -0
  74. ser2netweb/web/routes/system.py +308 -0
  75. ser2netweb/web/routes/totp.py +282 -0
  76. ser2netweb/web/selfsigned.py +129 -0
  77. ser2netweb/web/server.py +483 -0
  78. ser2netweb/web/static/app.css +327 -0
  79. ser2netweb/web/static/app.js +1102 -0
  80. ser2netweb/web/static/htmx.min.js +1 -0
  81. ser2netweb/web/static/points.js +218 -0
  82. ser2netweb/web/static/theme.js +7 -0
  83. ser2netweb/web/static/xterm-addon-fit.js +2 -0
  84. ser2netweb/web/static/xterm.css +218 -0
  85. ser2netweb/web/static/xterm.js +2 -0
  86. ser2netweb/web/templates/_cluster_body.html +109 -0
  87. ser2netweb/web/templates/_console.html +21 -0
  88. ser2netweb/web/templates/_footer.html +13 -0
  89. ser2netweb/web/templates/_login_notice.html +8 -0
  90. ser2netweb/web/templates/_macros.html +21 -0
  91. ser2netweb/web/templates/_mapping_form.html +477 -0
  92. ser2netweb/web/templates/_mapping_log.html +28 -0
  93. ser2netweb/web/templates/_mapping_traces.html +44 -0
  94. ser2netweb/web/templates/_mappings_body.html +149 -0
  95. ser2netweb/web/templates/_modbus_read.html +18 -0
  96. ser2netweb/web/templates/_ports_table.html +37 -0
  97. ser2netweb/web/templates/_serial_port_select.html +48 -0
  98. ser2netweb/web/templates/_shell.html +41 -0
  99. ser2netweb/web/templates/audit.html +55 -0
  100. ser2netweb/web/templates/base.html +77 -0
  101. ser2netweb/web/templates/dashboard.html +72 -0
  102. ser2netweb/web/templates/licenses.html +18 -0
  103. ser2netweb/web/templates/login.html +32 -0
  104. ser2netweb/web/templates/login_totp.html +23 -0
  105. ser2netweb/web/templates/settings.html +830 -0
  106. ser2netweb/web/templates/setup.html +43 -0
  107. ser2netweb/web/templates/totp.html +41 -0
  108. ser2netweb/web/totp.py +94 -0
  109. ser2netweb/winservice.py +1793 -0
  110. ser2netweb-3.0.0.dist-info/METADATA +120 -0
  111. ser2netweb-3.0.0.dist-info/RECORD +121 -0
  112. ser2netweb-3.0.0.dist-info/WHEEL +5 -0
  113. ser2netweb-3.0.0.dist-info/entry_points.txt +2 -0
  114. ser2netweb-3.0.0.dist-info/licenses/COMMERCIAL_LICENSE.md +94 -0
  115. ser2netweb-3.0.0.dist-info/licenses/LICENSE +662 -0
  116. ser2netweb-3.0.0.dist-info/licenses/NOTICE +20 -0
  117. ser2netweb-3.0.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +105 -0
  118. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/htmx.org.txt +13 -0
  119. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm-addon-fit.txt +19 -0
  120. ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm.txt +21 -0
  121. ser2netweb-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,556 @@
1
+ """Optional LDAP / Active Directory authentication, layered on the RBAC model.
2
+
3
+ A user authenticates by binding to the directory; their group membership maps to a
4
+ ser2netweb role. On success a 'shadow' local User (source='ldap', no password) is
5
+ upserted so the rest of the system — sessions, role checks, the Users panel — works
6
+ uniformly; the role is refreshed from LDAP groups on every login.
7
+
8
+ ldap3 is an OPTIONAL dependency, imported lazily: if it's absent or fails to import,
9
+ LDAP login is disabled with a log line saying which (ser2netweb.optional) and local accounts
10
+ keep working. The actual bind/search is isolated so the role-mapping and shadow-user
11
+ logic can be unit-tested without ldap3; the group -> role matching (OIDC claims use it
12
+ too) is pure Python.
13
+
14
+ LDAPS and StartTLS check the directory server's certificate and host name (tls_context:
15
+ the system's CAs or ldap.ca_file); ldap3's own default checks nothing. A refused
16
+ certificate is logged with what to set (TlsProblem); nothing is sent over that
17
+ connection.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import contextlib
22
+ import re
23
+ import ssl
24
+ from dataclasses import dataclass
25
+ from typing import Any
26
+
27
+ from .. import optional
28
+ from ..config import ROLE_RANK, User, fold # fold: how group names compare
29
+
30
+ # LDAP_MATCHING_RULE_IN_CHAIN: Active Directory follows nested groups for this filter
31
+ IN_CHAIN_RULE = "1.2.840.113556.1.4.1941"
32
+
33
+ # ---------------- group -> role ----------------
34
+ # A group setting (admin_group / operator_group / viewer_group, for LDAP and OIDC alike)
35
+ # names one group, and only its whole name matches — never a part of it. Letter case and
36
+ # extra spaces don't count (fold). It matches a group the directory or the identity
37
+ # provider reports when it is
38
+ # * the same text: a full DN, compared RDN by RDN (cn=ser2netweb-admins,ou=groups,
39
+ # dc=corp,dc=local), or the value exactly as the provider sends it;
40
+ # * the group's own name: the value of a DN's first RDN (ser2netweb-admins), the last
41
+ # segment of a path (Keycloak sends /team/ser2netweb-admins) or the part after a
42
+ # DOMAIN\ prefix (AD FS);
43
+ # * the leading RDNs of the DN (cn=ser2netweb-admins,ou=groups) or the trailing segments
44
+ # of a path (team/ser2netweb-admins); a setting starting with / is the whole path.
45
+ GROUP_SETTINGS = (("admin_group", "admin"), ("operator_group", "operator"),
46
+ ("viewer_group", "viewer"))
47
+
48
+ _DN_TYPE = re.compile(r"[A-Za-z][A-Za-z0-9-]*|[0-9]+(?:\.[0-9]+)*")
49
+ _HEX = frozenset("0123456789abcdefABCDEF")
50
+
51
+
52
+ def _split_dn(text) -> list[list[tuple[str, str]]] | None:
53
+ """The RDNs of an RFC 4514 DN, each a list of (attribute type, value) with the
54
+ escapes (\\, \\2C, UTF-8 bytes such as \\C4\\B0) decoded, or None when `text` is not
55
+ a DN."""
56
+ s = str(text)
57
+ rdns: list[list[tuple[str, str]]] = []
58
+ avas: list[tuple[str, str]] = []
59
+ i, n = 0, len(s)
60
+ while True:
61
+ eq = s.find("=", i)
62
+ if eq < 0 or not _DN_TYPE.fullmatch(s[i:eq].strip()):
63
+ return None
64
+ typ, i, raw = s[i:eq].strip().lower(), eq + 1, bytearray()
65
+ while i < n and s[i] not in ",+":
66
+ if s[i] == "\\":
67
+ pair = s[i + 1:i + 3]
68
+ if len(pair) == 2 and set(pair) <= _HEX:
69
+ raw.append(int(pair, 16))
70
+ i += 3
71
+ continue
72
+ if i + 1 >= n:
73
+ return None
74
+ i += 1
75
+ raw += s[i].encode("utf-8", "surrogatepass")
76
+ i += 1
77
+ avas.append((typ, raw.decode("utf-8", "replace").strip()))
78
+ if i >= n or s[i] == ",":
79
+ rdns.append(avas)
80
+ avas = []
81
+ if i >= n:
82
+ return rdns
83
+ i += 1
84
+
85
+
86
+ def _dn_key(text) -> tuple[frozenset[tuple[str, str]], ...] | None:
87
+ rdns = _split_dn(text)
88
+ return None if rdns is None else tuple(frozenset((t, fold(v)) for t, v in rdn)
89
+ for rdn in rdns)
90
+
91
+
92
+ def group_matches(setting, group) -> bool:
93
+ """Does this group setting name this group? (the rules above)"""
94
+ want = fold(setting or "")
95
+ if not want:
96
+ return False
97
+ if want == fold(group):
98
+ return True
99
+ have = _dn_key(group)
100
+ if have:
101
+ wanted = _dn_key(setting)
102
+ if wanted: # the full DN or its leading RDNs
103
+ return have[:len(wanted)] == wanted
104
+ return any(value == want for _type, value in have[0]) # the group's own name
105
+ text, typed = str(group).strip(), str(setting).strip()
106
+ if "\\" in text and "\\" not in typed: # DOMAIN\group
107
+ return fold(text.rsplit("\\", 1)[1]) == want
108
+ if "/" in text or "/" in typed: # a path such as Keycloak's /team/group
109
+ path = [fold(p) for p in text.strip("/").split("/")]
110
+ tail = [fold(p) for p in typed.strip("/").split("/")]
111
+ return path == tail if typed.startswith("/") else path[-len(tail):] == tail
112
+ return False
113
+
114
+
115
+ def group_name(group) -> str:
116
+ """A group's own name: a DN's first RDN value, a path's last segment, the part
117
+ after DOMAIN\\ — what to enter as the group setting."""
118
+ rdns = _split_dn(group)
119
+ if rdns:
120
+ return rdns[0][0][1]
121
+ text = str(group).strip()
122
+ if "\\" in text:
123
+ return text.rsplit("\\", 1)[1]
124
+ return text.rstrip("/").rsplit("/", 1)[-1] if "/" in text else text
125
+
126
+
127
+ def group_names(groups, limit: int = 10) -> str:
128
+ """The groups for a log line: their own names, at most `limit`, each cut at 64
129
+ characters."""
130
+ groups = list(groups)
131
+ names = [group_name(g) for g in groups[:limit]]
132
+ text = ", ".join(repr(n if len(n) <= 64 else n[:63] + "…") for n in names) or "none"
133
+ return text + (f" (+{len(groups) - limit} more)" if len(groups) > limit else "")
134
+
135
+
136
+ @dataclass
137
+ class RoleDecision:
138
+ """How a user's groups map to a role (role_decision)."""
139
+ role: str | None # the role they get; None: the sign-in is refused
140
+ setting: str = "" # the group setting that gave it ("": none, default_role)
141
+ group: str = "" # the group it matched
142
+ # a group setting that is only part of the name of one of their groups, which counted
143
+ # before group names had to match whole, and would give more than `role`:
144
+ # (setting, its value, that group) and the role it gave
145
+ partial: tuple[str, str, str] | None = None
146
+ partial_role: str = ""
147
+
148
+
149
+ def role_decision(groups, settings) -> RoleDecision:
150
+ """The highest role a user's groups give (LDAP group DNs or OIDC claim values):
151
+ admin_group, then operator_group, then viewer_group, else default_role (blank:
152
+ None, refused)."""
153
+ groups = [str(g) for g in groups]
154
+ decision = RoleDecision(settings.default_role or None)
155
+ for setting, role in GROUP_SETTINGS:
156
+ group = next((g for g in groups if group_matches(getattr(settings, setting), g)), None)
157
+ if group is not None:
158
+ decision = RoleDecision(role, setting, group)
159
+ break
160
+ for setting, role in GROUP_SETTINGS: # the earlier rule: the text anywhere in a group
161
+ text = (getattr(settings, setting) or "").strip().lower()
162
+ group = next((g for g in groups if text and text in g.lower()), None)
163
+ if group is not None:
164
+ if ROLE_RANK[role] > ROLE_RANK.get(decision.role or "", 0):
165
+ decision.partial = (setting, getattr(settings, setting), group)
166
+ decision.partial_role = role
167
+ break
168
+ return decision
169
+
170
+
171
+ def role_for_groups(groups, settings) -> str | None:
172
+ """Highest ser2netweb role granted by a user's groups, or None to deny (the user
173
+ authenticated but is in no mapped group and no default_role is set)."""
174
+ return role_decision(groups, settings).role
175
+
176
+
177
+ def upsert_ldap_user(config, username: str, role: str) -> User:
178
+ """Create or refresh the shadow account for an LDAP user."""
179
+ return config.upsert_external_user(username, role, "ldap")
180
+
181
+
182
+ # ---------------- TLS: LDAPS and StartTLS ----------------
183
+ class CaFileError(ValueError):
184
+ """ldap.ca_file can't be used: unreadable, or no certificate in it."""
185
+
186
+ def __init__(self, path: str, reason: str, unreadable: bool):
187
+ super().__init__(f"{path!r}: {reason}")
188
+ self.path, self.reason, self.unreadable = path, reason, unreadable
189
+
190
+
191
+ def tls_context(settings) -> ssl.SSLContext:
192
+ """How an LDAPS / StartTLS connection checks the directory server: its certificate
193
+ must chain to a CA this system trusts (its CA bundle; Windows: its certificate
194
+ store) — or, with ca_file set, to a certificate in that file only (PEM, or DER as
195
+ Windows exports it) — and name the host of the server URI (OpenSSL's check, for DNS
196
+ names and IP addresses alike). tls_verify off: no check at all (insecure). Raises
197
+ CaFileError."""
198
+ if not settings.tls_verify:
199
+ ctx = ssl.create_default_context()
200
+ ctx.check_hostname = False
201
+ ctx.verify_mode = ssl.CERT_NONE
202
+ return ctx
203
+ path = settings.ca_file.strip()
204
+ if not path:
205
+ return ssl.create_default_context()
206
+ try:
207
+ with open(path, "rb") as fh:
208
+ data = fh.read()
209
+ except OSError as e:
210
+ raise CaFileError(path, f"can't read it: {e.strerror or e}", True) from None
211
+ trusted: ssl.SSLContext | None = None
212
+ try: # PEM through OpenSSL's reader (several certificates, comments), else DER
213
+ if b"-----BEGIN" in data:
214
+ trusted = ssl.create_default_context(cafile=path)
215
+ elif data.strip(): # (empty cadata would mean the system's CAs)
216
+ trusted = ssl.create_default_context(cadata=data)
217
+ except (ssl.SSLError, ValueError, OSError):
218
+ trusted = None
219
+ if trusted is None or not trusted.cert_store_stats()["x509"]:
220
+ raise CaFileError(path, "it holds no certificate (PEM or DER)", False)
221
+ return trusted
222
+
223
+
224
+ def _tls(settings, ldap3):
225
+ """The ldap3 Tls for both LDAPS and StartTLS: the handshake runs with tls_context()
226
+ and the host of the server URI, so Python's own certificate and host-name check
227
+ applies (ldap3 2.9.1's default Tls checks nothing, its optional check rejects IP
228
+ addresses on Python 3.12+) and SNI is sent."""
229
+ context = tls_context(settings)
230
+ base: Any = ldap3.Tls
231
+
232
+ class VerifyingTls(base):
233
+ def wrap_socket(self, connection, do_handshake=False):
234
+ connection.socket = context.wrap_socket(
235
+ connection.socket, server_side=False, do_handshake_on_connect=do_handshake,
236
+ server_hostname=connection.server.host)
237
+
238
+ return VerifyingTls(validate=ssl.CERT_REQUIRED if settings.tls_verify else ssl.CERT_NONE)
239
+
240
+
241
+ _VERIFY_FAILED = re.compile(r"certificate verify failed: (.+?)(?: \(_ssl\.c:\d+\)|$)")
242
+ _RECOVERY = ("Local accounts still sign in; if no admin can, `ser2netweb --set-password NAME` "
243
+ "with a new NAME creates a local admin account.")
244
+ _INSECURE = ("Not checking the certificate (ldap.tls_verify: false) is insecure: anyone on "
245
+ "the network between ser2netweb and the directory could read the passwords.")
246
+
247
+
248
+ def tls_failure(exc) -> str | None:
249
+ """OpenSSL's reason for refusing the server's certificate, from what a failed
250
+ connection raised, or None if it wasn't that. ldap3 re-raises the ssl error as its
251
+ own exception whose text is the repr of the original's arguments (quotes escaped),
252
+ for a host with several addresses one per address in its args."""
253
+ texts, todo, seen = [], [exc], set()
254
+ while todo:
255
+ e = todo.pop()
256
+ if id(e) in seen:
257
+ continue
258
+ seen.add(id(e))
259
+ if isinstance(e, (list, tuple)):
260
+ todo.extend(e)
261
+ elif isinstance(e, BaseException):
262
+ texts.append(str(e))
263
+ todo.extend([*e.args, e.__cause__, e.__context__])
264
+ for text in sorted(texts, key=lambda t: t.count("\\")): # the least escaped first
265
+ if m := _VERIFY_FAILED.search(text):
266
+ return m.group(1).replace("\\", "").strip() # no backslash in these reasons
267
+ return None
268
+
269
+
270
+ @dataclass
271
+ class TlsProblem:
272
+ """Why an LDAPS / StartTLS connection to the directory failed before anything was
273
+ sent over it: the certificate is not trusted ("certificate"), it was issued for
274
+ another name ("name"), or ca_file can't be used ("ca_file")."""
275
+ kind: str
276
+ reason: str # OpenSSL's reason, or what is wrong with the CA file
277
+ uri: str
278
+ ca_file: str = ""
279
+ unreadable: bool = False # kind ca_file: can't be read (else: no certificate in it)
280
+
281
+ def __str__(self) -> str:
282
+ """The all.log line: what failed and what to set."""
283
+ if self.kind == "ca_file":
284
+ return (f"LDAP: the CA certificate file {self.ca_file!r} (ldap.ca_file) can't be "
285
+ f"used: {self.reason}, so LDAP sign-in over LDAPS / StartTLS fails until "
286
+ f"it is corrected in Settings → LDAP / Active Directory. {_RECOVERY}")
287
+ head = (f"LDAP: the certificate of the directory server {self.uri} was not accepted "
288
+ f"({self.reason}), so LDAP sign-in fails until this is fixed (nothing was "
289
+ f"sent over that connection)")
290
+ if self.kind == "name":
291
+ fix = (": it was issued for another name. Use a name it was issued for in the "
292
+ "server URI (an IP address works only if the certificate lists that "
293
+ "address).")
294
+ elif self.ca_file:
295
+ fix = (f". The CA certificate file {self.ca_file!r} (ldap.ca_file) has to hold the "
296
+ f"certificate of the CA that issued it (PEM or DER).")
297
+ else:
298
+ fix = (". If the directory's certificates come from your own CA (Active Directory "
299
+ "Certificate Services) or are self-signed, set Settings → LDAP / Active "
300
+ "Directory → CA certificate file (ldap.ca_file in config.json) to that CA's "
301
+ "certificate (PEM or DER).")
302
+ return f"{head}{fix} {_INSECURE} {_RECOVERY}"
303
+
304
+
305
+ def _tls_problem(exc, settings) -> TlsProblem | None:
306
+ if isinstance(exc, CaFileError):
307
+ return TlsProblem("ca_file", exc.reason, settings.server_uri, exc.path, exc.unreadable)
308
+ reason = tls_failure(exc) if settings.uses_tls else None
309
+ if reason is None:
310
+ return None
311
+ name = reason.startswith(("Hostname mismatch", "IP address mismatch"))
312
+ return TlsProblem("name" if name else "certificate", reason, settings.server_uri,
313
+ settings.ca_file.strip())
314
+
315
+
316
+ def _result_text(result) -> str:
317
+ """An LDAP error answer for a log line: description (code): message; referrals."""
318
+ text = f"{result.get('description')} ({result['result']})"
319
+ if result.get("message"):
320
+ text += ": " + " ".join(str(result["message"]).split())
321
+ if result.get("referrals"):
322
+ # not followed over TLS (authenticate): that server's certificate would go unchecked
323
+ text += "; it refers to " + ", ".join(str(r) for r in result["referrals"])
324
+ return text
325
+
326
+
327
+ # ---------------- bind + group lookup (ldap3) ----------------
328
+ class DirectoryGroups(list[str]):
329
+ """The group DNs read for a user whose bind succeeded (authenticate).
330
+ lookup_failed tells "they are in no group" apart from "their groups could not be
331
+ read" (the reason is logged)."""
332
+ lookup_failed = False
333
+
334
+
335
+ def _values(entry, attr) -> list[str]:
336
+ try:
337
+ return [str(v) for v in entry[attr].values]
338
+ except Exception:
339
+ return []
340
+
341
+
342
+ def _dns_domain(dn: str) -> str:
343
+ """corp.local for DC=corp,DC=local or OU=Staff,DC=corp,DC=local."""
344
+ return ".".join(v for rdn in _split_dn(dn) or [] for t, v in rdn if t == "dc")
345
+
346
+
347
+ class _GroupLookup:
348
+ """Reads the groups of the user who signed in, over an ldap3 connection."""
349
+
350
+ def __init__(self, conn, settings, username, log, ldap3, escape):
351
+ self.conn, self.settings, self.username, self.log = conn, settings, username, log
352
+ self.ldap3, self.escape = ldap3, escape
353
+ self._root: dict[str, str] | None = None
354
+
355
+ def problem(self, what: str) -> None:
356
+ """Log why the groups could not be read, with the server's error, if any."""
357
+ r = getattr(self.conn, "result", None) or {}
358
+ if r.get("result"): # an error answer, not just "no such entry"
359
+ what += f" — {_result_text(r)}"
360
+ self.log(f"LDAP: bound as {self.username!r}, but their groups could not be read: "
361
+ f"{what}")
362
+
363
+ def root(self, attr: str) -> str:
364
+ """An attribute of the server's RootDSE: defaultNamingContext (Active Directory:
365
+ the DN of the server's domain) or configurationNamingContext."""
366
+ if self._root is None:
367
+ names = ("defaultNamingContext", "configurationNamingContext")
368
+ self.conn.search("", "(objectClass=*)", search_scope=self.ldap3.BASE,
369
+ attributes=list(names))
370
+ entry = self.conn.entries[0] if self.conn.entries else None
371
+ self._root = {n: (_values(entry, n) or [""])[0] for n in names} if entry else {}
372
+ return self._root.get(attr, "")
373
+
374
+ def netbios_domain(self, name: str) -> str:
375
+ """The DN of the forest's domain with this NetBIOS name (its crossRef), or ""."""
376
+ config = self.root("configurationNamingContext")
377
+ if not config:
378
+ return ""
379
+ # under CN=Partitions only the domains' crossRef objects have a nETBIOSName
380
+ self.conn.search("CN=Partitions," + config, f"(nETBIOSName={self.escape(name)})",
381
+ search_scope=self.ldap3.LEVEL, attributes=["nCName"])
382
+ entries = self.conn.entries
383
+ return (_values(entries[0], "nCName") or [""])[0] if len(entries) == 1 else ""
384
+
385
+ def direct(self, bind_name: str) -> DirectoryGroups:
386
+ """Groups of the account that bound as `bind_name` (direct bind)."""
387
+ groups = DirectoryGroups()
388
+ attr = self.settings.group_attr
389
+ try:
390
+ if _split_dn(bind_name): # a DN: read that entry
391
+ user_dn = bind_name
392
+ self.conn.search(user_dn, "(objectClass=*)", search_scope=self.ldap3.BASE,
393
+ attributes=[attr])
394
+ entry = self.conn.entries[0] if self.conn.entries else None
395
+ if entry is None:
396
+ self.problem(f"no entry {user_dn!r}")
397
+ else: # an AD sign-in name; not a DN, so not a search base
398
+ entry = self.find_account(bind_name)
399
+ user_dn = entry.entry_dn if entry is not None else ""
400
+ if entry is None:
401
+ groups.lookup_failed = True
402
+ return groups
403
+ groups.extend(_values(entry, attr))
404
+ if self.settings.nested_groups:
405
+ self.add_nested(groups, user_dn)
406
+ except Exception as e:
407
+ self.problem(f"{type(e).__name__}: {e}")
408
+ groups.lookup_failed = True
409
+ return groups
410
+
411
+ def find_account(self, bind_name: str):
412
+ """The entry of an AD sign-in name: user@domain by userPrincipalName (an account
413
+ without one also by sAMAccountName, when the base is that domain) under the user
414
+ search base, else the server's domain; DOMAIN\\user by sAMAccountName in that
415
+ domain (found by its NetBIOS name), under the user search base if it is in it.
416
+ None (logged) unless there is exactly one."""
417
+ search_base = self.settings.user_search_base.strip()
418
+ if "\\" in bind_name:
419
+ netbios, _sep, account = bind_name.partition("\\")
420
+ domain = self.netbios_domain(netbios)
421
+ if not domain:
422
+ self.problem(f"the directory names no domain {netbios!r} (crossRef)")
423
+ return None
424
+ base = search_base or domain
425
+ # by its DC= part: a child domain's DN is below its parent's DN
426
+ if fold(_dns_domain(base)) != fold(_dns_domain(domain)):
427
+ self.problem(f"the user search base {base!r} is not in the domain {netbios!r}")
428
+ return None
429
+ tries = [("sAMAccountName", account)]
430
+ elif "@" in bind_name:
431
+ base = search_base or self.root("defaultNamingContext")
432
+ if not base:
433
+ self.problem("no user search base is set and the server names no "
434
+ "defaultNamingContext")
435
+ return None
436
+ account, _at, suffix = bind_name.rpartition("@")
437
+ tries = [("userPrincipalName", bind_name)]
438
+ if fold(suffix) == fold(_dns_domain(base)): # the implicit UPN: account@domain
439
+ tries.append(("sAMAccountName", account))
440
+ else:
441
+ self.problem(f"{bind_name!r} is no DN, user@domain or DOMAIN\\user name")
442
+ return None
443
+ for attr, value in tries:
444
+ self.conn.search(base, f"({attr}={self.escape(value)})",
445
+ attributes=[self.settings.group_attr])
446
+ entries = self.conn.entries
447
+ if len(entries) > 1:
448
+ self.problem(f"{len(entries)} entries have {attr}={value} under {base!r}")
449
+ return None
450
+ if entries:
451
+ return entries[0]
452
+ self.problem(" or ".join(f"{a}={v}" for a, v in tries) + f" is not under {base!r}")
453
+ return None
454
+
455
+ def add_nested(self, groups: DirectoryGroups, user_dn: str) -> None:
456
+ """Add the groups the user is in through other groups (Active Directory's
457
+ LDAP_MATCHING_RULE_IN_CHAIN, searched in the whole domain)."""
458
+ try:
459
+ base = self.root("defaultNamingContext") or self.settings.user_search_base.strip()
460
+ if not base:
461
+ self.problem("nested groups: no base to search them in")
462
+ groups.lookup_failed = True
463
+ return
464
+ self.conn.search(base, f"(member:{IN_CHAIN_RULE}:={self.escape(user_dn)})",
465
+ attributes=[self.ldap3.NO_ATTRIBUTES])
466
+ if (getattr(self.conn, "result", None) or {}).get("result"):
467
+ self.problem(f"nested groups under {base!r}")
468
+ groups.lookup_failed = True
469
+ known = {fold(g) for g in groups}
470
+ for entry in self.conn.entries:
471
+ if fold(entry.entry_dn) not in known:
472
+ known.add(fold(entry.entry_dn))
473
+ groups.append(entry.entry_dn)
474
+ except Exception as e: # keep the direct groups
475
+ self.problem(f"nested groups: {type(e).__name__}: {e}")
476
+ groups.lookup_failed = True
477
+
478
+
479
+ def authenticate(settings, username: str, password: str, logger=None,
480
+ server=None, conn_factory=None, on_tls_problem=None) -> list[str] | None:
481
+ """Bind to LDAP as `username`/`password`; return the user's group DNs (a
482
+ DirectoryGroups) on success or None on failure. Never raises on a bad bind.
483
+ `server`/`conn_factory` are injection points for tests (an ldap3 MOCK_SYNC
484
+ server). Returns None if ldap3 is missing or fails to import (logged). A refused
485
+ server certificate (or an unusable ca_file) is logged with what to set and passed
486
+ to on_tls_problem(TlsProblem)."""
487
+ log = logger or (lambda _m: None)
488
+ if not username or not password: # empty password must not become an anonymous bind
489
+ return None
490
+ try:
491
+ import ldap3
492
+ from ldap3.utils.conv import escape_filter_chars
493
+ from ldap3.utils.dn import escape_rdn
494
+ except Exception as e: # not only ImportError: never a 500 for the sign-in
495
+ log(f"LDAP login disabled: {optional.problem(e, 'ldap3')}")
496
+ return None
497
+
498
+ def _default_factory(srv, user, pw):
499
+ ab = ldap3.AUTO_BIND_TLS_BEFORE_BIND if settings.start_tls else ldap3.AUTO_BIND_NO_TLS
500
+ # over TLS, ldap3 would follow a referral to another server (with these
501
+ # credentials) without checking its certificate, or in plain text: it doesn't
502
+ return ldap3.Connection(srv, user=user, password=pw, auto_bind=ab,
503
+ auto_referrals=not settings.uses_tls)
504
+
505
+ def _unbind(conn) -> None:
506
+ with contextlib.suppress(Exception):
507
+ conn.unbind()
508
+
509
+ factory = conn_factory or _default_factory
510
+ try:
511
+ if server is None:
512
+ # connect_timeout so a dead/unreachable directory fails the login fast
513
+ # instead of hanging the worker thread on the OS socket timeout
514
+ server = ldap3.Server(settings.server_uri, get_info=ldap3.NONE, connect_timeout=5,
515
+ use_ssl=settings.server_uri.lower().startswith("ldaps"),
516
+ tls=_tls(settings, ldap3) if settings.uses_tls else None)
517
+ if settings.user_dn_template.strip():
518
+ # direct bind: the supplied credentials bind as the templated DN (or AD
519
+ # sign-in name: {username}@corp.local, CORP\{username})
520
+ bind_name = settings.user_dn_template.format(username=escape_rdn(username))
521
+ conn = factory(server, bind_name, password)
522
+ try:
523
+ return _GroupLookup(conn, settings, username, log, ldap3,
524
+ escape_filter_chars).direct(bind_name)
525
+ finally:
526
+ _unbind(conn)
527
+ # search+bind: bind as the service account, find the user, then bind as them
528
+ svc = factory(server, settings.bind_dn, settings.bind_password)
529
+ try:
530
+ flt = settings.user_search_filter.format(username=escape_filter_chars(username))
531
+ svc.search(settings.user_search_base, flt, attributes=[settings.group_attr])
532
+ if not svc.entries:
533
+ r = getattr(svc, "result", None) or {}
534
+ if r.get("result"): # an error answer, not just "no such user"
535
+ log(f"LDAP: the user search under {settings.user_search_base!r} failed — "
536
+ f"{_result_text(r)}")
537
+ return None
538
+ entry = svc.entries[0]
539
+ user_dn = entry.entry_dn
540
+ groups = DirectoryGroups(_values(entry, settings.group_attr))
541
+ _unbind(factory(server, user_dn, password)) # verify the password
542
+ if settings.nested_groups:
543
+ _GroupLookup(svc, settings, username, log, ldap3,
544
+ escape_filter_chars).add_nested(groups, user_dn)
545
+ return groups
546
+ finally:
547
+ _unbind(svc)
548
+ except Exception as e: # bad bind / server error -> denied, never crash the login
549
+ problem = _tls_problem(e, settings)
550
+ if problem is None: # not the name typed, which may be a password (login_post logs it)
551
+ log(f"LDAP authentication failed: {type(e).__name__}: {e}")
552
+ return None
553
+ log(str(problem))
554
+ if on_tls_problem is not None:
555
+ on_tls_problem(problem)
556
+ return None