Is AI-Generated Code Secure? Common Vulnerabilities in AI-Built Applications

Is AI-Generated Code Secure?

AI now writes roughly half of all committed code, according to Veracode, and the uncomfortable question most teams haven’t stopped to ask is whether that code is actually safe to ship. The honest answer, backed by the largest 2026 studies, is no, not by default.

AI-generated code is not secure out of the box. Veracode’s 2026 GenAI Code Security Report, tracking more than 100 models, found an average security pass rate of just 56%, meaning roughly 44% of code-generation tasks introduced a known vulnerability when the prompt gave no security instruction. Those tasks covered four vulnerability classes (SQL injection, cross-site scripting, log injection and weak cryptography) in four languages, and ran against raw models with no agents, guardrails or human review, so 44% is the rate at which models generate flaws, not the rate at which flaws reach production. IOActive’s 2026 whitepaper, testing 27 models across 730 prompts and ~20,000 code samples, found 31.6% of samples fully exploitable, no model achieving 100% secure output, and infrastructure code (Dockerfiles, Terraform) failing security controls 70-97% of the time. The models write code that compiles almost 100% of the time and is secure barely half the time. The practical implication is simple: AI-generated code has to be treated like unreviewed code from a brand-new contributor, scanned, reviewed, and fixed before it ships, never shipped blind.

This guide gives you the full picture: what the data actually says, the common vulnerabilities that show up in AI-built apps, a 12-point audit checklist with the real tools for each check, the fix playbook, and when and how much an audit costs. It’s written for the founder, CTO, or technical lead who’s shipping AI-assisted code and needs to know what they’re exposed to. Finding and fixing these issues before launch is exactly what our AI code security audit does.

Key Highlights
  • The direct answer: no, not by default. AI writes compilable code ~100% of the time and secure code ~56% of the time (Veracode, 100+ models). About 44% of tasks introduce a known vulnerability with no security prompting.
  • It’s exploitable, not just theoretical. IOActive found 31.6% of AI-generated samples fully exploitable and no model hitting 100% secure output, even the best configuration still produced 90 vulnerabilities across the test set.
  • Infrastructure code is the worst. Default AI-generated Dockerfiles failed security controls 97.8% of the time and Terraform 71.8%. Treat AI infra code as unsafe until scanned.
  • The weakest categories: cross-site scripting (15% pass), log injection (12%), and broken authentication (consistently failed). SQL injection (83%) and basic crypto (87%) are relatively better, but “better” still isn’t safe.
  • Model choice is a security decision, but not a solution. The best model (GPT-5.5) reached 68%; reasoning models averaged 56% against 51% for the rest; coding-specialized models (51%) were no safer than general ones (52%). “We use the best model” is not a security strategy.
  • The audit that catches it: secrets scan, SAST, dependency/SCA scan, authorization review, headers/CORS, input validation, DAST, error handling, deserialization, CI/CD gates, compliance docs, and re-test, no single tool is enough.
  • The one rule that matters: treat AI output as untrusted input. Scan it, review the business logic and auth/crypto by hand, and gate it before merge.
Table Of Contents
Table Of Contents

What the Data Actually Says

Two large, credible 2026 studies anchor the answer, and they agree.

Veracode’s 2026 GenAI Code Security Report tracked more than 100 models over four testing snapshots under standardized conditions with no security-specific prompting. The headline: a 56% average security pass rate, essentially flat from 55% a year earlier, even as every other model capability climbed and syntax correctness approached 100%. Put plainly, about 44% of code-generation tasks produced a known vulnerability. The best single model (GPT-5.5) topped out at 68%, reasoning models averaged 56% against 51% for non-reasoning ones, and, tellingly, coding-specialized models (51%) were no safer than general-purpose ones (52%), being trained to write code faster doesn’t make it safer. The spread by vulnerability type is the actionable part: SQL injection passed 83% of the time and insecure cryptographic algorithms 87%, but cross-site scripting passed only 15% and log injection only 12%. By language, Python was best (~63%) and Java worst (~30%).

IOActive’s 2026 whitepaper, “The Security Gap in AI-Generated Code,” came at it differently, 27 models, 730 real-world prompts, 27 languages, 219 vulnerability categories, 72 automated detectors, ~20,000 samples, and reached the same conclusion from another angle. Average security performance was 59%, 31.6% of samples were fully exploitable (an actual working vulnerability, not a theoretical one), and no model achieved 100% secure output, even the best configuration produced 90 vulnerabilities across the test set. The standout finding: infrastructure and DevOps code is the most dangerous category by far. Default AI-generated Dockerfiles failed security controls 97.8% of the time (396 of 405) and Terraform 71.8%. One honest caveat IOActive’s methodology makes clear, those infra prompts deliberately omitted security instructions to measure default behavior, so the accurate reading is “almost no default AI infrastructure generation meets expected security controls,” not “97.8% of all AI Dockerfiles in the wild are exploitable.” Either way, the lesson stands: AI infrastructure code cannot enter your pipeline unscanned just because it’s short and looks familiar. Authentication, rate limiting, and cryptography failed across nearly all models; memory-safe languages (Rust, Go) fared better but still failed on crypto and business logic.

A wider body of 2026 research points the same direction, independent academic studies report vulnerability rates that vary widely with method, and the consistent finding across all of them is that newer, larger, more capable models did not produce more secure code. The capability curve and the security curve have decoupled. IOActive’s own framing is the one to internalize: treat AI output as untrusted input, especially for infrastructure, authentication, and cryptography, and enforce mandatory security review before deployment.

The Common Vulnerabilities in AI-Built Apps

The vulnerabilities cluster into a predictable set, which is good news: predictable means auditable. Here’s what shows up most, grouped by where the risk concentrates.

The injection and input-handling failures are the most frequent and the most dangerous. Cross-site scripting (XSS) is the single worst category in the data (15% pass rate), AI routinely passes model or user output into HTML without sanitization, so the fix is output encoding plus a Content-Security-Policy. SQL injection is relatively better-handled (83%) but still appears whenever the model writes raw queries with string interpolation instead of parameterized queries. Broader injection (command, NoSQL) and improper input validation share the same root cause: validation that exists only in the front-end form and is trivially bypassed with a direct request, the fix is always server-side validation on every field. Insecure deserialization (unsafe YAML loaders, no schema validation on parsed JSON/XML) rounds out this group.

The authentication and access failures are where data actually leaks. Broken authentication failed across nearly all models in IOActive’s testing, typically client-side-only checks that a user can bypass by editing a cookie, and the fix is real server-side auth with short-lived tokens. Closely related is broken authorization / IDOR: the API never confirms the logged-in user actually owns the record, so changing an ID in the URL surfaces another customer’s data. This is manual-review territory; scanners miss it.

The secrets and dependency failures are rampant and rising. AI frequently hardcodes API keys, tokens, and credentials directly into client bundles, config files, and git history, the fix is server-side environment variables, nothing in the client bundle, and immediate rotation of anything exposed. On dependencies, two AI-specific risks matter: package hallucination (the model confidently imports packages that don’t exist, which attackers then register maliciously) and typo-squatted packages, so every AI-suggested dependency must be verified to exist, be maintained, and be the one you intended, with an SCA scanner in the loop.

Then the cryptography and disclosure failures: cryptographic misuse, where models reproduce legacy or weak crypto patterns from their training data rather than current secure defaults (crypto has to be tested specifically, “it runs” is not “it’s correct”), and sensitive information disclosure, where errors leak stack traces, internal paths, and database details, fixed with generic production error messages. Finally, memory-management issues (buffer overflows in non-memory-safe languages) and the newer category of prompt injection, where malicious instructions hidden in repo context or third-party rules files (a poisoned .cursorrules or CLAUDE.md) trick the AI into generating insecure code or leaking secrets, which is why AI-derived code and any third-party rules files should be treated as untrusted and whitelisted.

The pattern across all of them: the model produces something that works and looks right, and is quietly insecure in a way only a scan or a knowledgeable human catches.

The AI Code Security Audit Checklist

A proper audit runs in sequence, cheap automated scans first to catch the known-pattern issues, then manual review for the logic-level problems scanners can’t see. Here’s the 12-point version with the actual tools and pass criteria.

#CheckTool / methodPass criteria
1Secrets scanTruffleHog, Gitleaks, GitGuardian, against full git historyZero exposed secrets; all found secrets rotated, not just deleted
2SASTSemgrep (OWASP Top 10 + security-audit rules)Zero critical findings; scan is a blocking CI gate, not advisory
3Dependency / SCASnyk, npm auditZero critical CVEs; every AI-suggested package verified real and not typo-squatted
4Authorization reviewManual testing; RLS check (e.g. Supabase)No IDOR, can user A reach user B’s data?; row-level security on every table
5CORS & headersConfig reviewNo wildcard CORS in production; CSP, X-Frame-Options, HSTS set
6Input validationCode review + manual testingServer-side validation on every field; no string-interpolated SQL
7DASTOWASP ZAP against stagingZero high/critical findings
8Error handlingManual testing (break things on purpose)No stack traces, internal paths, or DB details leaked
9DeserializationCode reviewSchema validation on all parsed input; no unsafe YAML loaders
10CI/CD gatesConfig review + bypass logsAll security gates active and un-bypassable; secrets scanning enforced, not just available
11Compliance docsPolicy review; AI-SBOM / AIBOMSOC 2 / GDPR evidence ready; AI tools and model versions documented
12Re-test & verifyManual PoC; cross-model reviewEvery finding demonstrated, fixed in severity order, re-tested, and the same mistake searched for elsewhere

Two things make this more than a tool run. First, the authorization and business-logic checks (4, 6, 8) have to be done by a human, the data is unanimous that scanners catch injection and secrets reliably but miss logic-level flaws like IDOR. Second, the re-test step matters: for each suspected issue, actually demonstrate it (call the endpoint as a second user, replay a request without a session), fix it, and re-verify, a finding you can’t reproduce isn’t a finding, and a fix you don’t re-test isn’t a fix.

The Fix Playbook

The fix sequence mirrors the audit and comes down to six moves.

Scan for the replicated vulnerabilities first, SAST, SCA, and DAST together catch SQL injection, XSS, and hardcoded secrets reliably and cheaply, so start there. No single scanner is enough: SAST reads the source for injection and unsafe patterns, SCA checks dependencies for vulnerable and hallucinated packages, and DAST probes the running app, deploy all three. Add human review for the business logic, route anything touching application-specific logic, and especially authentication, authorization, and cryptography, through a senior reviewer who understands the full codebase, because that’s exactly where automated tools go blind and where the IOActive data shows the worst failures. Treat AI output as untrusted by default, review it to the same standard as a brand-new contributor’s first pull request, and make SAST a mandatory gate before AI-derived code enters the main branch. Verify every dependency the AI suggests exists and isn’t typo-squatted before installing it. Test cryptography specifically, don’t assume the model got encryption or hashing right just because the code runs. And monitor in production, some vulnerabilities only surface under real traffic, well past the merge point, so keep scanning and keep immutable backups.

Underneath all six is one principle worth repeating because it’s the whole game: the failure isn’t the AI writing bad code occasionally, it’s teams trusting AI code more than they’d trust a human junior’s. Reverse that default and most of the risk is manageable.

If the audit shows structural problems rather than isolated bugs, our AI build rescue service covers the repair, and our restructure AI code service handles the cleanup.

When to Audit, and What It Costs

On cadence: run the full checklist monthly for any active codebase, weekly during periods of heavy AI-assisted development (building a new feature, prepping a launch), and always immediately before a compliance audit or penetration test, before a launch, and before shipping or operating a B2B multi-tenant SaaS, the multi-tenant case is highest-risk because a single authorization miss exposes every tenant. If you are moving an AI-built prototype to production, see our AI prototype to production service.

On cost, treat these as vendor-reported planning ranges that vary with codebase size and scope. A pure automated scan is free to a few hundred dollars and takes minutes to hours, useful but incomplete, since it misses the logic-level issues. A focused human audit (the tier most teams actually need before launch) commonly runs roughly 2,000–5,000 over 3-5 days and delivers prioritized, demonstrated findings. A broader codebase audit runs ~5,000–10,000 over 1-2 weeks; investor-facing due-diligence and managed enterprise engagements run higher (10,000–25,000+). At the entry end, some providers offer a fixed pre-launch review from a few hundred dollars in a few business days. The useful rule: automated scanning is a baseline you should run continuously and cheaply; a human audit is what you buy before a launch, a raise, or a compliance milestone, and it’s the one that catches the authorization and business-logic flaws that actually sink companies.

Frequently Asked Questions

Is AI-generated code secure?

No, not by default. The two largest 2026 studies agree: Veracode (100+ models) found a 56% average security pass rate, meaning ~44% of code-generation tasks introduced a known vulnerability with no security prompting; IOActive (27 models, ~20,000 samples) found 31.6% of samples fully exploitable and no model reaching 100% secure output. AI writes compilable code almost always and secure code barely half the time. It should be treated like unreviewed code from a new contributor, scanned, reviewed, and fixed before it ships.

What are the most common vulnerabilities in AI-generated code?

The recurring ones: cross-site scripting (the single worst category at a 15% pass rate), log injection (12%), broken authentication and broken authorization/IDOR (which failed across nearly all models), SQL injection (better at 83% but still present with raw queries), improper input validation, insecure deserialization, hardcoded secrets, cryptographic misuse (weak/legacy patterns), insecure or hallucinated dependencies, sensitive-information disclosure via leaked errors, memory-management bugs, and prompt injection via poisoned repo context. The common thread is code that works and looks right while being quietly insecure.

Why is AI-generated infrastructure code especially risky?

Because it’s the worst-performing category by a wide margin. IOActive found default AI-generated Dockerfiles failed security controls 97.8% of the time and Terraform 71.8%. The precise reading matters: those prompts deliberately omitted security instructions to measure default behavior, so it means “almost no default AI infrastructure generation meets expected security controls,” not “97.8% of all AI Dockerfiles are exploitable in the wild.” The practical takeaway is the same, never let AI-generated Dockerfiles, Terraform, or CI/CD config into your pipeline without scanning it with tools like Trivy, Checkov, or Snyk first.

Does using a better or coding-specialized model fix the problem?

It helps at the margin but isn’t a solution. The best model in Veracode’s data (GPT-5.5) reached 68%, and reasoning models averaged 56% against 51% for non-reasoning ones, better than the overall 56% average only at the margin, but still failing roughly a third or more of security tasks. And coding-specialized models (51% pass) were actually no safer than general-purpose ones (52%). Model choice is a real security decision, but “we use the best model” is not a defensible security strategy when even the leaders fail a meaningful share of the time. You still need scanning and review. For choosing tools more broadly, see our guide to choosing the right AI stack for your website.

How do I audit AI-generated code for security?

Run a sequenced audit: secrets scan (TruffleHog across full git history, rotate anything found), SAST (Semgrep with OWASP rules, as a blocking CI gate), dependency/SCA scan (Snyk/npm audit, verify AI-suggested packages are real), manual authorization review (test for IDOR, confirm row-level security on every table), CORS and security headers, server-side input validation, DAST (OWASP ZAP on staging), error-handling review, deserialization check, CI/CD gate verification, compliance documentation, and a final re-test where you demonstrate each finding, fix in severity order, and re-verify. The automated scans catch known patterns; the manual steps catch the authorization and logic flaws scanners miss.

How do I fix the issues an audit finds?

Six moves: scan with SAST, SCA, and DAST together to catch the replicated vulnerabilities first; route business logic, auth, and crypto through a senior human reviewer (where scanners are blind); treat all AI output as untrusted and gate it behind SAST before merge, reviewing it like a new contributor’s first PR; verify every AI-suggested dependency exists and isn’t typo-squatted; test cryptography specifically rather than assuming “it runs” means “it’s correct”; and keep monitoring in production, since some issues only appear under real traffic. Fix in severity order, and after each fix, search for the same mistake elsewhere.

What is prompt injection in the context of AI coding?

It’s when malicious instructions are hidden in content the AI reads as context, a poisoned repository file, or a third-party rules file like .cursorrules or CLAUDE.md, tricking the coding assistant into generating insecure code or leaking credentials. It works by blurring the line between your instructions and untrusted external data. The defense is to treat AI-derived code as untrusted input, scrutinize and whitelist any third-party rules files before using them, and keep a human reviewing what the assistant produces rather than trusting it blind.

When and how often should I audit?

Run the full checklist monthly for active codebases, weekly during heavy AI-assisted development or launch prep, and always before a compliance audit or penetration test, before a launch, and before shipping or operating a B2B multi-tenant SaaS (the highest-risk case, since one authorization miss can expose every tenant). Cheap automated scanning should run continuously in CI; a deeper human audit is what you commission before a launch, a fundraise, or a compliance milestone, because that’s the one that catches the logic and authorization flaws automated tools can’t.

Conclusion

Is AI-generated code secure? The data from the two largest 2026 studies is clear and consistent: no, not by default. A 56% security pass rate and a 31.6% fully-exploitable rate aren’t edge cases, they’re the baseline, and they haven’t improved even as the models themselves got dramatically more capable. The capability curve and the security curve have come apart, which means the safety has to come from your process, not from the model.

The fix isn’t to stop using AI, it’s to stop trusting its output more than you’d trust a new hire’s. Treat AI-generated code as untrusted input: scan it with SAST, SCA, and DAST; put a knowledgeable human on the authorization, business-logic, and cryptography it can’t be trusted to get right; gate it before merge; and audit before every launch and compliance milestone. Do that, and AI coding is a genuine accelerator. Skip it, and you’re shipping code that, in Veracode’s tests, carried a known vulnerability in roughly 44% of generated tasks, straight to production.

Shipping AI-assisted code and want to know what you’re exposed to?

Explore our AI Code Security Audit service to see how we scan, manually review, and fix the vulnerabilities in AI-generated code before launch, with demonstrated findings and a prioritized remediation plan.

Book a consultation and send us the repo, we’ll scope the audit and show you exactly where you’re exposed.

author
Nirav Panchal
Lead – Custom Development

Lead of the Custom Development team at KrishaWeb, holds AWS certification and excels as a Team Leader. Renowned for his expertise in Laravel and React development. With expertise in cloud solutions, he leads with innovation and technical excellence.

author

Recent Articles

Browse some of our latest articles...

Prev
Next
subscribe