Is AI-Generated Code Secure? Risks and Defense
On this page
Learning Objective
Recognize the security weaknesses AI coding tools commonly introduce, understand why models produce them, and build a defense that combines secure-by-default instructions, security-focused review and automated scanning in CI.
Concept Explanation
Models learn from public code, and public code is full of insecure examples: string-concatenated SQL in tutorials, disabled certificate checks in quick fixes, hard-coded keys in sample apps. Models also optimize for code that works for the example in front of them, and the insecure version often works. The result is measurable. Veracode's 2025 GenAI Code Security Report tested more than 100 models on 80 coding tasks and found that the generated code introduced an OWASP Top 10 vulnerability in 45 percent of cases, that security performance had not improved as models got better at producing working code, and that cross-site scripting and log injection were mishandled in the large majority of relevant tasks.
People make it worse. A Stanford study by Perry and colleagues, presented at the ACM CCS conference in 2023, found that participants with access to an AI assistant wrote significantly less secure code than those without, and were more likely to believe their code was secure. Confident, clean-looking output lowers our guard exactly when we should raise it.
The weaknesses cluster in familiar places. Injection: SQL, shell commands and file paths built from user input. Broken access control: endpoints that check that a user is logged in but not that they own the record. Cryptography misuse: weak algorithms, hard-coded keys, disabled TLS verification. Secrets in code, logs and error messages. Unsafe deserialization and server-side request forgery where code fetches URLs supplied by users. Overly permissive configuration, such as CORS allowing every origin or debug mode in production.
Defense has three layers. First, tell the agent your security rules in the instruction file and in specs: parameterized queries only, authorization checks on every endpoint through the existing policy helper, never log request bodies, and so on, with the reason for each. Agents follow concrete rules much better than "write secure code". Second, review with security in mind (Day 14), especially new endpoints, queries, file and network access and configuration, or use a dedicated security review subagent or tool. Third, automate: static analysis such as Semgrep or CodeQL, dependency scanning and secret scanning in CI, as required checks, so that insecure patterns are caught regardless of who or what wrote the code.
Agents can also be part of the solution. They are good at finding vulnerabilities when asked specifically, at fixing scanner findings, and at writing tests that prove an attack no longer works. The same capability that writes an injection bug can find one; what matters is that the workflow asks.
| Weakness | Typical AI-generated form | Defense |
|---|---|---|
| SQL injection | f-string or concatenated SQL | Parameterized queries rule, Semgrep rule |
| Path traversal | open(base + user_path) | Resolve and check against the base directory |
| Broken access control | Checks login, not ownership | Policy helper on every endpoint, review |
| Secrets exposure | Keys in code or logs | Secret scanning, deny reads of secret files |
| Weak crypto or TLS | verify=False, MD5 passwords | Lint rules, approved crypto library only |
| Permissive config | CORS *, debug=True | Config review, environment-specific defaults |
Worked Example: An Insecure Endpoint, Its Fix and the Scanner That Catches It
The first version is typical assistant output: it works for the happy path and contains two vulnerabilities. The fixed version and the CI scan follow.
# Typical generated code: works, but injectable and missing an ownership check.
@app.get("/invoices/<invoice_id>/pdf")
@login_required
def invoice_pdf(invoice_id):
row = db.execute(f"SELECT path FROM invoices WHERE id = '{invoice_id}'").fetchone() # SQL injection
return send_file(os.path.join(PDF_DIR, row["path"])) # trusts stored path
# Fixed: parameterized query, ownership enforced in the query, path confined to PDF_DIR.
@app.get("/invoices/<int:invoice_id>/pdf")
@login_required
def invoice_pdf(invoice_id: int):
row = db.execute(
"SELECT path FROM invoices WHERE id = ? AND customer_id = ?",
(invoice_id, current_user.customer_id),
).fetchone()
if row is None:
abort(404) # same response whether missing or not yours
pdf = (PDF_DIR / row["path"]).resolve()
if not pdf.is_relative_to(PDF_DIR.resolve()):
abort(404)
return send_file(pdf)# .github/workflows/security.yml: required check on every pull request
name: security
on: [pull_request]
jobs:
semgrep:
runs-on: ubuntu-latest
container: semgrep/semgrep
steps:
- uses: actions/checkout@v6
- run: semgrep scan --config p/python --config p/owasp-top-ten --errorReturning 404 both when the invoice does not exist and when it belongs to someone else avoids revealing which invoice ids are valid. With the scan required on every pull request, the f-string query fails the build whether a person or an agent wrote it.
Real-World Examples
- Veracode's 2025 GenAI Code Security Report, published in July 2025, found security flaws from the OWASP Top 10 in 45 percent of AI-generated code samples across more than 100 models, with Java failing over 70 percent of security-relevant tasks.
- Perry, Srivastava, Kumar and Boneh's study "Do Users Write More Insecure Code with AI Assistants?" (ACM CCS 2023) found participants using an AI assistant produced less secure code and were more confident in its security than a control group.
Review Questions & Answers
They learn from public code that contains many insecure examples, and they optimize for code that works for the example in front of them; the insecure version frequently works for that case.
Participants with an AI assistant wrote less secure code than those without and were more likely to believe their code was secure, showing that confident output lowers vigilance.
It does not tell the agent what secure means in your codebase. Concrete rules, such as parameterized queries only and the specific authorization helper to call, give the agent actionable constraints it can follow and reviewers can check.
Filtering by the current customer in the query guarantees only the user's own invoices are ever returned, and returning 404 in both the missing and not-yours cases avoids leaking which invoice ids exist.