📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are the security risks of AI-generated code, such as insecure patterns, hallucinated packages, licence issues and secrets leaking into prompts, and how do you control them in a .NET team?

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.

Mid-Level Security Intermediate ai github-copilot secrets-management security slopsquatting supply-chain-security

🎯 Key points

  • Models reproduce common insecure patterns: string-built SQL, disabled certificate validation, weak crypto, missing [Authorize]
  • Hallucinated package names get registered by attackers (slopsquatting); one 2025 study found about 20% of suggested packages didn't exist
  • NuGet controls: package source mapping, packages.lock.json with locked-mode restore, allow-lists, NuGetAudit
  • Licence risk: suggestions matching public code; enable the public-code filter or code referencing
  • Prompts leave the machine: no secrets or personal information (Privacy Act 1988); content exclusions; business plans
  • Agent mode can be steered by poisoned repo content (instruction files, hidden Unicode, READMEs) and can run commands
  • Same gates as human code: SAST (CodeQL), secret scanning with push protection, dependency review, human approval
  • Maps to OWASP Top 10 for LLM Applications 2025: LLM03 supply chain, LLM02 sensitive information disclosure

⏱ 30-second answer

AI-generated code carries the usual risks plus some new ones:

  • Insecure patterns: models reproduce what's common, such as string-built SQL, a certificate callback that returns true, MD5, or a missing [Authorize].
  • Hallucinated packages: the model names a NuGet or npm package that doesn't exist, and attackers register those names (slopsquatting).
  • Licence exposure from suggestions matching public code, and data leakage when secrets or personal information go into prompts.
  • Poisoned context: instruction files or docs that steer agent mode into unsafe edits or commands.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 FromSqlRaw with string interpolation, ServerCertificateCustomValidationCallback returning true 'to fix a dev error', MD5 for 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.json with 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 by risk

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 mapping

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows the AI-specific security risks in generated code and tooling, and the concrete .NET controls for each.

Green flags

  • Names insecure patterns with .NET examples
  • Explains hallucinated packages and slopsquatting, and NuGet controls
  • Treats prompts as data leaving the organisation; mentions the Privacy Act
  • Knows agent mode can be steered by repo content
  • Relies on existing gates (SAST, secret scanning, review), made mandatory

Red flags

  • "Copilot is trained on good code, so it's secure"
  • Adds suggested packages without checking
  • Pastes production data into chat
  • No mention of licences or data handling

📚 Learn in depth

1. Why models produce insecure code

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.

2. Hallucinated packages and slopsquatting

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.

3. NuGet controls

  • Package source mapping (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.
  • Central package management (Directory.Packages.props): one place to review versions.
  • Lock files (RestorePackagesWithLockFile, then dotnet restore --locked-mode in CI): the build fails if the dependency graph changes unexpectedly.
  • NuGetAudit: warnings during restore for known vulnerabilities; can be made errors by severity.
  • Dependency review on PRs: shows added packages, licences and advisories.

4. Data leaving the machine

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.

5. Agent mode and poisoned context

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.

6. Licence exposure

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.

Try it yourself

  1. Ask an assistant for "a quick way to call an API with a self-signed cert" and see whether it disables validation.
  2. Add packageSourceMapping to a nuget.config and try restoring a package from an unmapped source.
  3. Turn on RestorePackagesWithLockFile, add a package locally, and watch dotnet restore --locked-mode fail.
  4. Enable CodeQL on a test repo and plant a FromSqlRaw with interpolation.
  5. Ask an assistant for packages that solve a niche problem and check each ID on nuget.org.

💻 Code

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

⚠ Common mistakes

  • Mistake: Treating AI-generated code as already reviewed. Why it is wrong: it reproduces insecure patterns and knows nothing of your threat model, data classification or which endpoints are internet-facing. Instead: apply SAST, analysers and human review, with extra scrutiny on auth, SQL and crypto.
  • Mistake: Running 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.
  • Mistake: No lock files. Why it is wrong: the dependency graph can change silently between builds. Instead: RestorePackagesWithLockFile and dotnet restore --locked-mode in CI.
  • Mistake: Letting faster iterations skip security steps. Why it is wrong: when AI doubles the number of PRs per sprint, manual security checks are the first thing dropped. Instead: make the checks automatic and blocking in the pipeline (CodeQL, secret scanning with push protection, dependency review, NuGetAudit) and keep threat modelling in the definition of ready for risky stories.
  • Mistake: Pasting connection strings or production logs into chat. Why it is wrong: secrets and personal information leave the organisation and may be retained. Instead: redact, use synthetic data, keep secrets in Key Vault with managed identity.
  • Mistake: Accepting "just disable certificate validation" to fix a dev error. Why it is wrong: it ships to production and enables man-in-the-middle attacks. Instead: trust the dev certificate properly (dotnet dev-certs https --trust).
  • Mistake: Ignoring licence exposure. Why it is wrong: copied public code can carry obligations, and several popular projects have moved to source-available or copyleft licences, so "it's on GitHub" doesn't mean it's free to reuse. Instead: enable the public-code filter or code referencing and run licence scanning on dependencies.
  • Mistake: Letting agent mode run commands automatically in any repo. Why it is wrong: poisoned context can trigger harmful commands. Instead: keep manual approval for commands and review instruction files as code.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions package source mapping, typosquatting or lock files Why: Checks broader software supply chain security knowledge
    How to answer

    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.

  2. When: Candidate says secrets must never be in prompts or code Why: Checks how secrets are actually managed in .NET on Azure
    How to answer

    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.

  3. When: Candidate mentions AI code review as a security control Why: Checks whether they understand the limits of AI review
    How to answer

    AI is a strong first pass, never the final check.

    • Code review: tools like Copilot code review catch missing null checks, undisposed resources, inconsistent naming and obvious logic slips in seconds, so humans can focus on design and domain rules. It comments; a human still approves.
    • Tests: great for scaffolding and edge-case lists, risky as proof: generated tests often assert what the code does, not what it should do. Check them by breaking the code or with mutation testing (Stryker.NET).
    • Docs: fast drafts of XML comments, READMEs and ADR skeletons; every statement is checked against the code.

    The trade-off: minutes saved on drafting against the risk of false confidence, so verification is part of the workflow.

🛠 Real-world problems: how you handle them

Agent mode added a non-existent NuGet package that was later squatted
Situation
[A team of 6] on [an internal ASP.NET Core API] used agent mode to add Redis resilience. It added a plausible package ID to `Directory.Packages.props`; the restore failed, so a developer [left it for later]. [Two weeks] later the name existed on nuget.org, published by an unknown account.
Signals
The restore suddenly succeeded on a developer machine; dependency review on the PR showed a new package with [~30] downloads, no repository link and a publish date days old; a new outbound connection from the build agent appeared in [firewall logs].
Investigation
Inspected the package contents with NuGet Package Explorer: an MSBuild `.targets` file making an HTTP call during build. Checked which machines had restored it from the NuGet cache and build logs; reviewed agent chat history to confirm the origin; checked the build agent's identity permissions.
Resolution
Removed the package, cleared NuGet caches, rotated credentials reachable from the affected build agent and developer machines, reported the package to nuget.org. Then added package source mapping, an allow-list check in CI, and locked-mode restore.
Prevention
Allow-list for new packages with a named approver; `dotnet restore --locked-mode` in CI; dependency review required on PRs; repo instructions telling the assistant not to add packages without saying so; a training session on slopsquatting.

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.

↩ Usually asked after

More in AI-Assisted Development

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me