Static analysis (SAST) check · Python

Llm output to sink from request input (Python)

Text generated by a language model reaches code execution, a shell command, a SQL statement or an unescaped HTML/template sink.

Why it matters

Model output follows instructions planted in its input (prompt injection), so treat it as untrusted user input.

How to fix it

Never eval, exec or shell out model output. Parse it into a fixed structure (JSON schema, an enum of allowed actions), pass values to SQL as bound parameters, and let the template engine escape it.

Example

The rule's own test fixtures, verbatim: the test suite requires the rule to report the first and not the second.

Vulnerable: reported (Python)
import subprocess

from openai import OpenAI

client = OpenAI()


def run_suggested_command(task):
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        max_tokens=200,
        messages=[{"role": "user", "content": task}],
    )
    command = resp.choices[0].message.content
    subprocess.run(command, shell=True)
Fixed: not reported (Python)
import json
import subprocess

from openai import OpenAI

client = OpenAI()
ALLOWED = {"status": ["git", "status"], "log": ["git", "log", "-5"]}


def run_suggested_command(task):
    resp = client.chat.completions.create(
        model="gpt-4o-mini",
        max_tokens=200,
        messages=[{"role": "user", "content": task}],
    )
    action = json.loads(resp.choices[0].message.content)["action"]
    print(action)
    subprocess.run(ALLOWED["status"], check=True)

What TrustIvan reads

Runs on repository scans of Python source once static analysis is turned on (SAST_RULES and the separately built analyzer image); it is off by default.

Weakness classes and references

Terms: SAST (static application security testing), Taint analysis, CWE (Common Weakness Enumeration), OWASP Top 10

All static analysis (SAST) checks · The whole catalogue · How this works in TrustIvan · Documentation

See TrustIvan on your own estate.

Book thirty minutes with an engineer and bring an image, a repository or a cloud account, or start free on the hosted service.