mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 14:25:08 +00:00
* fix(web): escape quotes in every HTML escaper, not just & < >
The escapers are all `div.textContent = x; return div.innerHTML`. That
round-trip escapes &, < and > -- the only characters the HTML serializer
must escape in a text node -- and leaves quotes alone. Every widget then
interpolates the result into a quoted attribute value:
value="${escapeHtml(v)}" title="${escapeHtml(v)}"
so a value of `x" onmouseover="alert(1)` closes the attribute and adds an
event handler of its own. CodeQL reported this 83 times
(js/incomplete-html-attribute-sanitization) across the widget files.
It is one bug, not 83: the widgets each carry a standalone fallback that
did escape quotes, but they all prefer BaseWidget.escapeHtml when
window.BaseWidget exists -- which it always does in the shipped page -- so
the correct fallbacks were dead code and the incomplete shared one ran.
Fixed at each source instead of at the call sites.
app-shell.js already documented this exact gap in a comment and worked
around it by building DOM nodes by hand; that workaround stays (setting a
property cannot be got wrong), the comment is now accurate.
cache.html's delete button interpolated the cache key into
`onclick="deleteCacheFile('...')"`. Escaping cannot help there -- the
browser HTML-decodes the attribute before parsing it as JS, so `'`
becomes a real `'` again -- so the key moves to a data-cache-key
attribute that the handler reads back.
url-input.js additionally wrote a value straight into an <a href> after
validating it against a schema-supplied protocol list, and that list
accepted any RFC 3986 scheme -- "javascript" included. Scriptable schemes
(javascript, data, vbscript, blob, filesystem) are now refused both when
the list is normalised and when a URL is checked against it, and the
render path routes its href through the same check instead of emitting
whatever was stored (js/xss-through-dom).
test/js/unit/test_html_escaping.js reads each escaper out of the shipped
file and runs it, so losing the quote handling again fails a test rather
than a scan.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): stop request-supplied names from reaching paths outside their base
Three of the py/path-injection alerts were live, not lint:
* GET /api/v3/plugins/<plugin_id>/static/<path:file_path> read any file
whose resolved path *string-prefixed* the plugin directory. Flask's
default converter forbids a slash but not dots, and
get_plugin_directory('..') returned the parent of the plugins directory
because it exists -- so every file under the project root then prefixed
that directory, config/config_secrets.json included. The prefix check
was also wrong on its own terms: with plugin dir "plugin-repos/foo",
"../foo-evil/x" resolves to "plugin-repos/foo-evil/x", whose string does
start with "plugin-repos/foo".
* POST /api/v3/plugins/of-the-day/json/delete interpolated the request
body's file_id into f"{file_id}.json" and unlinked it, unvalidated. A
file_id of "../../../../etc/something" deleted that file. This is the
one finding in the batch that destroyed data rather than exposing it.
* POST /api/v3/cache/delete passed the body's key through
CacheManager.clear_cache to DiskCache, which joined it as a filename and
called os.remove. Same shape, same result. The guard goes in
DiskCache.get_cache_path, the single choke point get/set/clear share, so
every caller is covered rather than just this route. Real keys are the
stems of files already flat in the cache directory -- that is how
list_cache_files derives them -- so nothing legitimate is turned away.
The rest of the cluster (web_interface/app.py's asset route, the plugin
update handler, _get_plugin_version, the plugin-schema read in config.py)
was guarded in ways that held, but each had grown its own version of the
check. They now go through one helper, src/common/path_safety.py, which
returns the *sanitised value* rather than a verdict -- so a caller cannot
validate one string and open another, which is how the two real bugs
above were shaped.
Also: WiFiManager.connect_to_network took the SSID and password straight
from POST /api/v3/wifi/connect into nmcli's argv. There is no shell there,
so CodeQL's py/command-line-injection alert overstates the risk -- but
nmcli reads a leading "-" as an option, so an SSID of "--ask" asks nmcli
to run differently rather than to join a network. Both values are now
checked for shape (802.11's 32-octet SSID limit, WPA's 8-63 char
passphrase or 64-char hex key, no control characters, no leading dash)
before any subprocess runs.
test/test_path_traversal_guards.py asserts on the filesystem, not just
the status code: a handler that returns 403 and deletes the file anyway
would pass the weaker check. Twelve of its cases fail against the
unpatched code.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): refuse a plugin id that is not a plain name, don't truncate it
pages_v3 and scripts/dev_server.py ran request ids through
os.path.basename and carried on with what came out, so "../weather"
rendered the config form for "weather". Nothing escaped the plugins
directory -- the relative_to guards held -- but the handler answered a
request nobody made, and validating one string while the filesystem sees
another is the shape both live traversals earlier in this branch had.
Same treatment as the rest: safe_path_component rejects rather than
truncates, resolve_under returns the path it checked, and the call sites
use what those return. The three handlers that had hand-rolled
resolve-and-relative_to blocks lose about twenty lines to the shared one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(web): say what the plugin web_ui iframe actually is
The docstring claimed the fragment runs "in a sandboxed iframe". The
iframe in plugin_config.html carries no sandbox attribute, so the
fragment runs with the interface's own origin. That is fine -- the file
belongs to an installed plugin, and an installed plugin already runs
Python on the device, so the trust boundary is install rather than this
route -- but a comment promising containment that is not there is worse
than no comment. This is the context for the py/reflective-xss alert on
this handler.
Also drops the now-unused os/os.path imports.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): inline url-input's scheme guard at the previewLink.href sink
CodeQL flagged this line as a new high-severity js/xss-through-dom alert
on this PR even though it is already covered by SCRIPTABLE_SCHEMES: the
guard reached the sink through safeHref -> isValidUrl, two function calls
away, which its DOM-based-XSS sanitizer recognition does not trace.
Behavior is unchanged -- same scheme check, same SCRIPTABLE_SCHEMES list,
same allowedProtocols gate -- just inlined directly above the
previewLink.href assignment it guards, so the barrier is visible in the
same scope as the sink.
Added a regression test that runs the shipped onInput handler (not just
the extracted helpers) against a mocked DOM, so a future change that
reintroduces an unguarded previewLink.href assignment fails here.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): address CodeRabbit findings on the CodeQL triage PR
- src/wifi_manager.py: reject non-ASCII WPA-PSK passphrases before any
credential-saving or connect flow runs. NetworkManager only accepts
printable ASCII passphrases (or a 64-char hex key); a non-ASCII value
was previously saved/attempted before nmcli itself rejected it.
- web_interface/blueprints/api_v3/config.py: fail closed when the
plugin config schema path can't be resolved under the plugins
directory (e.g. a symlinked plugin dir). Previously this fell
through with secret_fields left empty, so submitted credentials for
that plugin were saved as ordinary, unencrypted configuration.
- web_interface/static/v3/js/widgets/plugin-file-manager.js: stop
splicing the JSON day/column key into an inline oninput="..." handler
string. escHtml() escapes quotes for a normal HTML attribute, but the
browser HTML-decodes the attribute before running it as script, which
undoes that escaping and lets a crafted column name (e.g. from an
uploaded JSON file) break out of the JS string and execute. Cell
edits now travel through data-day/data-col attributes read by one
delegated 'input' listener instead.
While in this file: fixed 6 pre-existing missing-')' typos on
multi-line safeSetHTML(...) calls (already flagged by Biome in this
PR's own CodeRabbit run as syntax errors blocking its lint pass).
These predate this PR (present on main too) but made the whole file
fail to parse in any JS engine, which is a bigger problem than the
XSS finding itself and directly touches the same lines.
Added/extended regression tests for each fix; full suites pass
(pytest: 4580 passed, 62 skipped; JS: 84 assertions).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
155 lines
6.5 KiB
Python
155 lines
6.5 KiB
Python
"""The SSID and password reaching nmcli's argv come from an HTTP request body.
|
|
|
|
POST /api/v3/wifi/connect takes both verbatim and WiFiManager.connect_to_network
|
|
hands them to::
|
|
|
|
subprocess.run(["nmcli", "device", "wifi", "connect", ssid, "password", password])
|
|
|
|
There is no shell in that, so no metacharacter can start a second command --
|
|
CodeQL's py/command-line-injection alert overstates it on that point. What is
|
|
real is argument injection: nmcli reads a leading "-" as an option, so an SSID
|
|
of "--ask" or "-t" asks nmcli to *run differently* rather than to join a
|
|
network. Neither value was checked for shape at all before reaching argv.
|
|
|
|
These tests pin the validation without touching real networking: the
|
|
validators are classmethods, so nothing here constructs a WiFiManager.
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from src.wifi_manager import WiFiManager # noqa: E402
|
|
from test._api_v3_test_helpers import api_v3_client, api_v3_module # noqa: F401,E402
|
|
|
|
|
|
class TestSsidValidation:
|
|
@pytest.mark.parametrize("ssid", [
|
|
"HomeNet", "my wifi 5G", "Cafe-Guest", "café", "x" * 32, "-not-leading".lstrip("-"),
|
|
])
|
|
def test_ordinary_ssids_pass_through(self, ssid):
|
|
value, error = WiFiManager._validate_ssid(ssid)
|
|
assert error is None
|
|
assert value == ssid
|
|
|
|
def test_surrounding_whitespace_is_trimmed_not_rejected(self):
|
|
value, error = WiFiManager._validate_ssid(" HomeNet ")
|
|
assert error is None
|
|
assert value == "HomeNet"
|
|
|
|
@pytest.mark.parametrize("ssid", ["--ask", "-t", "-"])
|
|
def test_an_ssid_nmcli_would_read_as_an_option_is_refused(self, ssid):
|
|
value, error = WiFiManager._validate_ssid(ssid)
|
|
assert error is not None
|
|
assert value == ""
|
|
|
|
def test_an_ssid_over_32_octets_is_refused(self):
|
|
# 802.11 caps the SSID element at 32 octets, so a longer one could
|
|
# never name a real network.
|
|
_, error = WiFiManager._validate_ssid("x" * 33)
|
|
assert error is not None
|
|
# Multi-byte characters count as octets, not characters.
|
|
_, error = WiFiManager._validate_ssid("é" * 17)
|
|
assert error is not None
|
|
|
|
@pytest.mark.parametrize("ssid", ["a\nb", "a\rb", "a\x00b", "a\x7fb", "a\tb"])
|
|
def test_control_characters_are_refused(self, ssid):
|
|
_, error = WiFiManager._validate_ssid(ssid)
|
|
assert error is not None
|
|
|
|
@pytest.mark.parametrize("ssid", ["", " ", None, 42, ["HomeNet"]])
|
|
def test_empty_and_non_text_values_are_refused(self, ssid):
|
|
_, error = WiFiManager._validate_ssid(ssid)
|
|
assert error is not None
|
|
|
|
|
|
class TestPasswordValidation:
|
|
def test_an_empty_password_means_an_open_network(self):
|
|
value, error = WiFiManager._validate_wifi_password("")
|
|
assert error is None
|
|
assert value == ""
|
|
value, error = WiFiManager._validate_wifi_password(None)
|
|
assert error is None
|
|
assert value == ""
|
|
|
|
@pytest.mark.parametrize("password", ["hunter22", "a" * 63, "0" * 64, "AbCdEf0123" * 6 + "abcd"])
|
|
def test_valid_psk_lengths_pass_through(self, password):
|
|
value, error = WiFiManager._validate_wifi_password(password)
|
|
assert error is None, f"{password!r} rejected: {error}"
|
|
assert value == password
|
|
|
|
@pytest.mark.parametrize("password", ["short", "z" * 64, "a" * 200])
|
|
def test_lengths_that_could_never_authenticate_are_refused(self, password):
|
|
# 8-63 chars for a passphrase, or exactly 64 hex chars for a raw key.
|
|
# "z" * 64 is the right length for a key but is not hex, so it is
|
|
# neither -- note "a" * 64 *is* valid hex and must stay accepted.
|
|
_, error = WiFiManager._validate_wifi_password(password)
|
|
assert error is not None
|
|
|
|
@pytest.mark.parametrize("password", ["-password", "--ask"])
|
|
def test_a_password_nmcli_would_read_as_an_option_is_refused(self, password):
|
|
_, error = WiFiManager._validate_wifi_password(password)
|
|
assert error is not None
|
|
|
|
def test_control_characters_are_refused(self):
|
|
_, error = WiFiManager._validate_wifi_password("pass\nword")
|
|
assert error is not None
|
|
|
|
@pytest.mark.parametrize("password", ["pässword", "你好12345678"])
|
|
def test_non_ascii_passphrases_are_refused(self, password):
|
|
# NetworkManager accepts only printable ASCII WPA-PSK passphrases (or
|
|
# a 64-char hex key); a non-ASCII value would otherwise reach
|
|
# _connect_nmcli and be saved/attempted before nmcli itself rejects it.
|
|
_, error = WiFiManager._validate_wifi_password(password)
|
|
assert error is not None
|
|
|
|
|
|
class TestConnectRefusesBeforeRunningNmcli:
|
|
"""connect_to_network must not reach subprocess with a rejected value."""
|
|
|
|
@pytest.mark.parametrize("ssid,password", [
|
|
("--ask", "hunter22"),
|
|
("x" * 40, "hunter22"),
|
|
("Home\nNet", "hunter22"),
|
|
("HomeNet", "-secret1"),
|
|
("HomeNet", "short"),
|
|
])
|
|
def test_no_subprocess_runs_for_a_rejected_request(self, ssid, password):
|
|
manager = WiFiManager.__new__(WiFiManager) # no __init__: no real host access
|
|
with patch("src.wifi_manager.subprocess.run") as run:
|
|
ok, message = manager.connect_to_network(ssid, password)
|
|
assert ok is False
|
|
assert message
|
|
run.assert_not_called()
|
|
|
|
|
|
class TestConnectEndpointSurfacesTheRefusal:
|
|
URL = "/api/v3/wifi/connect"
|
|
|
|
@pytest.fixture
|
|
def wifi_manager(self):
|
|
with patch("src.wifi_manager.WiFiManager") as cls:
|
|
instance = MagicMock()
|
|
cls.return_value = instance
|
|
yield instance
|
|
|
|
def test_a_rejected_ssid_comes_back_as_a_client_error(
|
|
self, api_v3_client, wifi_manager
|
|
):
|
|
# The route delegates the shape check to the manager, so mirror what
|
|
# the real one now returns rather than asserting on a mock's default.
|
|
wifi_manager.connect_to_network.return_value = (False, "SSID cannot start with '-'")
|
|
response = api_v3_client.post(self.URL, json={"ssid": "--ask", "password": "hunter22"})
|
|
assert response.status_code == 400
|
|
assert "-" in response.get_json()["message"]
|
|
|
|
def test_an_ordinary_request_is_unaffected(self, api_v3_client, wifi_manager):
|
|
wifi_manager.connect_to_network.return_value = (True, "Connected to HomeNet")
|
|
response = api_v3_client.post(self.URL, json={"ssid": "HomeNet", "password": "hunter22"})
|
|
assert response.status_code == 200
|
|
wifi_manager.connect_to_network.assert_called_once_with("HomeNet", "hunter22")
|