From 1489a52916128105eb2663c144d2e97e4183e8d4 Mon Sep 17 00:00:00 2001 From: Satyanarayana Vuppala Date: Fri, 20 Nov 2026 13:54:53 +0000 Subject: [PATCH] security: owner-only store, race-free credential files, safer defaults Found in end-to-end testing before go-live: - ~/.secfoo was 0755 with 0644 files: on a shared machine or CI runner any local user could read every prompt (the scanned source), report and finding. The store root is now 0700, and an older store is tightened. - cloud.toml, memory.toml and claude-mcp-config.json were written with the default umask and chmod-ed afterwards, so a secret was briefly readable (and stayed readable until the chmod if the file pre-existed). They are now created 0600 via os.open. - 'secfoo config init' wrote an active Atlassian MCP entry, so every claude run executed 'npx -y mcp-remote@latest' (an unpinned download) and started an OAuth flow even for users who never use Atlassian. It is now a commented-out example, like the others. - Docker: the image installed an unpinned 'secfoo' after a fixed 60s sleep, so a release image could contain the previous version. release.yml now passes the version as a build arg and the Dockerfile retries until PyPI serves it. - release.yml no longer interpolates inputs.tag into a shell script; the value reaches the script as a variable. - install.sh ignored a writable PREFIX whose bin/ did not exist yet and silently installed to ~/.local/bin. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 15 ++++-- Dockerfile | 11 ++++- SECURITY.md | 6 +++ install.sh | 5 ++ src/secfoo/cloud.py | 7 ++- src/secfoo/config.example.toml | 12 +++-- src/secfoo/config.py | 30 +++++++++++- src/secfoo/mcp.py | 5 +- src/secfoo/memory.py | 8 +--- tests/test_store_privacy.py | 87 ++++++++++++++++++++++++++++++++++ 10 files changed, 161 insertions(+), 25 deletions(-) create mode 100644 tests/test_store_privacy.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a981618..7e65e19 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,14 +38,17 @@ jobs: with: ref: ${{ inputs.tag }} - id: check + env: + # Through the environment, not ${{ }} inside the script, so the tag + # text can never become shell code. + TAG: ${{ inputs.tag }} run: | - TAG_VERSION="${{ inputs.tag }}" - TAG_VERSION="${TAG_VERSION#v}" + TAG_VERSION="${TAG#v}" PKG_VERSION=$(grep -oP '(?<=__version__ = ")[^"]+' src/secfoo/__about__.py) echo "Tag version: $TAG_VERSION" echo "Package version: $PKG_VERSION" if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then - echo "::error::Tag ${{ inputs.tag }} does not match src/secfoo/__about__.py's __version__ ($PKG_VERSION). Bump __about__.py and retag." + echo "::error::Tag $TAG does not match src/secfoo/__about__.py's __version__ ($PKG_VERSION). Bump __about__.py and retag." exit 1 fi echo "version=$PKG_VERSION" >> "$GITHUB_OUTPUT" @@ -190,12 +193,14 @@ jobs: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Wait for the new version to be installable from PyPI - run: sleep 60 - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: . push: true + # Pinned so the image is exactly the release; the Dockerfile retries + # while PyPI's index catches up. + build-args: | + SECFOO_VERSION=${{ needs.check-version.outputs.version }} tags: | ghcr.io/secfoo-com/secfoo:${{ needs.check-version.outputs.version }} ghcr.io/secfoo-com/secfoo:latest diff --git a/Dockerfile b/Dockerfile index b8da6c2..6375f51 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,16 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends git \ && rm -rf /var/lib/apt/lists/* -RUN pip install --no-cache-dir secfoo +# The release workflow passes the version it just published, so the image +# tagged X.Y.Z really contains secfoo X.Y.Z -- an unpinned install could pick +# up the previous release while PyPI's index catches up. Retries cover that +# lag; a local `docker build .` without the arg installs the latest release. +ARG SECFOO_VERSION= +RUN for attempt in 1 2 3 4 5 6; do \ + pip install --no-cache-dir "secfoo${SECFOO_VERSION:+==${SECFOO_VERSION}}" && break; \ + [ "$attempt" = 6 ] && exit 1; sleep 20; \ + done \ + && secfoo --version WORKDIR /workspace diff --git a/SECURITY.md b/SECURITY.md index b65d603..30e451f 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -36,6 +36,12 @@ that may itself be untrusted or adversarial, so it's rendered defensively: report markdown never executes embedded HTML/scripts, and Mermaid diagrams render with `securityLevel: "strict"`. +The store (`~/.secfoo`, or `SECFOO_HOME`) holds prompts with the scanned +source, reports and findings, so secfoo keeps its root directory `0700` +(tightening one created by an older version) and writes files that hold a +credential (`cloud.toml`, `memory.toml`, `claude-mcp-config.json`) as `0600` +from the moment they are created. + ## Supported versions Only the latest published release on PyPI is supported. Please upgrade diff --git a/install.sh b/install.sh index 6eb2af2..c18893f 100755 --- a/install.sh +++ b/install.sh @@ -92,6 +92,11 @@ echo "Checksum OK." chmod +x "$TMP_DIR/$ASSET" INSTALL_DIR="$PREFIX/bin" +# A writable PREFIX without a bin/ yet (e.g. PREFIX=$HOME/opt) gets one, +# rather than silently installing somewhere else. +if [ ! -d "$INSTALL_DIR" ] && [ -w "$PREFIX" ]; then + mkdir -p "$INSTALL_DIR" +fi if [ ! -w "$INSTALL_DIR" ] 2>/dev/null; then INSTALL_DIR="$HOME/.local/bin" mkdir -p "$INSTALL_DIR" diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index 9792323..e0be59b 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -28,7 +28,7 @@ else: import tomli as tomllib -from secfoo.config import CLOUD_CONFIG_PATH +from secfoo.config import CLOUD_CONFIG_PATH, write_private_text from secfoo.egress import PORTAL_HOST, EgressError, require_origin from secfoo.storage.models import AssessmentRecord, RunRecord from secfoo.storage.repository import RunRepository @@ -105,12 +105,11 @@ def save_cloud_config(config: CloudConfig, path: Path | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) portal_url = _portal_origin(config.portal_url) api_key = _require_ingest_key(config.api_key) - path.write_text( + write_private_text( + path, f'api_key = "{_toml_escape(api_key)}"\n' f'portal_url = "{_toml_escape(portal_url)}"\n', - encoding="utf-8", ) - path.chmod(0o600) def delete_cloud_config(path: Path | None = None) -> None: diff --git a/src/secfoo/config.example.toml b/src/secfoo/config.example.toml index e3a1e1d..0cfa2db 100644 --- a/src/secfoo/config.example.toml +++ b/src/secfoo/config.example.toml @@ -59,11 +59,13 @@ enabled = true # Example: Atlassian (Confluence/Jira) via the official Rovo MCP server, # bridged through the `mcp-remote` npm package (stdio transport: secfoo -# just needs a command + args to run). -[[mcp_servers]] -name = "Atlassian-Rovo-MCP" -command = "npx" -args = ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] +# just needs a command + args to run). Uncomment to enable: every claude run +# then starts this command, and `npx -y` downloads the package if needed -- +# consider pinning a version you have reviewed instead of @latest. +# [[mcp_servers]] +# name = "Atlassian-Rovo-MCP" +# command = "npx" +# args = ["-y", "mcp-remote@latest", "https://mcp.atlassian.com/v1/mcp/authv2"] # Example: a plain remote MCP server reachable directly over HTTP/SSE # (no bridge needed) -- use `url` + `transport` instead of `command`. diff --git a/src/secfoo/config.py b/src/secfoo/config.py index 9d63e28..72c5923 100644 --- a/src/secfoo/config.py +++ b/src/secfoo/config.py @@ -21,12 +21,40 @@ def ensure_store_dirs() -> None: - STORE_DIR.mkdir(parents=True, exist_ok=True) + # Reports hold the scanned source, prompts and a map of its weaknesses, + # and the DB holds findings and key hashes: owner-only, like ~/.ssh. + # 0700 on the root is enough to keep other local users out of all of it. + STORE_DIR.mkdir(mode=0o700, parents=True, exist_ok=True) + _make_private(STORE_DIR) REPORTS_DIR.mkdir(parents=True, exist_ok=True) TMP_DIR.mkdir(parents=True, exist_ok=True) ATTACHMENTS_DIR.mkdir(parents=True, exist_ok=True) +def _make_private(directory: Path) -> None: + try: + if directory.stat().st_mode & 0o077: + directory.chmod(0o700) + except OSError: # not ours (a shared SECFOO_HOME) or a read-only mount: leave it + pass + + +def write_private_text(path: Path, text: str) -> None: + """Write a secret-bearing file that is never readable by others, not even + between creation and a later chmod (and tighten an existing file first).""" + path.parent.mkdir(parents=True, exist_ok=True) + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + try: + if hasattr(os, "fchmod"): # POSIX; O_CREAT's mode does not apply to an existing file + os.fchmod(fd, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as handle: + fd = -1 + handle.write(text) + finally: + if fd != -1: + os.close(fd) + + def run_dir(run_uuid: str) -> Path: return REPORTS_DIR / run_uuid diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index b33cd18..36b4f25 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -24,7 +24,7 @@ from dataclasses import dataclass from pathlib import Path -from secfoo.config import STORE_DIR +from secfoo.config import STORE_DIR, write_private_text from secfoo.settings import MCPServerConfig CLAUDE_MCP_CONFIG_PATH = STORE_DIR / "claude-mcp-config.json" @@ -81,10 +81,9 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: return None payload = {"mcpServers": {s.name: _server_to_standard_shape(s) for s in servers}} STORE_DIR.mkdir(parents=True, exist_ok=True) - CLAUDE_MCP_CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8") # Header values (the secfoo-memory bearer key, or any user server's # auth header) are secrets -- same 0600 as cloud.toml/memory.toml. - CLAUDE_MCP_CONFIG_PATH.chmod(0o600) + write_private_text(CLAUDE_MCP_CONFIG_PATH, json.dumps(payload, indent=2)) return CLAUDE_MCP_CONFIG_PATH diff --git a/src/secfoo/memory.py b/src/secfoo/memory.py index c4b4948..a1c6d61 100644 --- a/src/secfoo/memory.py +++ b/src/secfoo/memory.py @@ -36,7 +36,7 @@ else: import tomli as tomllib -from secfoo.config import STORE_DIR +from secfoo.config import STORE_DIR, write_private_text from secfoo.egress import EgressError, require_https_origin from secfoo.settings import MCPServerConfig @@ -94,11 +94,7 @@ def save_memory_config(config: MemoryConfig, path: Path | None = None) -> None: path = path or MEMORY_CONFIG_PATH path.parent.mkdir(parents=True, exist_ok=True) url = _memory_origin(config.url) - path.write_text( - f'api_key = "{_toml_escape(config.api_key)}"\nurl = "{_toml_escape(url)}"\n', - encoding="utf-8", - ) - path.chmod(0o600) + write_private_text(path, f'api_key = "{_toml_escape(config.api_key)}"\nurl = "{_toml_escape(url)}"\n') def delete_memory_config(path: Path | None = None) -> None: diff --git a/tests/test_store_privacy.py b/tests/test_store_privacy.py new file mode 100644 index 0000000..fa0abe2 --- /dev/null +++ b/tests/test_store_privacy.py @@ -0,0 +1,87 @@ +"""The local store and secret-bearing files are owner-only; the default config runs nothing.""" +from __future__ import annotations + +import stat +import sys +from pathlib import Path + +import pytest + +from secfoo import cloud, config, mcp, memory +from secfoo.settings import MCPServerConfig + +if sys.version_info >= (3, 11): + import tomllib +else: # Python 3.10 + import tomli as tomllib + +posix_only = pytest.mark.skipif(sys.platform == "win32", reason="POSIX permission bits") + + +def _mode(path: Path) -> int: + return stat.S_IMODE(path.stat().st_mode) + + +@pytest.fixture +def store(tmp_path, monkeypatch): + root = tmp_path / "store" + monkeypatch.setattr(config, "STORE_DIR", root) + monkeypatch.setattr(config, "REPORTS_DIR", root / "reports") + monkeypatch.setattr(config, "TMP_DIR", root / "tmp") + monkeypatch.setattr(config, "ATTACHMENTS_DIR", root / "attachments") + return root + + +@posix_only +def test_a_new_store_is_owner_only(store): + config.ensure_store_dirs() + assert _mode(store) == 0o700 + + +@posix_only +def test_an_existing_world_readable_store_is_tightened(store): + """Stores created by earlier versions were 0755: reports (scanned source, + findings) readable by every local user.""" + store.mkdir(mode=0o755) + store.chmod(0o755) + config.ensure_store_dirs() + assert _mode(store) == 0o700 + + +@posix_only +def test_write_private_text_creates_0600_and_tightens_an_existing_file(tmp_path): + fresh = tmp_path / "a" / "fresh.toml" + config.write_private_text(fresh, "k = 1\n") + assert _mode(fresh) == 0o600 and fresh.read_text() == "k = 1\n" + old = tmp_path / "old.toml" + old.write_text("api_key = 'previous'\nextra = 'longer content that must be truncated'\n") + old.chmod(0o644) + config.write_private_text(old, "api_key = 'new'\n") + assert _mode(old) == 0o600 and old.read_text() == "api_key = 'new'\n" + + +@posix_only +def test_credential_files_are_0600_even_when_a_readable_one_existed(tmp_path, monkeypatch): + cloud_path, memory_path = tmp_path / "cloud.toml", tmp_path / "memory.toml" + for path in (cloud_path, memory_path): + path.write_text("stale\n") + path.chmod(0o644) + cloud.save_cloud_config(cloud.CloudConfig(api_key="sfc_ingest_" + "a" * 40), cloud_path) + memory.save_memory_config(memory.MemoryConfig(api_key="mem-key"), memory_path) + assert _mode(cloud_path) == 0o600 and _mode(memory_path) == 0o600 + assert "stale" not in cloud_path.read_text() + memory_path.read_text() + + monkeypatch.setattr(mcp, "STORE_DIR", tmp_path) + monkeypatch.setattr(mcp, "CLAUDE_MCP_CONFIG_PATH", tmp_path / "claude-mcp-config.json") + written = mcp.write_claude_mcp_config( + [MCPServerConfig(name="x", url="https://mcp.example.com", transport="http", headers={"Authorization": "Bearer s"})]) + assert _mode(written) == 0o600 + + +def test_default_config_template_enables_no_mcp_server(): + """`secfoo config init` used to write an active Atlassian entry, so every + claude run started `npx -y mcp-remote@latest` (an unpinned download) and + an OAuth flow, whether or not the user uses Atlassian.""" + template = Path(config.__file__).with_name("config.example.toml").read_text(encoding="utf-8") + assert "mcp_servers" not in tomllib.loads(template) + assert "# [[mcp_servers]]\n# name = \"Atlassian-Rovo-MCP\"" in template # still documented