From ef590b8f1995c9e3d05f42aad946e00feee24b66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusei=20Garc=C3=ADa?= Date: Fri, 30 Oct 2026 21:35:02 -0600 Subject: [PATCH 1/4] feat: endurecer seguridad, instalador, backups verificados, tests y CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - login: límite de 5 intentos/5 min por IP; cookie SameSite=Strict + Secure con HTTPS - POST: rechaza Origin distinto del Host - /api/browse restringido a la carpeta personal - unzip seguro: anti Zip-Slip, sin symlinks, límite 2 GB / 20000 archivos - install.sh: JSON generado con python, contraseña por entorno (no argv), bind explícito - panel.py --reset-password - backup.py: verify_archive lee el tar.gz completo tras crearlo - tests unittest y workflow de GitHub Actions Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/ci.yml | 13 +++++ backup.py | 11 ++++ install.sh | 44 +++++++-------- panel.py | 93 ++++++++++++++++++++++++++++--- tests/test_core.py | 116 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 245 insertions(+), 32 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 tests/test_core.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3637fc7 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,13 @@ +name: CI +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - run: python -m unittest discover -s tests -v + - run: python -m py_compile panel.py backup.py + - run: sudo apt-get install -y shellcheck && shellcheck -S warning install.sh diff --git a/backup.py b/backup.py index ca1854a..aa88f25 100755 --- a/backup.py +++ b/backup.py @@ -173,6 +173,16 @@ def rd(): return False, str(e) +def verify_archive(path): + """Lee el tar.gz completo (valida CRC de gzip y estructura). Lanza si está corrupto.""" + with _tarfile.open(path, "r:gz") as tf: + for m in tf: + if m.isfile(): + f = tf.extractfile(m) + while f.read(1 << 20): + pass + + def run_backup(server_dir, world_name, backup_dir, send_fn=None, tag=None, retention_days=7, keep_monthly=True, log=None, progress=None): @@ -236,6 +246,7 @@ def prog(pct, stage): say(f"omitidos {skipped} temporales que el server borró a mitad del backup") size = _os.path.getsize(dest) / 1e9 prog(90, f"verificando ({size:.2f} GB)") + verify_archive(dest) say(f"OK {name} ({size:.2f} GB)") except Exception as e: try: diff --git a/install.sh b/install.sh index d469293..5dffe3d 100755 --- a/install.sh +++ b/install.sh @@ -96,28 +96,26 @@ if [ -f "$CFG_FILE" ] && [ "$FORCE" = 0 ] && [ "$NON_INT" = 0 ]; then [[ "$ow" =~ ^[sSyY]$ ]] || { say "conservo config existente"; } fi if [ ! -f "$CFG_FILE" ] || [ "$FORCE" = 1 ] || [[ "${ow:-}" =~ ^[sSyY]$ ]]; then - # start_cmd como array JSON: respeta comillas simples/dobles - # shellcheck disable=SC2206 - read -r -a CMD_ARR <<< "$START_CMD" - START_JSON=$(printf '"%s",' "${CMD_ARR[@]}"); START_JSON="[${START_JSON%,}]" - cat > "$CFG_FILE" <= LOGIN_MAX_FAILS + + +def login_failed(ip): + with _sessions_lock: + _login_fails.setdefault(ip, []).append(time.time()) + + +def login_ok(ip): + with _sessions_lock: + _login_fails.pop(ip, None) + + +HTTPS_ON = False + + CFG = load_config() SERVER_DIR = CFG["server_dir"] @@ -4619,6 +4645,29 @@ def list_mods(): return out +MAX_UNZIP_BYTES = 2 * 1024 * 1024 * 1024 +MAX_UNZIP_FILES = 20000 + + +def safe_extract_zip(zp, dest_dir): + """Extrae un zip rechazando Zip-Slip, symlinks y zip bombs.""" + import zipfile as _zf + root = os.path.realpath(dest_dir) + with _zf.ZipFile(zp) as z: + infos = z.infolist() + if len(infos) > MAX_UNZIP_FILES: + raise ValueError("zip con demasiados archivos") + if sum(i.file_size for i in infos) > MAX_UNZIP_BYTES: + raise ValueError("zip descomprimido excede el límite de 2 GB") + for m in infos: + if (m.external_attr >> 16) & 0o170000 == 0o120000: + continue # symlink + target = os.path.realpath(os.path.join(root, m.filename)) + if target != root and not target.startswith(root + os.sep): + continue + z.extract(m, root) + + def handle_upload(handler, dest_rel): dest_dir = safe_fs_path(dest_rel or "") if dest_dir is None: @@ -4678,13 +4727,7 @@ def handle_upload(handler, dest_rel): continue zp = os.path.join(dest_dir, fname) try: - with _zf.ZipFile(zp) as z: - for m in z.infolist(): - # anti Zip-Slip - rel = os.path.normpath(m.filename).lstrip("/") - if rel.startswith("..") or os.path.isabs(m.filename): - continue - z.extract(m, dest_dir) + safe_extract_zip(zp, dest_dir) os.remove(zp) done.append(fname) except Exception as e: @@ -4872,7 +4915,10 @@ def do_GET(self): if u.path == "/api/browse": qs = parse_qs(u.query) raw = ((qs.get("path", [""]) or [""])[0] or "").strip() or "~" + home = os.path.realpath(os.path.expanduser("~")) p = os.path.realpath(os.path.expanduser(raw)) + if p != home and not p.startswith(home + os.sep): + return self.send_json({"ok": False, "msg": "Solo se puede explorar dentro de tu carpeta personal"}, code=403) if not os.path.isdir(p): return self.send_json({"ok": False, "msg": "No existe o sin acceso"}, code=404) try: @@ -4888,7 +4934,7 @@ def do_GET(self): ready = os.path.isfile(os.path.join(full, "start.sh")) or \ os.path.isfile(os.path.join(full, "server.properties")) dirs.append({"name": n, "ready": ready}) - parent = os.path.dirname(p) if p != "/" else "/" + parent = os.path.dirname(p) if p != home else home return self.send_json({"ok": True, "path": p, "parent": parent, "dirs": dirs, "home": os.path.expanduser("~")}) @@ -5036,8 +5082,16 @@ def do_GET(self): self.send_response(404) self.end_headers() + def _same_origin(self): + origin = self.headers.get("Origin") + if not origin: + return True + return urlparse(origin).netloc == self.headers.get("Host", "") + def do_POST(self): u = urlparse(self.path) + if not self._same_origin(): + return self.send_json({"ok": False, "msg": "Origen no permitido"}, code=403) if u.path == "/api/upload": # binario: no pre-leer el cuerpo como texto if u.path not in PUBLIC_PATHS and self._need_auth(): @@ -5054,19 +5108,25 @@ def do_POST(self): payload = {} if u.path == "/api/login": pw = payload.get("password", "") + ip = self.client_address[0] + if login_blocked(ip): + return self.send_json({"ok": False, "msg": "Demasiados intentos. Espera 5 minutos."}, code=429) if auth_enabled() and verify_password(pw, CFG.get("panel_password_hash", "")): + login_ok(ip) tok = new_session() body = json.dumps({"ok": True}).encode() self.send_response(200) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) - self.send_header("Set-Cookie", f"pksess={tok}; HttpOnly; Path=/; SameSite=Lax") + self.send_header("Set-Cookie", f"pksess={tok}; HttpOnly; Path=/; SameSite=Strict; Max-Age={SESSION_TTL}" + + ("; Secure" if HTTPS_ON else "")) self.end_headers() try: self.wfile.write(body) except (BrokenPipeError, ConnectionResetError): pass return + login_failed(ip) time.sleep(1) return self.send_json({"ok": False, "msg": "Contraseña incorrecta"}, code=401) @@ -5455,7 +5515,21 @@ def do_POST(self): caches.open('pk1').then(ch=>ch.put(e.request,c)).catch(()=>{});return r;}).catch(()=>caches.match(e.request)));});""" PWA_ICON = """""" +def reset_password_cli(): + import getpass + pw = getpass.getpass("Nueva contraseña del panel (mín. 8): ") + if len(pw) < 8: + sys.exit("Mínimo 8 caracteres") + if pw != getpass.getpass("Repite la contraseña: "): + sys.exit("No coinciden") + save_panel_setting("panel_password_hash", hash_password(pw)) + print("Contraseña actualizada. Reinicia: systemctl --user restart pkhosting.service") + + if __name__ == "__main__": + if "--reset-password" in sys.argv: + reset_password_cli() + sys.exit(0) bind = CFG.get("bind", "127.0.0.1") server = ThreadingHTTPServer((bind, PORT), PKHostingPanelHandler) cert, key = CFG.get("ssl_cert"), CFG.get("ssl_key") @@ -5466,6 +5540,7 @@ def do_POST(self): ctx.load_cert_chain(cert, key) server.socket = ctx.wrap_socket(server.socket, server_side=True) scheme = "https" + HTTPS_ON = True print(f"[PKHosting] Ejecutando en {scheme}://{bind}:{PORT}", flush=True) try: server.serve_forever() diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..d7d5eac --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,116 @@ +import io +import json +import os +import sys +import tarfile +import tempfile +import time +import unittest +import zipfile + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import backup # noqa: E402 +import panel # noqa: E402 + + +class ConfigTest(unittest.TestCase): + def test_extra_keys_survive_load(self): + with tempfile.TemporaryDirectory() as d: + path = os.path.join(d, "c.json") + with open(path, "w") as f: + json.dump({"panel_password_hash": "a$b", "bind": "0.0.0.0", + "servers": [{"id": "x"}], "mc_port": 25570}, f) + old = panel.CONFIG_FILE + panel.CONFIG_FILE = path + try: + cfg = panel.load_config() + finally: + panel.CONFIG_FILE = old + self.assertEqual(cfg["panel_password_hash"], "a$b") + self.assertEqual(cfg["bind"], "0.0.0.0") + self.assertEqual(cfg["servers"], [{"id": "x"}]) + self.assertEqual(cfg["mc_port"], 25570) + + +class AuthTest(unittest.TestCase): + def test_hash_roundtrip(self): + h = panel.hash_password("secreto123") + self.assertTrue(panel.verify_password("secreto123", h)) + self.assertFalse(panel.verify_password("otra", h)) + self.assertFalse(panel.verify_password("x", "basura")) + + def test_login_rate_limit(self): + ip = "203.0.113.9" + panel.login_ok(ip) + for _ in range(panel.LOGIN_MAX_FAILS): + self.assertFalse(panel.login_blocked(ip)) + panel.login_failed(ip) + self.assertTrue(panel.login_blocked(ip)) + panel.login_ok(ip) + self.assertFalse(panel.login_blocked(ip)) + + +class ZipTest(unittest.TestCase): + def _zip(self, d, entries): + zp = os.path.join(d, "a.zip") + with zipfile.ZipFile(zp, "w") as z: + for name, data in entries: + z.writestr(name, data) + return zp + + def test_zip_slip_blocked(self): + with tempfile.TemporaryDirectory() as d: + dest = os.path.join(d, "dest") + os.makedirs(dest) + zp = self._zip(d, [("../evil.txt", "x"), ("/abs.txt", "x"), ("ok/a.txt", "hi")]) + panel.safe_extract_zip(zp, dest) + self.assertFalse(os.path.exists(os.path.join(d, "evil.txt"))) + self.assertTrue(os.path.isfile(os.path.join(dest, "ok", "a.txt"))) + + def test_zip_bomb_rejected(self): + with tempfile.TemporaryDirectory() as d: + zp = self._zip(d, [("a.txt", "x")]) + old = panel.MAX_UNZIP_BYTES + panel.MAX_UNZIP_BYTES = 0 + try: + with self.assertRaises(ValueError): + panel.safe_extract_zip(zp, d) + finally: + panel.MAX_UNZIP_BYTES = old + + +class BackupTest(unittest.TestCase): + def test_verify_detects_corruption(self): + with tempfile.TemporaryDirectory() as d: + p = os.path.join(d, "a.tar.gz") + with tarfile.open(p, "w:gz") as t: + info = tarfile.TarInfo("x") + data = b"hello" * 1000 + info.size = len(data) + t.addfile(info, io.BytesIO(data)) + backup.verify_archive(p) + with open(p, "rb") as f: + raw = bytearray(f.read()) + raw[20] ^= 0xFF + with open(p, "wb") as f: + f.write(raw) + with self.assertRaises(Exception): + backup.verify_archive(p) + + def test_retention_keeps_monthly_and_recent(self): + with tempfile.TemporaryDirectory() as d: + names = ["pkhosting-20240110-040000.tar.gz", # viejo, no último del mes + "pkhosting-20240128-040000.tar.gz", # último de enero → se queda + "pkhosting-20240201-040000.tar.gz"] # viejo, único de febrero → se queda + old = time.time() - 400 * 86400 + for n in names: + p = os.path.join(d, n) + open(p, "wb").close() + os.utime(p, (old, old)) + kept, deleted = backup.prune_backups(d, retention_days=7, keep_monthly=True) + self.assertEqual(deleted, ["pkhosting-20240110-040000.tar.gz"]) + self.assertEqual(len(kept), 2) + + +if __name__ == "__main__": + unittest.main() From 4012326ec8811b8c52c4804ff19fc1c8c6fc1186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusei=20Garc=C3=ADa?= Date: Fri, 30 Oct 2026 21:36:49 -0600 Subject: [PATCH 2/4] =?UTF-8?q?feat(ui):=20tema=20claro,=20layout=20m?= =?UTF-8?q?=C3=B3vil,=20fuentes=20sin=20Google,=20nav=20accesible=20por=20?= =?UTF-8?q?teclado?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Sonnet 5.5 --- panel.py | 95 ++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 72 insertions(+), 23 deletions(-) diff --git a/panel.py b/panel.py index 421181f..be49f0b 100755 --- a/panel.py +++ b/panel.py @@ -1703,8 +1703,6 @@ def read_console_lines(limit=250): - - + @@ -2607,32 +2653,32 @@ def read_console_lines(limit=250): -