mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-21 02:19:07 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb0e869bf6 |
+10
-3
@@ -1419,9 +1419,16 @@ $ACTUAL_USER ALL=(ALL) NOPASSWD: $BASH_PATH $PROJECT_ROOT_DIR/scripts/fix_perms/
|
|||||||
EOF
|
EOF
|
||||||
if [ -n "$JOURNALCTL_PATH" ]; then
|
if [ -n "$JOURNALCTL_PATH" ]; then
|
||||||
cat >> /tmp/ledmatrix_web_sudoers << EOF
|
cat >> /tmp/ledmatrix_web_sudoers << EOF
|
||||||
$ACTUAL_USER ALL=(ALL) NOPASSWD: $JOURNALCTL_PATH -u ledmatrix.service *
|
# NOEXEC, because these rules end in a wildcard and journalctl starts a pager
|
||||||
$ACTUAL_USER ALL=(ALL) NOPASSWD: $JOURNALCTL_PATH -u ledmatrix *
|
# when its output is a terminal. From that pager (less) a "!sh" is a root
|
||||||
$ACTUAL_USER ALL=(ALL) NOPASSWD: $JOURNALCTL_PATH -t ledmatrix *
|
# shell -- the standard journalctl escalation. The web interface always passes
|
||||||
|
# --no-pager, so nothing here needs it, but the rule cannot require a flag that
|
||||||
|
# sits in the middle of the command line. NOEXEC stops the command executing
|
||||||
|
# another program at all, which closes the hole without depending on wildcard
|
||||||
|
# matching subtleties.
|
||||||
|
$ACTUAL_USER ALL=(ALL) NOPASSWD:NOEXEC: $JOURNALCTL_PATH -u ledmatrix.service *
|
||||||
|
$ACTUAL_USER ALL=(ALL) NOPASSWD:NOEXEC: $JOURNALCTL_PATH -u ledmatrix *
|
||||||
|
$ACTUAL_USER ALL=(ALL) NOPASSWD:NOEXEC: $JOURNALCTL_PATH -t ledmatrix *
|
||||||
EOF
|
EOF
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
+1
-63
@@ -111,12 +111,6 @@ class RestoreOptions:
|
|||||||
"""Which sections of a backup should be restored."""
|
"""Which sections of a backup should be restored."""
|
||||||
|
|
||||||
restore_config: bool = True
|
restore_config: bool = True
|
||||||
#: Whether to take the backup's display.hardware block as well.
|
|
||||||
#: Off by default: that block describes the panel physically wired to
|
|
||||||
#: *this* device -- its size, chain length, mapping, multiplexing and
|
|
||||||
#: refresh cap. A backup carries the panel of the machine it was taken
|
|
||||||
#: on, and restoring one onto a different rig drives the wrong geometry.
|
|
||||||
restore_hardware: bool = False
|
|
||||||
restore_secrets: bool = True
|
restore_secrets: bool = True
|
||||||
restore_wifi: bool = True
|
restore_wifi: bool = True
|
||||||
restore_fonts: bool = True
|
restore_fonts: bool = True
|
||||||
@@ -555,60 +549,6 @@ def _copy_file(src: Path, dst: Path) -> None:
|
|||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
_HARDWARE_PATH = ("display", "hardware")
|
|
||||||
|
|
||||||
|
|
||||||
def _restore_config_preserving_hardware(src: Path, dst: Path, keep_hardware: bool) -> None:
|
|
||||||
"""Copy a backed-up config.json, optionally keeping the local panel block.
|
|
||||||
|
|
||||||
display.hardware describes the panel physically attached to this device:
|
|
||||||
cols, rows, chain_length, hardware_mapping, panel_type, multiplexing and
|
|
||||||
the refresh-rate cap. None of that travels with a configuration -- it is a
|
|
||||||
property of the machine. Restoring a backup taken on a 512x64 rig onto a
|
|
||||||
128x32 one used to overwrite the smaller panel's geometry with the larger
|
|
||||||
one's, which is not a setting the user can see going wrong; the display
|
|
||||||
simply stops being right.
|
|
||||||
|
|
||||||
Falls back to a plain copy when either file cannot be parsed, so a restore
|
|
||||||
never fails because of this.
|
|
||||||
"""
|
|
||||||
if not keep_hardware:
|
|
||||||
_copy_file(src, dst)
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
incoming = json.loads(src.read_text(encoding="utf-8"))
|
|
||||||
local = json.loads(dst.read_text(encoding="utf-8")) if dst.exists() else {}
|
|
||||||
except (OSError, ValueError) as exc:
|
|
||||||
logger.warning(
|
|
||||||
"[Backup] Could not merge local panel config (%s); restoring the "
|
|
||||||
"backup's config.json as-is", exc)
|
|
||||||
_copy_file(src, dst)
|
|
||||||
return
|
|
||||||
|
|
||||||
section, key = _HARDWARE_PATH
|
|
||||||
local_hw = (local.get(section) or {}).get(key)
|
|
||||||
if not isinstance(local_hw, dict) or not local_hw:
|
|
||||||
_copy_file(src, dst)
|
|
||||||
return
|
|
||||||
|
|
||||||
if not isinstance(incoming.get(section), dict):
|
|
||||||
incoming[section] = {}
|
|
||||||
incoming_hw = incoming[section].get(key)
|
|
||||||
incoming[section][key] = local_hw
|
|
||||||
if isinstance(incoming_hw, dict) and incoming_hw != local_hw:
|
|
||||||
logger.info(
|
|
||||||
"[Backup] Kept this device's display.hardware; the backup's panel "
|
|
||||||
"was %sx%s chain %s, this one is %sx%s chain %s",
|
|
||||||
incoming_hw.get("cols"), incoming_hw.get("rows"),
|
|
||||||
incoming_hw.get("chain_length"),
|
|
||||||
local_hw.get("cols"), local_hw.get("rows"),
|
|
||||||
local_hw.get("chain_length"))
|
|
||||||
|
|
||||||
tmp_path = dst.with_suffix(dst.suffix + ".restore-tmp")
|
|
||||||
tmp_path.write_text(json.dumps(incoming, indent=2) + "\n", encoding="utf-8")
|
|
||||||
os.replace(tmp_path, dst)
|
|
||||||
|
|
||||||
|
|
||||||
def restore_backup(
|
def restore_backup(
|
||||||
zip_path: Path,
|
zip_path: Path,
|
||||||
project_root: Path,
|
project_root: Path,
|
||||||
@@ -644,9 +584,7 @@ def restore_backup(
|
|||||||
# Main config.
|
# Main config.
|
||||||
if options.restore_config and (tmp_dir / _CONFIG_REL).exists():
|
if options.restore_config and (tmp_dir / _CONFIG_REL).exists():
|
||||||
try:
|
try:
|
||||||
_restore_config_preserving_hardware(
|
_copy_file(tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL)
|
||||||
tmp_dir / _CONFIG_REL, project_root / _CONFIG_REL,
|
|
||||||
keep_hardware=not options.restore_hardware)
|
|
||||||
result.restored.append("config")
|
result.restored.append("config")
|
||||||
except OSError as e:
|
except OSError as e:
|
||||||
logger.error("[Backup] Failed to restore config.json: %s", e, exc_info=True)
|
logger.error("[Backup] Failed to restore config.json: %s", e, exc_info=True)
|
||||||
|
|||||||
@@ -1,75 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""A restore must not repoint this device at another machine's panel.
|
|
||||||
|
|
||||||
display.hardware describes the panel physically wired to this device -- cols,
|
|
||||||
rows, chain_length, hardware_mapping, panel_type, multiplexing, the refresh
|
|
||||||
cap. A backup carries the panel of the machine it was taken on. Restoring a
|
|
||||||
512x64 rig's backup onto a 128x32 one used to overwrite the smaller panel's
|
|
||||||
geometry with the larger one's, and nothing on screen explains why: the
|
|
||||||
display just stops being right.
|
|
||||||
|
|
||||||
That is not hypothetical. It happened, and the rig it happened to had to be
|
|
||||||
reflashed.
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
||||||
|
|
||||||
from src.backup_manager import _restore_config_preserving_hardware # noqa: E402
|
|
||||||
|
|
||||||
BIG = {"display": {"hardware": {"cols": 128, "rows": 64, "chain_length": 4,
|
|
||||||
"hardware_mapping": "adafruit-hat-pwm"},
|
|
||||||
"runtime": {"gpio_slowdown": 4}},
|
|
||||||
"timezone": "America/New_York", "some-plugin": {"enabled": True}}
|
|
||||||
SMALL = {"display": {"hardware": {"cols": 64, "rows": 32, "chain_length": 2,
|
|
||||||
"hardware_mapping": "regular"},
|
|
||||||
"runtime": {"gpio_slowdown": 2}},
|
|
||||||
"timezone": "UTC"}
|
|
||||||
|
|
||||||
|
|
||||||
def _run(tmp, keep):
|
|
||||||
src = tmp / "backup_config.json"; src.write_text(json.dumps(BIG))
|
|
||||||
dst = tmp / "config.json"; dst.write_text(json.dumps(SMALL))
|
|
||||||
_restore_config_preserving_hardware(src, dst, keep_hardware=keep)
|
|
||||||
return json.loads(dst.read_text())
|
|
||||||
|
|
||||||
|
|
||||||
def test_local_panel_survives(tmp_path):
|
|
||||||
out = _run(tmp_path, keep=True)
|
|
||||||
hw = out["display"]["hardware"]
|
|
||||||
assert (hw["cols"], hw["rows"], hw["chain_length"]) == (64, 32, 2), (
|
|
||||||
"the restore repointed this device at the backup's panel")
|
|
||||||
assert hw["hardware_mapping"] == "regular", "panel wiring came from the backup"
|
|
||||||
|
|
||||||
|
|
||||||
def test_everything_else_is_restored(tmp_path):
|
|
||||||
out = _run(tmp_path, keep=True)
|
|
||||||
assert out["timezone"] == "America/New_York", "config was not restored"
|
|
||||||
assert out["some-plugin"] == {"enabled": True}, "plugin config was not restored"
|
|
||||||
assert out["display"]["runtime"] == {"gpio_slowdown": 4}, (
|
|
||||||
"only display.hardware should be held back")
|
|
||||||
|
|
||||||
|
|
||||||
def test_opting_in_takes_the_backups_panel(tmp_path):
|
|
||||||
out = _run(tmp_path, keep=False)
|
|
||||||
hw = out["display"]["hardware"]
|
|
||||||
assert (hw["cols"], hw["rows"], hw["chain_length"]) == (128, 64, 4)
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_device_with_no_local_hardware_takes_the_backups(tmp_path):
|
|
||||||
src = tmp_path / "b.json"; src.write_text(json.dumps(BIG))
|
|
||||||
dst = tmp_path / "c.json"; dst.write_text(json.dumps({"timezone": "UTC"}))
|
|
||||||
_restore_config_preserving_hardware(src, dst, keep_hardware=True)
|
|
||||||
out = json.loads(dst.read_text())
|
|
||||||
assert out["display"]["hardware"]["cols"] == 128, (
|
|
||||||
"nothing local to preserve, so the backup's panel should be used")
|
|
||||||
|
|
||||||
|
|
||||||
def test_unparseable_local_config_still_restores(tmp_path):
|
|
||||||
src = tmp_path / "b.json"; src.write_text(json.dumps(BIG))
|
|
||||||
dst = tmp_path / "c.json"; dst.write_text("{ not json")
|
|
||||||
_restore_config_preserving_hardware(src, dst, keep_hardware=True)
|
|
||||||
assert json.loads(dst.read_text())["timezone"] == "America/New_York", (
|
|
||||||
"a restore must never fail because of this merge")
|
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Wildcard grants to commands that start a pager must carry NOEXEC.
|
||||||
|
|
||||||
|
`journalctl` runs a pager when its output is a terminal, and from `less` a
|
||||||
|
`!sh` is a shell with the privileges journalctl was given. That is the standard
|
||||||
|
journalctl privilege escalation, and the installer's rules end in a wildcard:
|
||||||
|
|
||||||
|
<user> ALL=(ALL) NOPASSWD: /usr/bin/journalctl -u ledmatrix *
|
||||||
|
|
||||||
|
The web interface always passes --no-pager -- both call sites do, in app.py and
|
||||||
|
api_v3.py -- so nothing the project runs needs the pager. But a sudoers rule
|
||||||
|
cannot require a flag that sits in the middle of the command line, and reasoning
|
||||||
|
about what a trailing `*` does or does not admit is exactly the kind of
|
||||||
|
subtlety that produces a hole.
|
||||||
|
|
||||||
|
sudo's NOEXEC tag stops the command executing another program at all, which
|
||||||
|
closes it without depending on that reasoning. It works by LD_PRELOAD, so it
|
||||||
|
applies to dynamically linked binaries; journalctl is one.
|
||||||
|
|
||||||
|
On a stock Raspberry Pi image none of this is reachable, because
|
||||||
|
/etc/sudoers.d/010_pi-nopasswd already grants the default user
|
||||||
|
`ALL=(ALL) NOPASSWD: ALL`. It matters on a hardened install, or where the
|
||||||
|
service runs as a user without that blanket rule.
|
||||||
|
"""
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
INSTALLERS = (
|
||||||
|
ROOT / "first_time_install.sh",
|
||||||
|
ROOT / "scripts" / "install" / "configure_wifi_permissions.sh",
|
||||||
|
)
|
||||||
|
|
||||||
|
#: Commands that will start another program of their own accord -- a pager, an
|
||||||
|
#: editor, a shell -- and so must not be granted the ability to do so.
|
||||||
|
SPAWNS_A_PROGRAM = ("journalctl", "systemctl", "less", "more", "man", "git")
|
||||||
|
|
||||||
|
|
||||||
|
def _grant_lines():
|
||||||
|
lines = []
|
||||||
|
for installer in INSTALLERS:
|
||||||
|
if not installer.is_file():
|
||||||
|
continue
|
||||||
|
for line in installer.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||||
|
stripped = line.strip()
|
||||||
|
if "NOPASSWD" in stripped and not stripped.startswith("#"):
|
||||||
|
lines.append(stripped)
|
||||||
|
return lines
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_installers_are_present():
|
||||||
|
missing = [str(p.relative_to(ROOT)) for p in INSTALLERS if not p.is_file()]
|
||||||
|
assert not missing, f"installer(s) missing: {missing}"
|
||||||
|
|
||||||
|
|
||||||
|
def test_wildcard_pager_grants_carry_noexec():
|
||||||
|
offenders = []
|
||||||
|
for rule in _grant_lines():
|
||||||
|
command = rule.split("NOPASSWD", 1)[1]
|
||||||
|
if not command.rstrip().endswith("*"):
|
||||||
|
continue
|
||||||
|
tool = command.replace("_PATH", "").replace("$", "").lower()
|
||||||
|
for name in SPAWNS_A_PROGRAM:
|
||||||
|
if re.search(rf"(^|/|\s){name}(\s|$)", tool):
|
||||||
|
if "NOEXEC" not in rule:
|
||||||
|
offenders.append(rule)
|
||||||
|
break
|
||||||
|
assert not offenders, (
|
||||||
|
"wildcard grant to a command that can start a pager or shell, without "
|
||||||
|
"NOEXEC:\n " + "\n ".join(offenders))
|
||||||
|
|
||||||
|
|
||||||
|
def test_journalctl_is_granted_at_all():
|
||||||
|
"""Guard against 'fixing' the above by deleting the rules."""
|
||||||
|
text = "\n".join(_grant_lines())
|
||||||
|
assert "JOURNALCTL_PATH" in text or "journalctl" in text, (
|
||||||
|
"no journalctl grant remains; the web interface reads logs through it")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("unit", ["ledmatrix.service", "ledmatrix"])
|
||||||
|
def test_each_journalctl_rule_is_tagged(unit):
|
||||||
|
matching = [r for r in _grant_lines()
|
||||||
|
if "JOURNALCTL_PATH" in r and f"-u {unit} " in r]
|
||||||
|
assert matching, f"no journalctl rule for -u {unit}"
|
||||||
|
untagged = [r for r in matching if "NOEXEC" not in r]
|
||||||
|
assert not untagged, f"untagged journalctl rule(s): {untagged}"
|
||||||
Reference in New Issue
Block a user