Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
c9f099e
Security: small hardening fixes from review
mdipierro Nov 7, 2026
2677d21
Security: pin the host of emailed auth links, sanitize X-Script-Name
mdipierro Nov 7, 2026
387f410
Security: password reset must not bypass email verification/approval
mdipierro Nov 7, 2026
581c84f
Security: enforce two factor authentication on the JSON login API
mdipierro Nov 7, 2026
a60e7c6
Security: Grid details/edit/delete only load records matching the query
mdipierro Nov 7, 2026
176944a
Security: do not serve uploaded files inline unless the type is safe
mdipierro Nov 7, 2026
fb1c9eb
Security: Publisher denies everything unless a policy is given
mdipierro Nov 7, 2026
5c95d5a
Security: stop reading the session token from the request body
mdipierro Nov 7, 2026
b88779d
Security: Grid delete requires the form key, validate the referrer
mdipierro Nov 7, 2026
048923c
Security: Grid only sorts by its own columns
mdipierro Nov 7, 2026
50d86f3
Security: harden SSO, OAuth2 and WebAuthn logins
mdipierro Nov 7, 2026
80828ad
Security: use a CSPRNG for keys and session ids, retire rotated ids
mdipierro Nov 7, 2026
ff3bcaf
Security: count two factor tries server side, expire the code
mdipierro Nov 7, 2026
6312efc
Security: keep token authenticated users per request, not in session
mdipierro Nov 7, 2026
285bc70
Security: stronger password hashing, throttle login attempts
mdipierro Nov 7, 2026
5e2fdd6
Security: dashboard uses the validated X-Script-Name prefix
mdipierro Nov 7, 2026
2464b6f
Auth: link first SSO login to existing account with verified email
mdipierro Nov 7, 2026
5131b76
Form: list:reference gets a multiple select, keep hidden fields in vars
mdipierro Nov 7, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 58 additions & 13 deletions apps/_dashboard/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import uuid
import zipfile
Expand All @@ -32,7 +34,16 @@
request,
response,
)
from py4web.core import DAL, Fixture, Reloader, Session, dumps, error_logger, safely
from py4web.core import (
DAL,
Fixture,
Reloader,
Session,
dumps,
error_logger,
get_script_name,
safely,
)
from py4web.utils.factories import ActionFactory
from py4web.utils.grid import Grid

Expand Down Expand Up @@ -90,25 +101,48 @@ def index():
user_id=(session.get("user") or {}).get("id"),
# reverse-proxy prefix so client-rendered route links (Vue) point at
# the externally-visible path, not the raw registered rule
script_prefix=(
request.environ.get("SCRIPT_NAME", "")
or request.environ.get("HTTP_X_SCRIPT_NAME", "")
).rstrip("/"),
script_prefix=get_script_name(),
)

# brute force protection for the dashboard password (per process, per ip)
LOGIN_MAX_FAILURES = 5
LOGIN_WINDOW = 300 # seconds
LOGIN_FAILURES = {} # ip -> (failures, first failure time)
LOGIN_LOCK = threading.Lock()

def _login_failures(ip):
with LOGIN_LOCK:
count, since = LOGIN_FAILURES.get(ip, (0, 0))
if time.time() - since > LOGIN_WINDOW:
LOGIN_FAILURES.pop(ip, None)
return 0
return count

def _record_login(ip, valid):
with LOGIN_LOCK:
if valid:
LOGIN_FAILURES.pop(ip, None)
else:
count, since = LOGIN_FAILURES.get(ip, (0, time.time()))
LOGIN_FAILURES[ip] = (count + 1, since)

@action("login", method="POST")
@action.uses(session)
def login():
if MODE == "demo":
valid = True
else:
ip = request.remote_addr or ""
if _login_failures(ip) >= LOGIN_MAX_FAILURES:
return dict(user=False, mode=MODE, error="too many failed attempts")
valid = False
password = request.json.get("password")
password_file = os.environ.get("PY4WEB_PASSWORD_FILE")
if password and password_file and os.path.exists(password_file):
with open(password_file, "r") as fp:
encrypted_password = fp.read().strip()
valid = CRYPT()(password)[0] == encrypted_password
_record_login(ip, valid)
if valid:
session["user"] = dict(id=1)
return dict(user=valid, mode=MODE)
Expand Down Expand Up @@ -186,7 +220,14 @@ def make_grid():
"big-reference",
)
]
return Grid(table, columns=columns)
writable = MODE == "full"
return Grid(
table,
columns=columns,
create=writable,
editable=writable,
deletable=writable,
)

grid = action.uses(db)(make_grid)()
return dict(app_name=app_name, table_name=table_name, grid=grid)
Expand Down Expand Up @@ -239,6 +280,8 @@ def apps():
@catch_errors
def delete_app(name):
"""delete the app"""
if MODE != "full":
abort(403)
path = os.path.join(FOLDER, name)
# Keep backups out of the apps folder so they don't show up in
# listings or get re-imported by py4web.
Expand All @@ -259,6 +302,8 @@ def delete_app(name):
@session_secured
def new_file(name, file_name):
"""creates a new file"""
if MODE != "full":
abort(403)
app_path = os.path.join(FOLDER, name)
if not os.path.exists(app_path):
return {"status": "success", "payload": "App does not exist"}
Expand Down Expand Up @@ -384,7 +429,7 @@ def packed(path):
@catch_errors
def tickets():
"""Returns most recent tickets grouped by path+error"""
tickets = safely(error_logger.database_logger.get) if MODE != "DEMO" else None
tickets = safely(error_logger.database_logger.get) if MODE != "demo" else None
return {"payload": tickets or [], "status": "success"}

@action("clear")
Expand Down Expand Up @@ -643,8 +688,8 @@ def gitshow(project, commit):
@action.uses(Logged(session), "translations.html")
def translations(name):
"""renders the translation editor for app ``name``"""
folder = os.path.join(FOLDER, name, "translations")
if not os.path.exists(folder):
folder = os.path.join(safe_join(FOLDER, name) or abort(400), "translations")
if MODE == "full" and not os.path.exists(folder):
os.makedirs(folder)
return dict(app_name=name)

Expand All @@ -653,16 +698,16 @@ def translations(name):
@action.uses(Logged(session))
def get_translations(name):
"""returns a json with all translations for all languages"""
t = Translator(os.path.join(FOLDER, name, "translations"))
t = Translator(os.path.join(safe_join(FOLDER, name) or abort(400), "translations"))
return t.languages


@action("api/translations/<name>", method="POST")
@action.uses(Logged(session))
def post_translations(name):
"""updates all languages"""
folder = os.path.join(FOLDER, name, "translations")
if not os.path.exists(folder):
folder = os.path.join(safe_join(FOLDER, name) or abort(400), "translations")
if MODE == "full" and not os.path.exists(folder):
os.makedirs(folder)
t = Translator(folder)
t.languages = request.json
Expand All @@ -674,6 +719,6 @@ def post_translations(name):
@action.uses(Logged(session))
def update_translations(name):
"""find all T(...) decorated strings in the code and returns them"""
app_folder = os.path.join(FOLDER, name)
app_folder = safe_join(FOLDER, name) or abort(400)
strings = Translator.find_matches(app_folder)
return {"strings": strings}
1 change: 1 addition & 0 deletions apps/_scaffold/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
auth.param.password_complexity = {"entropy": settings.PASSWORD_ENTROPY}
auth.param.block_previous_password_num = 3
auth.param.default_login_enabled = settings.DEFAULT_LOGIN_ENABLED
auth.param.base_url = settings.BASE_URL
auth.define_tables()
auth.fix_actions()
auth.logger = logger
Expand Down
4 changes: 4 additions & 0 deletions apps/_scaffold/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@
ALLOWED_ACTIONS = ["all"]

# email settings
# trusted base url for links sent by email (e.g. "https://example.com")
# if None they are built from the request Host/Origin headers
BASE_URL = os.environ.get("PY4WEB_BASE_URL")

SMTP_SSL = False
SMTP_SERVER = None
SMTP_SENDER = "you@example.com"
Expand Down
57 changes: 37 additions & 20 deletions py4web/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@

PY4WEB_CMD = sys.argv[0]

REGEX_SCRIPT_NAME = re.compile(r"^(/[\w.~-]+)*/?$")
REGEX_APPJSON = r"(^|\s|,)application/json(,|\s|$)"

PASSWORD_FILENAME = "password.txt"
Expand Down Expand Up @@ -838,20 +839,18 @@ def load(self):
self_local = self.local
self_local.changed = False
self_local.data = {}
self_local.loaded_uuid = None
self_local.cookie_name = params.name.format(app_name=app_name)
self_local.secure = request.url.startswith("https")
# The session token is read from the cookie only. It used to also be
# accepted from the query string and request body; query-string
# tokens leak via Referer headers, browser history, and access logs,
# so that fallback was a session-stealing footgun.
# The session token is read from the cookie or, for clients that do not
# keep cookies, from the X-Session-Token header. It used to also be
# accepted from the query string and request body: query-string tokens
# leak via Referer headers, browser history, and access logs, and a
# body token lets a cross-site form force the attacker's session on a
# victim (a custom header cannot be sent cross-site without CORS).
raw_token = request.get_cookie(self_local.cookie_name)
if not raw_token and request.method in {"POST", "PUT", "DELETE", "PATCH"}:
raw_token = (
request.forms
and request.forms.get("_session_token")
or request.json
and request.json.get("_session_token")
)
if not raw_token:
raw_token = request.headers.get("X-Session-Token")
if DEBUG:
logging.debug("Session token found %s", raw_token)
data = {}
Expand Down Expand Up @@ -888,6 +887,7 @@ def load(self):
)
):
self_local.data.update(data) # the take the loaded data
self_local.loaded_uuid = data.get("uuid")

def save(self):
"""Saves the session"""
Expand All @@ -901,6 +901,12 @@ def save(self):
self_local.data["cookie_name"] = self_local.cookie_name
if params.storage:
cookie_data = self_local.data["uuid"]
# the session id changed (login, logout/clear): make sure the old
# id stops working, else a stolen or fixated id would stay valid
old_uuid = getattr(self_local, "loaded_uuid", None)
if old_uuid and old_uuid != cookie_data:
params.storage.set(old_uuid, "{}", params.expiration)
self_local.loaded_uuid = cookie_data
params.storage.set(
cookie_data, json.dumps(self_local.data), params.expiration
)
Expand Down Expand Up @@ -997,6 +1003,22 @@ def on_success(self, context):
#########################################################################################


def get_script_name():
"""Returns the URL prefix the app is mounted under (without trailing /)

SCRIPT_NAME is set by the WSGI server and trusted. X-Script-Name is a
client-controlled header, so only a plain path prefix is accepted from it,
never something like "@evil.com" that would change the host of absolute
URLs.
"""
script_name = request.environ.get("SCRIPT_NAME", "")
if not script_name:
script_name = request.environ.get("HTTP_X_SCRIPT_NAME", "")
if script_name and not REGEX_SCRIPT_NAME.match(script_name):
script_name = ""
return script_name.rstrip("/")


def URL( # pylint: disable=invalid-name
*parts,
vars=None, # pylint: disable=redefined-builtin
Expand All @@ -1023,10 +1045,7 @@ def URL( # pylint: disable=invalid-name
# no-parts branch below can strip it when use_appname=False.
app_name = getattr(request, "app_name", None)
has_appname = bool(use_appname and app_name)
script_name = (
request.environ.get("SCRIPT_NAME", "")
or request.environ.get("HTTP_X_SCRIPT_NAME", "")
).rstrip("/")
script_name = get_script_name()
if not parts:
# request.path is WSGI PATH_INFO, which never carries SCRIPT_NAME, so a
# self-referential URL(vars=...) behind a reverse-proxy prefix must have
Expand Down Expand Up @@ -1837,10 +1856,7 @@ def error404(error): # pylint: disable=unused-argument
href = "/"
else:
href = "/" + guess_app_name
script_name = (
request.environ.get("SCRIPT_NAME", "")
or request.environ.get("HTTP_X_SCRIPT_NAME", "")
).rstrip("/")
script_name = get_script_name()
if script_name:
href = script_name + href
return error_page(404, button_text=guess_app_name, href=href)
Expand Down Expand Up @@ -2166,7 +2182,8 @@ def set_password(password, password_file):
"""Set administrator's password for the Dashboard"""
click.echo(f'Storing the hashed password in file "{password_file}"\n')
with open(password_file, "w", encoding="utf8") as fp:
fp.write(str(pydal.validators.CRYPT()(password)[0]))
alg = "pbkdf2(210000,20,sha512)"
fp.write(str(pydal.validators.CRYPT(digest_alg=alg)(password)[0]))


def reinstall_apps(kwargs):
Expand Down
Loading
Loading