diff --git a/archive_host.py b/archive_host.py index cd0d237..1fa3189 100644 --- a/archive_host.py +++ b/archive_host.py @@ -109,6 +109,15 @@ def _run_unar(entry: Path, out: Path) -> dict: return {"ok": False, "error": "extract-too-large", "target": str(out)} if proc.returncode != 0: return {"ok": False, "error": f"exit-{proc.returncode}", "target": str(out)} + # ARCH-SYMLINK-01: unar материализует симлинки из архива → парсеры/MCP/скачивание + # пошли бы ПО ним и прочитали произвольный файл хоста (/etc/passwd, ~/.claude). + # Удаляем все симлинки сразу после распаковки. + for p in out.rglob("*"): + try: + if p.is_symlink(): + p.unlink() + except OSError: + pass files = sum(1 for p in out.rglob("*") if p.is_file()) return {"ok": True, "files": files, "target": str(out)} diff --git a/main.py b/main.py index ee49ec9..ec9ca8d 100644 --- a/main.py +++ b/main.py @@ -133,7 +133,9 @@ else: list_user_files, stream_claude, ) -app = FastAPI(title="smeta-web") +# docs_url/redoc/openapi выключены: полная карта API (вкл. /api/admin/*) не должна +# отдаваться анониму (пентест INFO-OPENAPI-01). +app = FastAPI(title="smeta-web", docs_url=None, redoc_url=None, openapi_url=None) app.mount("/static", StaticFiles(directory="static"), name="static") from path_safety import UnsafePath, safe_work_dir @@ -149,7 +151,7 @@ MAX_MESSAGE_LEN = 10_000 # ⚠️ Версия UI — единый источник. БАМПАТЬ ПРИ КАЖДОМ ДЕПЛОЕ (формат: YYYY-MM-DD + буква). # Фронт берёт её через GET /api/version (chat.html + admin.html, элемент .app-version). -APP_VERSION = "2026-07-19c" +APP_VERSION = "2026-07-19d" # Audit: path → action name mapping _AUDIT_MAP = [ @@ -875,14 +877,22 @@ async def download_file(filename: str, request: Request): user = _get_user(request) tab_id = request.headers.get("x-tab-id", "default") safe_name = Path(filename).name - fpath = get_work_dir(user, tab_id) / safe_name + work_dir = get_work_dir(user, tab_id) + fpath = work_dir / safe_name if not fpath.exists() or not fpath.is_file(): owner = _admin_tab_owner(request, user, tab_id) if owner: - fpath = get_work_dir(owner, tab_id) / safe_name + work_dir = get_work_dir(owner, tab_id) + fpath = work_dir / safe_name if not fpath.exists() or not fpath.is_file(): raise HTTPException(404, "File not found") - return FileResponse(fpath, filename=filename) + # ARCH-SYMLINK-01: файл-симлинк из враждебного архива не должен уводить за work_dir + # (единый guard с admin-путём). DISP-01: имя в заголовке — safe_name, не сырой param. + try: + fpath.resolve().relative_to(work_dir.resolve()) + except ValueError: + raise HTTPException(404, "File not found") + return FileResponse(fpath, filename=safe_name) @app.post("/api/extract_complaints") diff --git a/tests/test_archive_bomb.py b/tests/test_archive_bomb.py index 7a9fa35..0d317dd 100644 --- a/tests/test_archive_bomb.py +++ b/tests/test_archive_bomb.py @@ -59,6 +59,42 @@ def test_bomb_extraction_killed_and_cleaned(monkeypatch, tmp_path): assert not out.exists() or archive_host._dir_size(out) == 0 # частичное снесено +class _FakeSymlinkProc: + """Имитация unar, кладущего symlink + обычный файл, затем выход 0.""" + def __init__(self, out: Path, target: Path): + out.mkdir(parents=True, exist_ok=True) + (out / "real.gge").write_bytes(b"") + try: + (out / "evil.gge").symlink_to(target) # симлинк на секрет вне out + except OSError: + pass + self.returncode = 0 + + def poll(self): + return 0 + + def wait(self, timeout=None): + return + + def kill(self): + self.returncode = -9 + + +def test_extraction_strips_symlinks(monkeypatch, tmp_path): + secret = tmp_path / "secret_outside.txt" + secret.write_text("HOST-SECRET") + out = tmp_path / "out" + monkeypatch.setattr(archive_host, "_backend", lambda: "unar") + monkeypatch.setattr(archive_host.subprocess, "Popen", + lambda *a, **k: _FakeSymlinkProc(out, secret)) + res = archive_host._run_unar(tmp_path / "evil.rar", out) + assert res["ok"] is True + names = {p.name for p in out.rglob("*")} + assert "real.gge" in names + assert "evil.gge" not in names # симлинк удалён + assert secret.read_text() == "HOST-SECRET" # цель не тронута + + def test_dir_size_counts_files(tmp_path): (tmp_path / "a").write_bytes(b"x" * 100) sub = tmp_path / "s" diff --git a/tests/test_archive_host.py b/tests/test_archive_host.py index 5b53c80..c360459 100644 --- a/tests/test_archive_host.py +++ b/tests/test_archive_host.py @@ -27,18 +27,29 @@ def test_no_backend(): def test_extraction_wiring(): - orig_b, orig_run = ah._backend, subprocess.run + orig_b, orig_popen = ah._backend, subprocess.Popen ah._backend = lambda: "unar" - def fake_run(cmd, **kw): + def fake_popen(cmd, **kw): out = Path(cmd[cmd.index("-o") + 1]) (out / "sub").mkdir(parents=True, exist_ok=True) (out / "sub" / "смета.xlsx").write_text("x") - class R: - returncode = 0 - return R() - subprocess.run = fake_run + class P: # Popen-подобный: сразу завершён успехом + returncode = 0 + + def poll(self): + return 0 + + def wait(self, timeout=None): + return + + def kill(self): + pass + + return P() + + subprocess.Popen = fake_popen try: wd = Path(tempfile.mkdtemp()) r = ah.extract_rarlike(Path("09.0200.rar"), wd) @@ -46,7 +57,7 @@ def test_extraction_wiring(): assert r["files"] == 1, r assert (wd / "09.0200_extracted" / "sub" / "смета.xlsx").exists() finally: - ah._backend, subprocess.run = orig_b, orig_run + ah._backend, subprocess.Popen = orig_b, orig_popen if __name__ == "__main__": diff --git a/tests/test_block1_auth.py b/tests/test_block1_auth.py index 5e586df..e11c9cd 100644 --- a/tests/test_block1_auth.py +++ b/tests/test_block1_auth.py @@ -71,6 +71,24 @@ def test_deprecated_pages_redirect(env): assert r.headers.get("location", "").endswith("/"), f"{url} → {r.headers.get('location')}" +def test_download_symlink_escape_blocked(env): + """ARCH-SYMLINK-01: symlink в work_dir, указывающий ВНЕ его (из враждебного архива), + не должен отдаваться через /api/files (иначе чтение /etc/passwd, ~/.claude).""" + auth, main, client, tmp = env + secret = tmp / "host_secret.txt" + secret.write_text("HOST-SECRET-LEAK") + wd = main.get_work_dir("mallory@x", "sym-tab") + link = wd / "evil.gge" + try: + link.symlink_to(secret) + except OSError: + import pytest as _pt + _pt.skip("symlink not supported") + r = client.get("/api/files/evil.gge", headers=_h(auth, user="mallory@x", tab="sym-tab")) + assert r.status_code == 404 # симлинк-escape → 404, не утечка + assert "HOST-SECRET-LEAK" not in r.text + + def test_chat_bad_tab_id_clean_400(env): """Fable P2: traversal-tab_id в /api/chat должен давать чистый 400 ДО стрима/save, а не грязный обрыв внутри генератора с мусорной строкой в БД."""