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.
- ser2netweb/__init__.py +20 -0
- ser2netweb/__main__.py +6 -0
- ser2netweb/accounts.py +503 -0
- ser2netweb/cli.py +489 -0
- ser2netweb/clock.py +128 -0
- ser2netweb/config.py +4491 -0
- ser2netweb/console.py +181 -0
- ser2netweb/datalock.py +181 -0
- ser2netweb/engine/__init__.py +0 -0
- ser2netweb/engine/access.py +173 -0
- ser2netweb/engine/bindhint.py +115 -0
- ser2netweb/engine/bridge.py +1928 -0
- ser2netweb/engine/cluster.py +1140 -0
- ser2netweb/engine/modbus.py +530 -0
- ser2netweb/engine/modbus_gateway.py +1465 -0
- ser2netweb/engine/mqtt_pub.py +632 -0
- ser2netweb/engine/netguard.py +805 -0
- ser2netweb/engine/netinfo.py +199 -0
- ser2netweb/engine/portdiag.py +414 -0
- ser2netweb/engine/portlist.py +471 -0
- ser2netweb/engine/protocols/__init__.py +28 -0
- ser2netweb/engine/protocols/base.py +117 -0
- ser2netweb/engine/protocols/raw.py +12 -0
- ser2netweb/engine/protocols/rfc2217.py +586 -0
- ser2netweb/engine/protocols/telnet.py +172 -0
- ser2netweb/engine/serial_compat.py +598 -0
- ser2netweb/engine/serial_io.py +210 -0
- ser2netweb/engine/serial_link.py +414 -0
- ser2netweb/engine/sockopts.py +103 -0
- ser2netweb/engine/sparkplug.py +538 -0
- ser2netweb/engine/sparkplug_node.py +550 -0
- ser2netweb/engine/supervisor.py +533 -0
- ser2netweb/engine/tls.py +232 -0
- ser2netweb/envvars.py +57 -0
- ser2netweb/explain.py +117 -0
- ser2netweb/healthcheck.py +78 -0
- ser2netweb/i18n.py +110 -0
- ser2netweb/importer.py +550 -0
- ser2netweb/layout.py +118 -0
- ser2netweb/licences.py +86 -0
- ser2netweb/locale/tr.json +1569 -0
- ser2netweb/logsetup.py +253 -0
- ser2netweb/logtext.py +23 -0
- ser2netweb/notify.py +761 -0
- ser2netweb/optional.py +76 -0
- ser2netweb/reload.py +295 -0
- ser2netweb/runtime.py +762 -0
- ser2netweb/sdnotify.py +85 -0
- ser2netweb/ser2net_import.py +2001 -0
- ser2netweb/signins.py +98 -0
- ser2netweb/standalone.py +154 -0
- ser2netweb/state.py +1457 -0
- ser2netweb/storage.py +130 -0
- ser2netweb/textfold.py +51 -0
- ser2netweb/tlsreload.py +37 -0
- ser2netweb/watchdog.py +201 -0
- ser2netweb/web/__init__.py +0 -0
- ser2netweb/web/api.py +793 -0
- ser2netweb/web/auth.py +699 -0
- ser2netweb/web/certinfo.py +144 -0
- ser2netweb/web/httpguard.py +413 -0
- ser2netweb/web/ldap_auth.py +556 -0
- ser2netweb/web/oidc_auth.py +330 -0
- ser2netweb/web/proxy.py +398 -0
- ser2netweb/web/routes/__init__.py +78 -0
- ser2netweb/web/routes/cluster.py +669 -0
- ser2netweb/web/routes/common.py +359 -0
- ser2netweb/web/routes/console.py +451 -0
- ser2netweb/web/routes/forms.py +853 -0
- ser2netweb/web/routes/login.py +573 -0
- ser2netweb/web/routes/mappings.py +470 -0
- ser2netweb/web/routes/ops.py +374 -0
- ser2netweb/web/routes/settings.py +2135 -0
- ser2netweb/web/routes/system.py +308 -0
- ser2netweb/web/routes/totp.py +282 -0
- ser2netweb/web/selfsigned.py +129 -0
- ser2netweb/web/server.py +483 -0
- ser2netweb/web/static/app.css +327 -0
- ser2netweb/web/static/app.js +1102 -0
- ser2netweb/web/static/htmx.min.js +1 -0
- ser2netweb/web/static/points.js +218 -0
- ser2netweb/web/static/theme.js +7 -0
- ser2netweb/web/static/xterm-addon-fit.js +2 -0
- ser2netweb/web/static/xterm.css +218 -0
- ser2netweb/web/static/xterm.js +2 -0
- ser2netweb/web/templates/_cluster_body.html +109 -0
- ser2netweb/web/templates/_console.html +21 -0
- ser2netweb/web/templates/_footer.html +13 -0
- ser2netweb/web/templates/_login_notice.html +8 -0
- ser2netweb/web/templates/_macros.html +21 -0
- ser2netweb/web/templates/_mapping_form.html +477 -0
- ser2netweb/web/templates/_mapping_log.html +28 -0
- ser2netweb/web/templates/_mapping_traces.html +44 -0
- ser2netweb/web/templates/_mappings_body.html +149 -0
- ser2netweb/web/templates/_modbus_read.html +18 -0
- ser2netweb/web/templates/_ports_table.html +37 -0
- ser2netweb/web/templates/_serial_port_select.html +48 -0
- ser2netweb/web/templates/_shell.html +41 -0
- ser2netweb/web/templates/audit.html +55 -0
- ser2netweb/web/templates/base.html +77 -0
- ser2netweb/web/templates/dashboard.html +72 -0
- ser2netweb/web/templates/licenses.html +18 -0
- ser2netweb/web/templates/login.html +32 -0
- ser2netweb/web/templates/login_totp.html +23 -0
- ser2netweb/web/templates/settings.html +830 -0
- ser2netweb/web/templates/setup.html +43 -0
- ser2netweb/web/templates/totp.html +41 -0
- ser2netweb/web/totp.py +94 -0
- ser2netweb/winservice.py +1793 -0
- ser2netweb-3.0.0.dist-info/METADATA +120 -0
- ser2netweb-3.0.0.dist-info/RECORD +121 -0
- ser2netweb-3.0.0.dist-info/WHEEL +5 -0
- ser2netweb-3.0.0.dist-info/entry_points.txt +2 -0
- ser2netweb-3.0.0.dist-info/licenses/COMMERCIAL_LICENSE.md +94 -0
- ser2netweb-3.0.0.dist-info/licenses/LICENSE +662 -0
- ser2netweb-3.0.0.dist-info/licenses/NOTICE +20 -0
- ser2netweb-3.0.0.dist-info/licenses/THIRD-PARTY-NOTICES.md +105 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/htmx.org.txt +13 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm-addon-fit.txt +19 -0
- ser2netweb-3.0.0.dist-info/licenses/tools/licenses/npm/xterm.txt +21 -0
- ser2netweb-3.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
"""Sign-in pages: login/logout, first-run setup and OIDC single sign-on."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from starlette.responses import RedirectResponse
|
|
10
|
+
from starlette.routing import Route
|
|
11
|
+
|
|
12
|
+
from ... import notify
|
|
13
|
+
from ...config import (
|
|
14
|
+
AccountNameError, ConfigError, User, external_name, external_name_problem, fold,
|
|
15
|
+
new_pwd_version,
|
|
16
|
+
)
|
|
17
|
+
from ...engine import netguard, netinfo
|
|
18
|
+
from ...i18n import _
|
|
19
|
+
from .. import auth, ldap_auth, oidc_auth, proxy
|
|
20
|
+
from . import totp
|
|
21
|
+
from .common import Ctx, csrf_failed, local_path
|
|
22
|
+
from .forms import _password_problem, _username_problem
|
|
23
|
+
|
|
24
|
+
OIDC_COOKIE = "ser2net_oidc"
|
|
25
|
+
# The sign-in, first-run setup and sign-out forms are a few short fields: a larger request
|
|
26
|
+
# is refused (413) before it is read, a file or a long field (400) while it is.
|
|
27
|
+
FORM_MAX_BYTES = 64 * 1024
|
|
28
|
+
FORM_LIMITS = {"max_files": 0, "max_fields": 16, "max_part_size": 16 * 1024}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def routes(ctx: Ctx) -> list:
|
|
32
|
+
state, render, client_ip, set_session = ctx.state, ctx.render, ctx.client_ip, ctx.set_session
|
|
33
|
+
|
|
34
|
+
async def login_get(request):
|
|
35
|
+
# ?next=: the page to go back to (GuardMiddleware sends a page request without a
|
|
36
|
+
# session here with it; the dashboard's "session ended" link too)
|
|
37
|
+
return render(request, "login.html", error=None,
|
|
38
|
+
oidc_enabled=state.config.oidc.enabled,
|
|
39
|
+
next=local_path(request.query_params.get("next"), ""))
|
|
40
|
+
|
|
41
|
+
def _typed(form) -> str:
|
|
42
|
+
"""The user name a refused sign-in form had, to fill it in again: a retry that
|
|
43
|
+
re-types only the password must not go to 'admin' (the field's default)."""
|
|
44
|
+
return str(form.get("username") or "").strip()[:auth.LOGIN_NAME_MAX]
|
|
45
|
+
|
|
46
|
+
# ---------------- LDAP / OIDC groups -> role ----------------
|
|
47
|
+
# (source, user name) whose sessions a refused sign-in already ended, so that more
|
|
48
|
+
# refused tries don't save config.json (and push out a backup) each time; their next
|
|
49
|
+
# successful sign-in takes them off again. An LDAP name in any letter case is one
|
|
50
|
+
# person (AppConfig.external_accounts).
|
|
51
|
+
refused: set[tuple[str, str]] = set()
|
|
52
|
+
|
|
53
|
+
def _person(source: str, username: str) -> tuple[str, str]:
|
|
54
|
+
return source, fold(username) if source == "ldap" else username
|
|
55
|
+
|
|
56
|
+
def _directory_role(source: str, username: str, groups, settings) -> str | None:
|
|
57
|
+
"""The role the groups reported by the directory (LDAP) or the identity provider
|
|
58
|
+
(OIDC) give `username`. Logs which groups they have when no group setting
|
|
59
|
+
matched, and warns when a setting matched one only as part of its name."""
|
|
60
|
+
name = source.upper()
|
|
61
|
+
d = ldap_auth.role_decision(groups, settings)
|
|
62
|
+
if d.partial is not None:
|
|
63
|
+
_warn_partial(source, username, d)
|
|
64
|
+
if not d.setting:
|
|
65
|
+
why = ("their groups could not be read (see above)"
|
|
66
|
+
if getattr(groups, "lookup_failed", False) else
|
|
67
|
+
f"no group setting matches their groups: {ldap_auth.group_names(groups)}")
|
|
68
|
+
if d.role:
|
|
69
|
+
state.log(f"{name} login for {username!r}: {why}; default role {d.role}")
|
|
70
|
+
else:
|
|
71
|
+
state.log(f"{name} login denied for {username!r}: {why}")
|
|
72
|
+
return d.role
|
|
73
|
+
|
|
74
|
+
def _warn_partial(source: str, username: str, d: ldap_auth.RoleDecision) -> None:
|
|
75
|
+
if d.partial is None:
|
|
76
|
+
return
|
|
77
|
+
setting, value, group = d.partial
|
|
78
|
+
section, whole = (("LDAP / Active Directory", "its full DN") if source == "ldap" else
|
|
79
|
+
("Single sign-on (OIDC)", "the whole value"))
|
|
80
|
+
state.log(f"WARNING: {source.upper()} {setting} {value!r} is only part of the name of "
|
|
81
|
+
f"the group {group!r}, which no longer counts as a match: {username!r} gets "
|
|
82
|
+
f"{d.role or 'no access'} instead of {d.partial_role}. A group setting has to "
|
|
83
|
+
f"name the whole group: set it to {ldap_auth.group_name(group)!r} or {whole} "
|
|
84
|
+
f"under Settings → {section} ({source}.{setting} in config.json). If no "
|
|
85
|
+
f"admin can sign in any more, `ser2netweb --set-password NAME` with a new NAME "
|
|
86
|
+
f"creates a local admin account.")
|
|
87
|
+
state.group_warnings[(source, setting)] = {
|
|
88
|
+
"setting": setting, "value": value, "group": group,
|
|
89
|
+
"name": ldap_auth.group_name(group), "user": username, "got": d.role or "",
|
|
90
|
+
"was": d.partial_role, "time": time.strftime("%Y-%m-%d %H:%M")}
|
|
91
|
+
|
|
92
|
+
def _note_tls_problem(problem: ldap_auth.TlsProblem) -> None:
|
|
93
|
+
"""A sign-in found the directory server's certificate refused (or ldap.ca_file
|
|
94
|
+
unusable): Settings → LDAP shows it until that section is saved or a directory
|
|
95
|
+
sign-in works. Runs in the sign-in's worker thread."""
|
|
96
|
+
state.ldap_tls_problem = {"kind": problem.kind, "reason": problem.reason,
|
|
97
|
+
"uri": problem.uri, "ca_file": problem.ca_file,
|
|
98
|
+
"unreadable": problem.unreadable,
|
|
99
|
+
"time": time.strftime("%Y-%m-%d %H:%M")}
|
|
100
|
+
|
|
101
|
+
async def _end_refused_sessions(source: str, username: str) -> None:
|
|
102
|
+
"""The directory or identity provider confirmed who this is, but their groups
|
|
103
|
+
give no role any more: end the sessions their shadow account still has, which
|
|
104
|
+
would otherwise keep the role saved with it until they expire."""
|
|
105
|
+
if _person(source, username) in refused:
|
|
106
|
+
return
|
|
107
|
+
accounts = []
|
|
108
|
+
try:
|
|
109
|
+
async with state.edit_config(keep_on_failure=True): # ended in memory anyway
|
|
110
|
+
accounts = state.config.external_accounts(username, source)
|
|
111
|
+
for user in accounts:
|
|
112
|
+
user.pwd_version += 1
|
|
113
|
+
except ConfigError as e: # still ended in memory, until a restart
|
|
114
|
+
state.log(f"could not save the sign-out of {username!r}: {e}")
|
|
115
|
+
if not accounts:
|
|
116
|
+
return
|
|
117
|
+
refused.add(_person(source, username))
|
|
118
|
+
state.log(f"{source.upper()}: {username!r} signed out everywhere: their groups give "
|
|
119
|
+
f"no role any more")
|
|
120
|
+
|
|
121
|
+
def _record_failure(ip: str, user: str, source: str = "", reason: str = "",
|
|
122
|
+
action: str = "login_failed", detail: str = "") -> None:
|
|
123
|
+
"""The audit record (bounded: state.failed_logins) and the notification of a
|
|
124
|
+
failed or refused sign-in (notify.sign_in_detail: personal data left out there
|
|
125
|
+
when Settings -> Notifications says so)."""
|
|
126
|
+
state.failed_logins.add(ip, user, action, detail)
|
|
127
|
+
state.notifier.emit("login_failed", ip, "", notify.sign_in_detail(
|
|
128
|
+
state.config.notifications, user, ip, source, reason))
|
|
129
|
+
|
|
130
|
+
def _oidc_failed(request, reason: str, user: str = "") -> None:
|
|
131
|
+
"""An SSO sign-in that came back from the identity provider and failed: recorded
|
|
132
|
+
(oidc_login_failed, with a short reason; all.log has the details) and notified
|
|
133
|
+
like a failed local or LDAP sign-in."""
|
|
134
|
+
_record_failure(client_ip(request), user, "OIDC", reason, "oidc_login_failed", reason)
|
|
135
|
+
|
|
136
|
+
def _name_refused(request, source: str, username: str) -> str | None:
|
|
137
|
+
"""A sign-in through the directory (LDAP) or the identity provider (OIDC) that
|
|
138
|
+
can't have an account under this name is refused: the name of a local account or
|
|
139
|
+
of one of the other sign-in method, letter case aside — such a sign-in must never
|
|
140
|
+
take over, convert or demote that account (upsert_external_user refuses it too) —
|
|
141
|
+
or a name no account can have (external_name_problem). Logged, audited (within
|
|
142
|
+
the failed sign-ins' limit) and notified like a failed sign-in. Returns the
|
|
143
|
+
sign-in page's message, or None when the name can be used."""
|
|
144
|
+
taken = state.config.taken_name(username, source)
|
|
145
|
+
why = (f"the {taken.kind} account {taken.username!r} has this name" if taken
|
|
146
|
+
else external_name_problem(username))
|
|
147
|
+
if why is None:
|
|
148
|
+
return None
|
|
149
|
+
ip, what = client_ip(request), source.upper()
|
|
150
|
+
if taken:
|
|
151
|
+
other = ("a local account" if taken.source == "local"
|
|
152
|
+
else "an account of another sign-in method")
|
|
153
|
+
state.log(f"{what} login denied for {username!r}: {why}, and an {what} sign-in "
|
|
154
|
+
f"never takes over {other}. To let them sign in with {what}, delete the "
|
|
155
|
+
f"{taken.kind} account in Settings → Users (another admin must remain).")
|
|
156
|
+
else:
|
|
157
|
+
hint = ("; Settings → Single sign-on (OIDC) → Username claim can name another "
|
|
158
|
+
"claim" if source == "oidc" else "")
|
|
159
|
+
state.log(f"{what} login denied for {username!r}: no account can have this name "
|
|
160
|
+
f"here: {why}{hint}")
|
|
161
|
+
_record_failure(ip, username, what,
|
|
162
|
+
f"the name of a {taken.kind} account" if taken else why,
|
|
163
|
+
f"{source}_login_denied",
|
|
164
|
+
f"{taken.kind} account {taken.username}" if taken else why)
|
|
165
|
+
if taken and taken.source == "local":
|
|
166
|
+
return _("There is a local account named {0} here, so you can't sign in under that "
|
|
167
|
+
"name with SSO or a directory account. Sign in with that account’s "
|
|
168
|
+
"password, or ask an admin to delete the local account first.").format(
|
|
169
|
+
taken.username)
|
|
170
|
+
if taken:
|
|
171
|
+
return _("An account named {0} here signs in another way (through the directory or "
|
|
172
|
+
"SSO), so you can't sign in under that name like this. Ask an admin to "
|
|
173
|
+
"delete that account first.").format(taken.username)
|
|
174
|
+
return _("Your user name from the directory or the identity provider can’t be used "
|
|
175
|
+
"here; an admin can see why in all.log.")
|
|
176
|
+
|
|
177
|
+
def _refusal_page(request, source: str, message: str | None, username: str = "",
|
|
178
|
+
nxt: str = ""):
|
|
179
|
+
if source == "oidc":
|
|
180
|
+
return render(request, "login.html", status_code=403, error=None, oidc_enabled=True,
|
|
181
|
+
oidc_error=message)
|
|
182
|
+
return render(request, "login.html", status_code=403, error=message,
|
|
183
|
+
oidc_enabled=state.config.oidc.enabled, username=username, next=nxt)
|
|
184
|
+
|
|
185
|
+
async def _save_external(source: str, username: str, role: str) -> User | None:
|
|
186
|
+
"""The saved shadow account of an LDAP/OIDC user who signed in; None when a local
|
|
187
|
+
account got this name while the sign-in waited for the lock. The directory decides
|
|
188
|
+
the role, also when it takes the last admin role away (refusing that would keep
|
|
189
|
+
a removed admin's rights): that is logged as a warning."""
|
|
190
|
+
before = state.config.usable_admin_count()
|
|
191
|
+
user = None
|
|
192
|
+
try:
|
|
193
|
+
# saved only when the account changed (a repeated sign-in writes nothing); used
|
|
194
|
+
# even when it can't be saved: the sign-in goes on, and it is made again later
|
|
195
|
+
async with state.edit_config(keep_on_failure=True):
|
|
196
|
+
before = state.config.usable_admin_count()
|
|
197
|
+
user = state.config.upsert_external_user(username, role, source)
|
|
198
|
+
except AccountNameError:
|
|
199
|
+
return None
|
|
200
|
+
except ConfigError as e:
|
|
201
|
+
state.log(f"WARNING: {source.upper()}: could not save the account of "
|
|
202
|
+
f"{username!r} ({e}); they are signed in, but it is made again at their "
|
|
203
|
+
f"next sign-in after a restart")
|
|
204
|
+
if user is None: # (upsert_external_user returns the account or raises)
|
|
205
|
+
return None
|
|
206
|
+
if before and not state.config.usable_admin_count():
|
|
207
|
+
state.log(f"WARNING: {source.upper()} gives {user.username!r} the role {role}, so "
|
|
208
|
+
f"no admin account can sign in any more. `ser2netweb --set-password "
|
|
209
|
+
f"NAME` with a new NAME creates a local admin account.")
|
|
210
|
+
return user
|
|
211
|
+
|
|
212
|
+
# ---------------- OIDC single sign-on ----------------
|
|
213
|
+
async def oidc_login(request):
|
|
214
|
+
oidc = state.config.oidc
|
|
215
|
+
if not oidc.enabled:
|
|
216
|
+
return proxy.redirect(request, "/login")
|
|
217
|
+
redirect_uri = oidc_auth.redirect_uri(oidc, request,
|
|
218
|
+
proxy.public_url(state.config.admin_ui))
|
|
219
|
+
st, nonce = secrets.token_urlsafe(16), secrets.token_urlsafe(16)
|
|
220
|
+
verifier = oidc_auth.new_code_verifier() # PKCE
|
|
221
|
+
try:
|
|
222
|
+
url = await asyncio.to_thread(oidc_auth.build_authorize_url, oidc, redirect_uri, st,
|
|
223
|
+
nonce, code_verifier=verifier)
|
|
224
|
+
except oidc_auth.InsecureEndpoint as e:
|
|
225
|
+
state.log(f"OIDC login init failed: {e}")
|
|
226
|
+
return render(request, "login.html", status_code=502, error=None, oidc_enabled=True,
|
|
227
|
+
oidc_error=_("SSO sign-in is off: the identity provider gives an "
|
|
228
|
+
"address that isn’t https:// (all.log says which)."))
|
|
229
|
+
except Exception as e:
|
|
230
|
+
state.log(f"OIDC login init failed: {e}")
|
|
231
|
+
return render(request, "login.html", status_code=502, error=None,
|
|
232
|
+
oidc_enabled=True, oidc_error=_("SSO provider is unreachable."))
|
|
233
|
+
# the address the provider sends the browser back to, which it must have registered:
|
|
234
|
+
# when it refuses it, the user stays on the provider's error page
|
|
235
|
+
state.log(f"OIDC login init from {client_ip(request)}: redirect URI {redirect_uri!r}"
|
|
236
|
+
+ ("" if oidc.redirect_uri.strip() else
|
|
237
|
+
" (made from the request; Settings → Single sign-on (OIDC) shows it)"))
|
|
238
|
+
resp = RedirectResponse(url, status_code=303)
|
|
239
|
+
# "x": the page to go back to after the sign-in (?next=, as for a password sign-in)
|
|
240
|
+
payload = {"s": st, "n": nonce, "r": redirect_uri, "v": verifier}
|
|
241
|
+
if nxt := local_path(request.query_params.get("next"), ""):
|
|
242
|
+
payload["x"] = nxt
|
|
243
|
+
auth.set_cookie(resp, request, state.config, OIDC_COOKIE,
|
|
244
|
+
auth.sign_payload(state.config.secret_key, payload, ttl_seconds=600),
|
|
245
|
+
max_age=600, path="/auth/oidc")
|
|
246
|
+
return resp
|
|
247
|
+
|
|
248
|
+
def _same(given: str, expected) -> bool:
|
|
249
|
+
"""The state from the URL is the one in the signed cookie (compared as bytes: a
|
|
250
|
+
str with non-ASCII text would make compare_digest raise)."""
|
|
251
|
+
return secrets.compare_digest(given.encode(), str(expected or "").encode())
|
|
252
|
+
|
|
253
|
+
def _provider_error(request, data, error: str):
|
|
254
|
+
"""The provider sent the browser back with an error instead of a code (RFC 6749
|
|
255
|
+
4.1.2.1, OIDC Core 3.1.2.6): logged with its description, shown by its code —
|
|
256
|
+
never the provider's own text."""
|
|
257
|
+
st = request.query_params.get("state", "")
|
|
258
|
+
ours = bool(data) and _same(st, data.get("s"))
|
|
259
|
+
desc = request.query_params.get("error_description", "")
|
|
260
|
+
state.log(f"OIDC: the identity provider refused the sign-in: {error[:64]!r}"
|
|
261
|
+
+ (f" ({desc[:200]!r})" if desc else "")
|
|
262
|
+
+ ("" if ours else " (not for a sign-in started in this browser)"))
|
|
263
|
+
code = error if re.fullmatch(r"[a-z0-9_]{1,64}", error) else "?"
|
|
264
|
+
_oidc_failed(request, f"the identity provider refused it ({code})"
|
|
265
|
+
+ ("" if ours else ", not for a sign-in started in this browser"))
|
|
266
|
+
if error == "access_denied":
|
|
267
|
+
status, message = 403, _("The identity provider didn’t let you sign in to ser2netweb. "
|
|
268
|
+
"Ask its administrator to give your account access.")
|
|
269
|
+
elif error in ("temporarily_unavailable", "server_error"):
|
|
270
|
+
status, message = 503, _("The identity provider can’t sign you in right now. Try "
|
|
271
|
+
"again in a few minutes.")
|
|
272
|
+
else:
|
|
273
|
+
status, message = 400, _("The identity provider refused the sign-in request ({0}). "
|
|
274
|
+
"An admin should check the SSO settings; all.log has "
|
|
275
|
+
"the details.").format(code)
|
|
276
|
+
return render(request, "login.html", status_code=status, error=None, oidc_enabled=True,
|
|
277
|
+
oidc_error=message)
|
|
278
|
+
|
|
279
|
+
async def oidc_callback(request):
|
|
280
|
+
oidc = state.config.oidc
|
|
281
|
+
if not oidc.enabled:
|
|
282
|
+
return proxy.redirect(request, "/login")
|
|
283
|
+
stash = auth.cookie(request, OIDC_COOKIE, path="/auth/oidc")
|
|
284
|
+
data = auth.read_payload(state.config.secret_key, stash)
|
|
285
|
+
if (error := request.query_params.get("error")) is not None:
|
|
286
|
+
return _provider_error(request, data, error)
|
|
287
|
+
code = request.query_params.get("code", "")
|
|
288
|
+
st = request.query_params.get("state", "")
|
|
289
|
+
if (not data or not code or not _same(st, data.get("s"))
|
|
290
|
+
or not isinstance(data.get("r"), str) or not isinstance(data.get("n"), str)):
|
|
291
|
+
_oidc_failed(request, "the answer doesn't match a sign-in started in this browser"
|
|
292
|
+
+ (" (none, or it took over 10 minutes)" if not data else ""))
|
|
293
|
+
return render(request, "login.html", status_code=400, error=None, oidc_enabled=True,
|
|
294
|
+
oidc_error=_("SSO state mismatch — please try again."))
|
|
295
|
+
# "v": the PKCE verifier (a state cookie from before it was sent has none)
|
|
296
|
+
claims = await asyncio.to_thread(oidc_auth.complete, oidc, data["r"], code, data["n"],
|
|
297
|
+
state.log, code_verifier=str(data.get("v") or ""))
|
|
298
|
+
if claims is None:
|
|
299
|
+
_oidc_failed(request, "the code or the ID token was refused (all.log says why)")
|
|
300
|
+
return render(request, "login.html", status_code=401, error=None, oidc_enabled=True,
|
|
301
|
+
oidc_error=_("SSO sign-in failed."))
|
|
302
|
+
username = oidc_auth.username_from_claims(claims, oidc)
|
|
303
|
+
if not username:
|
|
304
|
+
state.log(f"OIDC login denied: {oidc_auth.no_username_reason(claims, oidc)}")
|
|
305
|
+
_oidc_failed(request, "no user name in the ID token (all.log says why)")
|
|
306
|
+
elif refusal := _name_refused(request, "oidc", username):
|
|
307
|
+
return _refusal_page(request, "oidc", refusal)
|
|
308
|
+
role = username and _directory_role("oidc", username,
|
|
309
|
+
oidc_auth.groups_from_claims(claims, oidc), oidc)
|
|
310
|
+
if not username or not role:
|
|
311
|
+
if username:
|
|
312
|
+
_oidc_failed(request, "their groups give no role", username)
|
|
313
|
+
await _end_refused_sessions("oidc", username)
|
|
314
|
+
return render(request, "login.html", status_code=403, error=None, oidc_enabled=True,
|
|
315
|
+
oidc_error=_("Your account isn't mapped to a role."))
|
|
316
|
+
user = await _save_external("oidc", username, role)
|
|
317
|
+
if user is None: # a local account got the name meanwhile
|
|
318
|
+
return _refusal_page(request, "oidc", _name_refused(request, "oidc", username))
|
|
319
|
+
refused.discard(_person("oidc", username))
|
|
320
|
+
state.log(f"login: {user.username} ({role}, oidc) from {client_ip(request)}")
|
|
321
|
+
ctx.audit(request, "oidc_login", user.username, user=user.username)
|
|
322
|
+
# a state cookie from before 2.9 has no "x": the dashboard
|
|
323
|
+
resp = proxy.redirect(request, local_path(data.get("x")))
|
|
324
|
+
set_session(resp, request, user)
|
|
325
|
+
ctx.new_csrf_token(request)
|
|
326
|
+
auth.delete_cookie(resp, request, state.config, OIDC_COOKIE, path="/auth/oidc")
|
|
327
|
+
return resp
|
|
328
|
+
|
|
329
|
+
# sign-ins not tried because too many were being checked already: logged once a minute
|
|
330
|
+
busy_note = netguard.LogEvery(lambda msg: state.log(msg))
|
|
331
|
+
|
|
332
|
+
def _note_name_paused(label: str, username: str) -> None:
|
|
333
|
+
"""Log when failed attempts (from any address) pause sign-ins under a name: that is
|
|
334
|
+
what keeps someone guessing one account's password from many addresses below the
|
|
335
|
+
directory's own lock-out."""
|
|
336
|
+
lim = state.name_limiter
|
|
337
|
+
if lim.blocked(username):
|
|
338
|
+
name = "a name that is no account's" if label == auth.UNKNOWN_USER else repr(label)
|
|
339
|
+
state.log(f"sign-ins under {name} are refused for now: {lim.max_attempts} "
|
|
340
|
+
f"failed in {lim.window_s // 60} minutes (from any address)")
|
|
341
|
+
|
|
342
|
+
def _is_account_name(name: str) -> bool:
|
|
343
|
+
"""Is `name` an account's (letter case aside)? Only then does a failed sign-in
|
|
344
|
+
record the name typed."""
|
|
345
|
+
folded = name.casefold()
|
|
346
|
+
return any(u.username.casefold() == folded for u in state.config.users)
|
|
347
|
+
|
|
348
|
+
async def _renew_hash(user: User, password: str) -> None:
|
|
349
|
+
"""A local account's password hash from an older version (a lower scrypt cost) is
|
|
350
|
+
made again with today's cost once its password has been checked. Best effort:
|
|
351
|
+
the sign-in works even when this can't be saved (it is tried again at the next
|
|
352
|
+
one), and the account's sessions stay (pwd_version is unchanged)."""
|
|
353
|
+
if state.password_work.busy():
|
|
354
|
+
return
|
|
355
|
+
old = user.password_hash
|
|
356
|
+
new = await state.password_work.run(auth.hash_password, password)
|
|
357
|
+
async with state.config_lock:
|
|
358
|
+
if state.config.get_user(user.username) is not user or user.password_hash != old:
|
|
359
|
+
return # changed meanwhile
|
|
360
|
+
user.password_hash = new
|
|
361
|
+
try: # only this hash changes: an unrelated setting must not stop it
|
|
362
|
+
await asyncio.to_thread(state.store.save, state.config, validate=False)
|
|
363
|
+
except OSError as e:
|
|
364
|
+
user.password_hash = old
|
|
365
|
+
state.log(f"could not save the renewed password hash of {user.username!r}: {e}")
|
|
366
|
+
return
|
|
367
|
+
state.log(f"the password hash of {user.username!r} was renewed with today's scrypt cost")
|
|
368
|
+
|
|
369
|
+
def _too_many(request, typed: str, nxt: str):
|
|
370
|
+
return render(request, "login.html", status_code=429,
|
|
371
|
+
error=_("Too many attempts. Wait a few minutes and try again."),
|
|
372
|
+
oidc_enabled=state.config.oidc.enabled, username=typed, next=nxt)
|
|
373
|
+
|
|
374
|
+
def _login_failed(request, ip: str, username: str, typed: str, nxt: str):
|
|
375
|
+
"""Log, record and notify a failed sign-in (login_post counted it already); the
|
|
376
|
+
sign-in page again, with the name typed (`typed`) and the page to go back to
|
|
377
|
+
(`nxt`). A name that is no account's is recorded as auth.UNKNOWN_USER: what was
|
|
378
|
+
typed may well be a password."""
|
|
379
|
+
label = username if _is_account_name(username) else auth.UNKNOWN_USER
|
|
380
|
+
state.log(f"failed login for {label!r} from {ip}")
|
|
381
|
+
_record_failure(ip, label)
|
|
382
|
+
_note_name_paused(label, username)
|
|
383
|
+
return render(request, "login.html", status_code=401,
|
|
384
|
+
error=_("Invalid username or password."),
|
|
385
|
+
oidc_enabled=state.config.oidc.enabled, username=typed, next=nxt)
|
|
386
|
+
|
|
387
|
+
async def login_post(request):
|
|
388
|
+
ip = client_ip(request)
|
|
389
|
+
form = await request.form(**FORM_LIMITS)
|
|
390
|
+
if not auth.csrf_token_matches(request, form.get("_csrf")):
|
|
391
|
+
return csrf_failed()
|
|
392
|
+
typed = _typed(form)
|
|
393
|
+
nxt = local_path(form.get("next"), "") # the page to go back to (login_get)
|
|
394
|
+
if state.rate_limiter.blocked(ip):
|
|
395
|
+
return _too_many(request, typed, nxt)
|
|
396
|
+
# username defaults to "admin" so single-user (password-only) logins keep working
|
|
397
|
+
username = (form.get("username") or "admin").strip() or "admin"
|
|
398
|
+
password = form.get("password", "")
|
|
399
|
+
if len(username) > auth.LOGIN_NAME_MAX: # no account has such a name: not tried
|
|
400
|
+
state.rate_limiter.record_failure(ip)
|
|
401
|
+
return _login_failed(request, ip, username, typed, nxt)
|
|
402
|
+
if state.name_limiter.blocked(username): # from any address: that name only
|
|
403
|
+
return _too_many(request, typed, nxt)
|
|
404
|
+
user = state.config.get_user(username)
|
|
405
|
+
local = user is not None and user.source == "local"
|
|
406
|
+
directory = not local and state.config.ldap.enabled
|
|
407
|
+
work = state.directory_work if directory else state.password_work
|
|
408
|
+
if work.busy(): # not tried, not counted
|
|
409
|
+
busy_note(f"sign-in from {ip} not tried: {work.limit + work.queue} "
|
|
410
|
+
f"{'directory sign-ins' if directory else 'password checks'} are "
|
|
411
|
+
"running or waiting already")
|
|
412
|
+
return render(request, "login.html", status_code=429,
|
|
413
|
+
error=_("Too many sign-ins at the same time. Try again in a "
|
|
414
|
+
"moment."),
|
|
415
|
+
oidc_enabled=state.config.oidc.enabled, username=typed, next=nxt)
|
|
416
|
+
# counted as failed before the password is checked, in the same step as the checks
|
|
417
|
+
# above (no await between them): concurrent attempts can't all get past the limits
|
|
418
|
+
# while the first ones are still being checked. A sign-in that works resets them.
|
|
419
|
+
state.rate_limiter.record_failure(ip)
|
|
420
|
+
state.name_limiter.record_failure(username)
|
|
421
|
+
authed = None
|
|
422
|
+
# local account: verify the scrypt hash off the event loop (it's slow on purpose)
|
|
423
|
+
if local and user is not None:
|
|
424
|
+
if await work.run(auth.verify_password, password, user.password_hash):
|
|
425
|
+
authed = user
|
|
426
|
+
# LDAP/AD: for unknown users (or LDAP shadow accounts) when LDAP is enabled
|
|
427
|
+
elif directory:
|
|
428
|
+
username = external_name(username)
|
|
429
|
+
groups = await work.run(
|
|
430
|
+
ldap_auth.authenticate, state.config.ldap, username, password, state.log,
|
|
431
|
+
on_tls_problem=_note_tls_problem)
|
|
432
|
+
if groups is not None:
|
|
433
|
+
state.ldap_tls_problem = None # the connection to the directory works
|
|
434
|
+
if refusal := _name_refused(request, "ldap", username):
|
|
435
|
+
return _refusal_page(request, "ldap", refusal, typed, nxt)
|
|
436
|
+
role = _directory_role("ldap", username, groups, state.config.ldap)
|
|
437
|
+
if role:
|
|
438
|
+
authed = await _save_external("ldap", username, role)
|
|
439
|
+
if authed is None: # a local account got the name meanwhile
|
|
440
|
+
return _refusal_page(request, "ldap",
|
|
441
|
+
_name_refused(request, "ldap", username), typed,
|
|
442
|
+
nxt)
|
|
443
|
+
refused.discard(_person("ldap", username))
|
|
444
|
+
else:
|
|
445
|
+
await _end_refused_sessions("ldap", username)
|
|
446
|
+
else: # no such local account, no directory: the work of a wrong password
|
|
447
|
+
await work.run(auth.verify_password, password, auth.DUMMY_HASH)
|
|
448
|
+
if authed is not None and authed.totp_on: # the password alone is not enough
|
|
449
|
+
if local and auth.needs_rehash(authed.password_hash):
|
|
450
|
+
await _renew_hash(authed, password)
|
|
451
|
+
return totp.challenge(ctx, request, authed, nxt)
|
|
452
|
+
if authed is not None: # under its account's name (LDAP: in any letter case)
|
|
453
|
+
state.rate_limiter.reset(ip)
|
|
454
|
+
state.name_limiter.reset(authed.username)
|
|
455
|
+
if local and auth.needs_rehash(authed.password_hash):
|
|
456
|
+
await _renew_hash(authed, password)
|
|
457
|
+
state.log(f"login: {authed.username} ({authed.role}, {authed.source}) from {ip}")
|
|
458
|
+
ctx.audit(request, "login", f"{authed.role}, {authed.source}", user=authed.username)
|
|
459
|
+
resp = proxy.redirect(request, nxt or "/")
|
|
460
|
+
set_session(resp, request, authed)
|
|
461
|
+
ctx.new_csrf_token(request)
|
|
462
|
+
return resp
|
|
463
|
+
return _login_failed(request, ip, username, typed, nxt)
|
|
464
|
+
|
|
465
|
+
async def _sign_out_everywhere(username: str) -> None:
|
|
466
|
+
"""A logout the revocation list has no room for: end all of the account's
|
|
467
|
+
sessions instead (pwd_version + 1), which ends the copies of its cookies too."""
|
|
468
|
+
user = None
|
|
469
|
+
try:
|
|
470
|
+
async with state.edit_config(keep_on_failure=True): # ended in memory anyway
|
|
471
|
+
user = state.config.get_user(username)
|
|
472
|
+
if user is not None:
|
|
473
|
+
user.pwd_version += 1
|
|
474
|
+
except ConfigError as e: # still ended in memory, until a restart
|
|
475
|
+
state.log(f"could not save the sign-out of {username!r}: {e}")
|
|
476
|
+
if user is None:
|
|
477
|
+
return
|
|
478
|
+
state.revoked_sessions.forget(username)
|
|
479
|
+
state.log(f"{username!r} signed out everywhere: too many of its sessions were ended "
|
|
480
|
+
"by a logout to remember each one")
|
|
481
|
+
|
|
482
|
+
async def logout_post(request):
|
|
483
|
+
form = await request.form(**FORM_LIMITS)
|
|
484
|
+
if not auth.csrf_token_matches(request, form.get("_csrf")):
|
|
485
|
+
return csrf_failed()
|
|
486
|
+
# the cookie is a signed token: end it on the server too, so a copy of it is
|
|
487
|
+
# refused from now on (not just deleted in this browser)
|
|
488
|
+
token = auth.cookie(request, auth.SESSION_COOKIE)
|
|
489
|
+
full = state.revoked_sessions.add(state.config.secret_key, token)
|
|
490
|
+
if full is not None and auth.session_user(state.config, token) is not None:
|
|
491
|
+
await _sign_out_everywhere(full)
|
|
492
|
+
if not ctx.is_anonymous(request): # an open-access visitor had no session to end
|
|
493
|
+
ctx.audit(request, "logout")
|
|
494
|
+
resp = proxy.redirect(request, "/login")
|
|
495
|
+
auth.delete_cookie(resp, request, state.config, auth.SESSION_COOKIE)
|
|
496
|
+
ctx.new_csrf_token(request)
|
|
497
|
+
return resp
|
|
498
|
+
|
|
499
|
+
# ---------------- first-run setup ----------------
|
|
500
|
+
# Only while no account exists (GuardMiddleware sends everything here then). Like
|
|
501
|
+
# open access, it trusts a request only when every host name it claims is this
|
|
502
|
+
# machine's (auth.claims_own_host, the DNS-rebinding guard). Through another name
|
|
503
|
+
# (a reverse proxy, Docker's host name) the page asks for the one-time code that
|
|
504
|
+
# AppState.prepare_first_run wrote to setup-code.txt. No redirect: every path leads here.
|
|
505
|
+
def setup_page(request, status_code=200, error=None, username=""):
|
|
506
|
+
# username: the admin name a refused form had (accounts can't be renamed, so one
|
|
507
|
+
# that silently fell back to "admin" would stay so)
|
|
508
|
+
return render(request, "setup.html", status_code=status_code, error=error,
|
|
509
|
+
ips=netinfo.list_ip_candidates(), admin=state.config.admin_ui,
|
|
510
|
+
locked=state.setup_locked, need_code=not auth.claims_own_host(request.headers),
|
|
511
|
+
host=auth.foreign_host(request.headers), username=username)
|
|
512
|
+
|
|
513
|
+
async def setup_get(request):
|
|
514
|
+
trusted = auth.claims_own_host(request.headers) and not state.setup_locked
|
|
515
|
+
return setup_page(request, 200 if trusted else 403)
|
|
516
|
+
|
|
517
|
+
async def setup_post(request):
|
|
518
|
+
form = await request.form(**FORM_LIMITS)
|
|
519
|
+
if not auth.csrf_token_matches(request, form.get("_csrf")):
|
|
520
|
+
return csrf_failed()
|
|
521
|
+
if state.setup_locked:
|
|
522
|
+
return setup_page(request, status_code=403)
|
|
523
|
+
ip = client_ip(request)
|
|
524
|
+
typed = _typed(form)
|
|
525
|
+
if not auth.claims_own_host(request.headers):
|
|
526
|
+
if state.rate_limiter.blocked(ip):
|
|
527
|
+
return setup_page(request, 429, _("Too many attempts. Wait a few minutes and try "
|
|
528
|
+
"again."), typed)
|
|
529
|
+
if not state.setup_code_ok(form.get("setup_code") or ""):
|
|
530
|
+
state.rate_limiter.record_failure(ip)
|
|
531
|
+
state.log(f"first-run setup refused: wrong setup code from {ip} "
|
|
532
|
+
f"(host {auth.foreign_host(request.headers)!r})")
|
|
533
|
+
return setup_page(request, 403, _("That setup code is not right. It is in "
|
|
534
|
+
"setup-code.txt in ser2netweb’s data folder."), typed)
|
|
535
|
+
username = (form.get("username") or "admin").strip() or "admin"
|
|
536
|
+
pw = form.get("password", "")
|
|
537
|
+
pw2 = form.get("password2", "")
|
|
538
|
+
err = _username_problem(username) or _password_problem(pw, pw2)
|
|
539
|
+
if err:
|
|
540
|
+
return setup_page(request, 400, err, typed)
|
|
541
|
+
pw_hash = await state.password_work.run(auth.hash_password, pw)
|
|
542
|
+
try:
|
|
543
|
+
async with state.edit_config():
|
|
544
|
+
# checked again here: another setup request may have finished while this one
|
|
545
|
+
# was sending its form or hashing — it must not replace that admin
|
|
546
|
+
claimed = state.config.password_set
|
|
547
|
+
if not claimed:
|
|
548
|
+
state.config.users = [User(username=username, password_hash=pw_hash,
|
|
549
|
+
role="admin", pwd_version=new_pwd_version())]
|
|
550
|
+
except ConfigError as e: # not saved: still no account
|
|
551
|
+
return setup_page(request, 400, str(e), typed)
|
|
552
|
+
if claimed:
|
|
553
|
+
state.log(f"first-run setup from {ip} ignored: the admin account exists already")
|
|
554
|
+
return proxy.redirect(request, "/login")
|
|
555
|
+
state.first_run_done()
|
|
556
|
+
if (user := state.config.get_user(username)) is None: # (created just above)
|
|
557
|
+
return proxy.redirect(request, "/login")
|
|
558
|
+
state.log(f"first-run setup complete; admin user '{username}' created")
|
|
559
|
+
ctx.audit(request, "first_run_setup", username, user=username)
|
|
560
|
+
resp = proxy.redirect(request, "/")
|
|
561
|
+
set_session(resp, request, user)
|
|
562
|
+
ctx.new_csrf_token(request)
|
|
563
|
+
return resp
|
|
564
|
+
|
|
565
|
+
return [
|
|
566
|
+
Route("/login", login_get, methods=["GET"]),
|
|
567
|
+
Route("/login", login_post, methods=["POST"], max_body_size=FORM_MAX_BYTES),
|
|
568
|
+
Route("/logout", logout_post, methods=["POST"], max_body_size=FORM_MAX_BYTES),
|
|
569
|
+
Route("/auth/oidc/login", oidc_login, methods=["GET"]),
|
|
570
|
+
Route("/auth/oidc/callback", oidc_callback, methods=["GET"]),
|
|
571
|
+
Route("/setup", setup_get, methods=["GET"]),
|
|
572
|
+
Route("/setup", setup_post, methods=["POST"], max_body_size=FORM_MAX_BYTES),
|
|
573
|
+
]
|