SQL and Code Injection in LLM Contexts
What You'll Learn
You'll learn why LLMs that generate SQL queries or code pose unique injection risks and how to prevent them from becoming attack vectors.
The Core Problem
When LLMs interact with databases or execute code on behalf of users, they can inadvertently create injection vulnerabilities. Unlike traditional injection attacks where malicious input comes directly from users, LLM-mediated injection occurs when the model generates dangerous SQL or code based on manipulated prompts.
Think of it like a translator who doesn't understand security context: if you trick the translator into translating "give me all passwords" into SQL, they'll faithfully produce SELECT * FROM passwords without realizing the implications.
Key Risk Scenarios
SQL Generation: An LLM creates database queries based on natural language requests. A malicious user might prompt: "Show me all users where name is 'admin'--' OR '1'='1". If the LLM naively converts this to SQL, it could expose the entire user table.
Code Execution: When LLMs generate Python, JavaScript, or shell commands that your system executes, injected instructions like "delete all files" could be catastrophically interpreted as valid code.
Prevention Strategies
-
Parameterized Queries: Never let LLMs generate raw SQL strings. Use query builders or ORMs where the LLM only specifies parameters, not full queries.
-
Code Sandboxing: Execute LLM-generated code in isolated environments with strict resource limits and no access to sensitive systems.
-
Output Validation: Parse and validate generated SQL/code against allowlists of safe operations before execution.
-
Minimal Permissions: Database and execution contexts should have least-privilege access—read-only when possible.
Key Takeaway: LLMs generating executable code or SQL create injection risks that require parameterization, sandboxing, validation, and privilege limitation—treating model output as untrusted input just like user submissions.