Security risks of AI-generated code and AI coding tools: insecure patterns from training data, hallucinated packages and slopsquatting, licence exposure, secrets and personal data in prompts, poisoned instruction files, and the .NET controls for each.
AI-generated code carries the usual risks plus some new ones:
true, MD5, or a missing [Authorize].Control it with the gates you already need (SAST, secret scanning, dependency review, human approval) plus package source mapping, lock files and allow-lists, content exclusions and a data policy. The trade-off: a little friction on new dependencies in exchange for closing the cheapest attack path.
"I group the risks into four. First, insecure code: a model reproduces what's common in its training data, and a lot of public code is insecure. In .NET I see
FromSqlRawwith string interpolation,ServerCertificateCustomValidationCallbackreturningtrue'to fix a dev error',MD5for passwords,[AllowAnonymous]copied onto the wrong controller, and permissive CORS. It compiles, the tests pass, and it's a vulnerability.Second, the supply chain. Models invent package names that sound right, like
Microsoft.Extensions.Caching.Redis.Resilience. Attackers watch for those and publish them with malicious install scripts or code, which is called slopsquatting. A 2025 academic study found roughly one in five packages suggested by code models didn't exist, and the same fake names repeated, which is what makes it exploitable. So in our repos new packages need a human decision: NuGet package source mapping so packages only come from approved feeds,packages.lock.jsonwith locked-mode restore in CI, NuGetAudit and dependency review on every PR. Third, data: anything in a prompt leaves the developer's machine, so no secrets, no customer data, no personal information covered by the Privacy Act; we use a business plan, content exclusions for sensitive paths, and secrets live in Key Vault, not in files the assistant reads. Fourth, licences: we block suggestions matching public code, or use code referencing to see the source.The mistake I see is treating AI code as pre-reviewed. It needs more scrutiny, not less, and agent mode adds a newer risk: it reads repo content as instructions, so a poisoned instruction file or README can make it add a dependency or run a command. Same gates as human code, plus a few aimed at the new failure modes."
| Risk | Example in .NET | Control |
|---|---|---|
| Insecure pattern | FromSqlRaw($"... {input}"), cert validation disabled, MD5 |
CodeQL / SAST, Roslyn security analysers, review checklist |
| Hallucinated package | Plausible but non-existent NuGet ID | Package source mapping, allow-list, lock files, dependency review |
| Vulnerable dependency | Old version with a known CVE suggested | NuGetAudit, Dependabot, dotnet list package --vulnerable |
| Licence | Copy of GPL code in a proprietary repo | Public-code filter or code referencing, licence scanning |
| Secrets in prompts | Connection string pasted to "fix" an error | Data policy, Key Vault and managed identity, secret scanning with push protection |
| Personal data in prompts | Production log with names and emails | Redaction, synthetic data, content exclusions, approved plans |
| Poisoned context | Instruction file with hidden directives | Review instruction files as code, CODEOWNERS, agent command approval |
| OWASP Top 10 for LLM Applications 2025 | Relevance to coding assistants |
|---|---|
| LLM01 Prompt injection | Agent steered by repo or web content |
| LLM02 Sensitive information disclosure | Secrets and personal data in prompts |
| LLM03 Supply chain | Hallucinated or malicious packages, poisoned extensions and MCP servers |
| LLM05 Improper output handling | Generated code merged without validation |
| LLM06 Excessive agency | Agent allowed to run commands or push without approval |
In [our solution of ~60 projects], enabling package source mapping and a locked-mode restore blocked [2] AI-suggested packages in the first [month], one of which did not exist on nuget.org at the time it was suggested. CodeQL on PRs flagged [4] SQL injection findings in [a quarter], [3] of them in AI-assisted changes.
Checks that the candidate knows the AI-specific security risks in generated code and tooling, and the concrete .NET controls for each.
Green flags
Red flags
A model predicts what is likely, and likely means common. Public code is full of tutorials that disable certificate checks, concatenate SQL and store passwords badly. Without explicit constraints and review, those patterns come back. The model also doesn't know your threat model: it can't tell that a controller handles another tenant's data.
developer asks for code ──► model suggests 'dotnet add package Contoso.Json.Fast'
│
package doesn't exist ──► attacker registers the name with a payload
│
next developer (or agent) restores it ──► payload runs in build or at run time
The 2025 study by Spracklen and colleagues tested hundreds of thousands of code samples and found about 20% of recommended packages did not exist, with open-source models much worse than commercial ones, and many fake names repeated across runs. Repeatable names are what make squatting worthwhile. NuGet has fewer install-time hooks than npm, but a malicious package can still run code through MSBuild targets or simply at run time.
nuget.config): each package ID pattern can only come from a named source, so a squatted name on a public feed can't sneak in for an internal prefix, and you can restrict public packages to an approved list.Directory.Packages.props): one place to review versions.RestorePackagesWithLockFile, then dotnet restore --locked-mode in CI): the build fails if the dependency graph changes unexpectedly.Prompts, selected code, open tabs and sometimes terminal output are sent to the model provider. Business and enterprise plans give contractual terms (for example, no training on your prompts) and controls such as content exclusions, but the safest data is the data never sent. Personal information in a prompt is a disclosure to a third party under the Australian Privacy Principles unless your policy and contract cover it.
Agent mode reads files as context and can run commands. Researchers showed in 2025 that hidden Unicode characters in rules or instruction files can carry directives a human reviewer doesn't see, making the agent add a backdoor or an unexpected dependency. Defences: review instruction files like code (CODEOWNERS), keep command execution on manual approval, limit which MCP servers are allowed, and run cloud agents with least-privilege tokens.
Models can reproduce chunks of public code. GitHub offers a filter that blocks suggestions matching public code and a code-referencing option that shows the likely source and licence. Decide the policy with legal, and keep licence scanning in CI either way.
packageSourceMapping to a nuget.config and try restoring a package from an unmapped source.RestorePackagesWithLockFile, add a package locally, and watch dotnet restore --locked-mode fail.FromSqlRaw with interpolation.Supply-chain controls for AI-suggested dependencies, and an insecure snippet assistants commonly produce next to its fix.
<!-- nuget.config: packages only from approved sources; internal prefix pinned to the internal feed -->
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
<add key="internal" value="https://pkgs.dev.azure.com/contoso/_packaging/internal/nuget/v3/index.json" />
</packageSources>
<packageSourceMapping>
<packageSource key="internal"><package pattern="Contoso.*" /></packageSource>
<packageSource key="nuget.org"><package pattern="*" /></packageSource>
</packageSourceMapping>
</configuration>
<!-- Directory.Build.props: lock the graph and treat known vulnerabilities as errors -->
<Project>
<PropertyGroup>
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
<WarningsAsErrors>$(WarningsAsErrors);NU1903;NU1904</WarningsAsErrors>
</PropertyGroup>
</Project>
namespace Orders.Infrastructure;
public sealed class OrderSearch(OrdersDbContext db)
{
// Typical AI suggestion: SQL injection through interpolation into FromSqlRaw.
// public Task<List<Order>> ByCustomer(string name) =>
// db.Orders.FromSqlRaw($"SELECT * FROM Orders WHERE CustomerName = '{name}'").ToListAsync();
// Fix: FromSql turns the interpolated value into a DbParameter.
public Task<List<Order>> ByCustomer(string name, CancellationToken ct) =>
db.Orders.FromSql($"SELECT * FROM Orders WHERE CustomerName = {name}").ToListAsync(ct);
}
# CI: fail if the dependency graph changed without an updated lock file
dotnet restore --locked-mode
dotnet add package for whatever the assistant suggests. Why it is wrong: the package may not exist yet, or may be a squatted malicious copy. Instead: check the ID, owner, downloads and repository; keep an allow-list and package source mapping.RestorePackagesWithLockFile and dotnet restore --locked-mode in CI.dotnet dev-certs https --trust).Most of these risks aren't new; AI makes them more frequent and harder to spot because the code looks clean and confident. So the controls are mostly the ones a mature team already has, made non-optional: SAST, secret scanning with push protection, dependency review, lock files, human approval. The genuinely new pieces are hallucinated packages, data in prompts, and agents acting on untrusted context, and those need explicit policy.
Looking ahead, the direction is clear: agents get more autonomy (cloud coding agents opening PRs, MCP tools reaching real systems), so the security boundary moves from "what the developer types" to "what the agent is allowed to do". I'd plan for that now: least-privilege tokens for agents, an approved list of MCP servers, provenance for builds (SLSA-style attestations and SBOMs), and an AI section in the secure development policy that maps to the OWASP Top 10 for LLM Applications and is reviewed every six months as tools change.
| Control | When it fits | Cost | When not to |
|---|---|---|---|
| Package source mapping + allow-list | Any team using AI assistants | Friction for new packages | Never skip on production code |
| Lock files + locked-mode restore | All CI builds | Lock file churn in PRs | Throwaway prototypes |
| Public-code filter | Proprietary code, unclear licence policy | Some suggestions blocked | Open-source projects with compatible licences |
| Content exclusions | Paths with secrets, keys, regulated data | Less helpful suggestions there | As a replacement for keeping secrets out of the repo |
| Manual approval for agent commands | Agent mode in real repos | Slower agent loops | Sandboxed, disposable environments |
Measure with SAST findings by origin, blocked package additions, secret-scanning push blocks and incidents traced to dependencies.
Supply chain security protects everything that goes into your build, not just your own code. The attacks: typosquatting (Newtonsof.Json), dependency confusion (a public package with your internal name), compromised maintainers or packages, and compromised build systems or CI actions. NuGet packages are dangerous because their MSBuild targets and analysers run code during build. My controls: package source mapping so each package id comes only from its intended feed, lock files with --locked-mode, signature validation with trusted signers where it fits, an internal feed with upstreams as a single entry point, and NuGetAudit for known vulnerabilities. For what we ship: an SBOM for every build and signed provenance attestations proving which commit and pipeline produced the artefact, aiming at SLSA build levels. Trade-off: every control adds friction to adding a dependency, which is partly the point.
A secret is anything that grants access or proves identity: database passwords, API keys and tokens, client secrets, JWT signing keys, SAS tokens. The best secret is no secret at all: in Azure I use managed identity so the app authenticates to Azure SQL, Storage and Service Bus with Entra tokens, not stored credentials. What must remain a secret, typically a third-party API key that doesn't support Entra, goes in Azure Key Vault, read through the AddAzureKeyVault configuration provider using the app's managed identity, with Key Vault RBAC per app and a vault per environment. Locally, developers use dotnet user-secrets or their own Entra sign-in against a dev vault. Nothing goes in appsettings.json or the repo, and secret scanning blocks pushes. The trade-off: Entra and Key Vault become runtime dependencies with network hops and throttling limits, so you load at start-up, cache and reload on an interval, and automate rotation rather than doing it by hand.
AI is a strong first pass, never the final check.
The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.
How to tell it (STAR)
**S:** At [company], agent mode added a NuGet package that didn't exist; [two weeks] later someone published it with a build-time payload. **T:** I had to contain it and stop it happening again. **A:** I inspected the package, found an MSBuild target calling out during build, traced every machine that restored it, cleared caches, rotated reachable credentials and reported it. Then I added package source mapping, a CI allow-list check and locked-mode restore, and ran a short session on slopsquatting. **R:** Exposure was limited to [2 developer machines and 1 build agent] with [no evidence of data access], and the allow-list has since blocked [3] unvetted packages.
Last updated 23 Nov 2026.