Covers the layers of automated security analysis for .NET (CA security rules, CodeQL taint analysis, Sonar vulnerabilities and hotspots, secret scanning, NuGetAudit and Dependabot), what each catches and misses, severity policy in CI, and a disciplined false-positive triage process.
I run layers, because each tool sees a different kind of flaw:
CA2100/CA3001–CA3012 (injection), insecure deserialisers, weak crypto (CA5350/CA5351), disabled certificate validation (CA5359).Policy: block critical/high on the PR, track the rest with an SLA. For false positives, I prove the data flow is safe, then suppress at the narrowest scope with a written reason, and review suppressions regularly. The trade-off: more tools catch more, but noise trains people to click 'dismiss', and none of them find a missing authorisation check.
"I think about security analysis as layers, because each tool sees a different class of problem. Inside the build I have the Roslyn security rules from the .NET SDK, raised to errors in
.editorconfig: SQL built from strings, the CA3001 to CA3012 injection rules, insecure deserialisers likeBinaryFormatterandJavaScriptSerializerwith a type resolver, weak hashes like MD5 and SHA-1,ServerCertificateCustomValidationCallbackreturning true. Those are fast and run on every developer's machine. In CI I add a taint analyser, usually CodeQL in GitHub code scanning or SonarQube's security rules, because injection usually crosses three or four methods: the controller takes a string, a service passes it on, a repository concatenates it. Pattern rules miss that; data-flow analysis follows it from source to sink. Then two things that aren't really code analysis but belong in the same pipeline: secret scanning with push protection, and dependency scanning, which in .NET is NuGetAudit during restore, now auditing transitive packages by default in .NET 10, plus Dependabot to raise upgrade PRs.For example, on [a payments API] CodeQL flagged a path traversal where an invoice id from the query string built a blob path. Two of its other findings that week were false positives, because the input was a
Guidroute constraint. The way I handle that is a rule: nobody dismisses a finding without writing why, the suppression goes at the narrowest scope, and a tech lead reviews new suppressions in the PR. We block critical and high findings on the PR and give moderate ones a [30-day] SLA, which also gives us evidence for the Essential Eight 'patch applications' control.The mistake I see is believing a green scan means the app is secure. None of these tools will tell you that a user can read another customer's invoice because the handler forgot to check ownership. Scanners find known patterns; threat modelling and review find logic flaws."
| Layer | Finds | Misses | Runs |
|---|---|---|---|
| CA security rules (SDK) | Known dangerous APIs, simple injection in one method, weak crypto, insecure deserialisation | Flows across many methods, business logic | IDE, every build |
CodeQL (security-extended) |
Taint from sources to sinks across methods: SQLi, path traversal, SSRF, XSS, log injection | Authorisation logic, config in Azure | CI on PR and schedule |
| SonarQube security rules + hotspots | Vulnerabilities (taint in commercial editions) and hotspots needing human review | Same as above | CI |
| Secret scanning + push protection | API keys, connection strings, tokens in commits | Secrets in pipeline logs or config stores | On push |
| NuGetAudit / Dependabot | Packages with known advisories (GitHub Advisory Database) | Zero-days, malicious packages without an advisory | Restore, scheduled PRs |
| Step | What I do |
|---|---|
| 1. Reproduce the path | Read the reported source → sink flow; is the input really attacker-controlled? |
| 2. Decide | Real: fix. Not exploitable: suppress. Unsure: treat as real |
| 3. Suppress narrowly | [SuppressMessage(..., Justification = "...")] on the member; CodeQL dismissal with reason; NuGetAuditSuppress for one advisory URL |
| 4. Record | Reason in the code or alert; reviewed in the PR |
| 5. Revisit | Periodic review of suppressions; remove when code changes |
After adding CodeQL and NuGetAudit to [12] .NET repositories, the first scan produced [140] alerts; triage took two days, [31] were real (mostly log injection and two path traversals), and new critical/high alerts afterwards averaged [under one a month], each fixed before merge.
Checks that the candidate understands what different security analysers can and cannot find, can set a sensible CI policy, and has a disciplined approach to false positives.
Green flags
Red flags
A pattern rule looks at one call site: "is SqlCommand.CommandText set from a non-constant string?" Taint analysis builds a data-flow graph:
SOURCE PROPAGATION SINK
[FromQuery] string name ──► service.Find(name) ──► repo.Query($"... '{name}'") ──► SqlCommand.ExecuteReader
│
SANITISER? (parameterisation, Guid.Parse, allow-list)
If data reaches a sink without passing a recognised sanitiser, the tool raises an alert. CodeQL models ASP.NET Core sources (model binding, HttpRequest), and sinks such as ADO.NET, File.*, Process.Start, HttpClient URLs and response writes. The CA3001–CA3012 rules in the .NET SDK also do data-flow, but are disabled by default and limited in scope, so you enable them explicitly.
| Rule | Catches |
|---|---|
| CA2100 | SQL command text built from non-literal input |
| CA3001–CA3012 | Taint: SQL, XSS, file path, process command, XPath, regex, LDAP injection |
| CA2300–CA2330 | BinaryFormatter, LosFormatter, insecure JavaScriptSerializer, Json.NET TypeNameHandling |
| CA3075 / CA3077 | Insecure XML DTD processing (XXE) |
| CA5350 / CA5351 | Weak (SHA-1, 3DES) and broken (MD5, DES) crypto |
| CA5359 | Certificate validation disabled |
| CA5394 | System.Random used for security |
Enable the category in one line: dotnet_analyzer_diagnostic.category-Security.severity = error.
Once a secret is pushed it lives in history and forks; deleting the file doesn't remove it. Push protection blocks the push instead. If one leaks: rotate first, then clean history if needed. Under the Privacy Act's Notifiable Data Breaches scheme, a leaked credential that exposed personal information may itself be a notifiable incident, so treat it as an incident.
NuGetAudit checks restored packages against the GitHub Advisory Database and emits NU1901–NU1904 (low to critical). Settings: NuGetAudit, NuGetAuditLevel, NuGetAuditMode (direct or all; all is the default for .NET 10 projects). To accept one advisory, add <NuGetAuditSuppress Include="https://github.com/advisories/GHSA-..." /> rather than lowering the level. Make NU1903;NU1904 errors in CI with WarningsAsErrors.
Automated tools find known patterns. Broken object-level authorisation (another customer's invoice), missing rate limits, misconfigured Azure networking and business-logic abuse need threat modelling, review and testing (DAST, pen tests).
category-Security and see CA2100/CA3001 fire.security-extended suite and read the data-flow path it reports.dotnet restore and read the NU190x warning; then suppress that one advisory and confirm others still fail.Before/after: an invoice download endpoint that CodeQL and the CA rules flag, and the fix.
// Before: path traversal (CodeQL cs/path-injection) and SQL injection (CA2100 / CA3001).
namespace Billing.Api;
public static class InvoiceEndpoints
{
public static void MapInvoices(this WebApplication app)
{
app.MapGet("/invoices/{file}", (string file) =>
Results.File(Path.Combine("/data/invoices", file))); // "../../appsettings.json"
app.MapGet("/invoices/search", async (string customer, SqlConnection db) =>
{
var cmd = new SqlCommand($"SELECT * FROM Invoices WHERE Customer = '{customer}'", db);
return Results.Ok(await cmd.ExecuteScalarAsync());
});
}
}
// After: input constrained to a Guid, ownership checked, SQL parameterised.
using Microsoft.Data.SqlClient;
namespace Billing.Api;
public static class InvoiceEndpoints
{
public static void MapInvoices(this WebApplication app)
{
app.MapGet("/invoices/{id:guid}", async (Guid id, IInvoiceStore store, HttpContext http, CancellationToken ct) =>
{
var invoice = await store.FindForCustomerAsync(id, http.User.CustomerId(), ct); // no tool checks this for you
return invoice is null ? Results.NotFound() : Results.File(invoice.BlobPath, "application/pdf");
}).RequireAuthorization();
app.MapGet("/invoices/search", async (string customer, SqlConnection db, CancellationToken ct) =>
{
await using var cmd = new SqlCommand("SELECT COUNT(*) FROM Invoices WHERE Customer = @customer", db);
cmd.Parameters.Add(new SqlParameter("@customer", System.Data.SqlDbType.NVarChar, 100) { Value = customer });
return Results.Ok(await cmd.ExecuteScalarAsync(ct));
}).RequireAuthorization();
}
}
<!-- Directory.Build.props: security rules and dependency audit as build policy -->
<Project>
<PropertyGroup>
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode> <!-- explicit, also covers older TFMs -->
<NuGetAuditLevel>moderate</NuGetAuditLevel>
<WarningsAsErrors>$(WarningsAsErrors);NU1903;NU1904</WarningsAsErrors> <!-- high, critical block -->
</PropertyGroup>
<ItemGroup>
<!-- Accepted: not reachable, see ADR-0042; revisit 2027-02-01 -->
<NuGetAuditSuppress Include="https://github.com/advisories/GHSA-xxxx-xxxx-xxxx" />
</ItemGroup>
</Project>
# .editorconfig
[*.cs]
dotnet_analyzer_diagnostic.category-Security.severity = error
CA security rules plus CodeQL or Sonar, which are actively maintained.NuGetAuditLevel to silence one advisory. Why it is wrong: every future advisory at that level is hidden too. Instead: NuGetAuditSuppress the specific advisory URL with a review date.dotnet user-secrets and Key Vault references, add a pre-commit hook (gitleaks) and turn on push protection.The hard part isn't installing scanners, it's keeping trust in the alerts. If the first week brings 300 findings and half are noise, the team learns to dismiss. I run the first scan in report-only mode, triage everything once with the team so we agree what 'real' means, then switch on blocking for critical and high. Every suppression carries a reason and an owner. I measure mean time to fix for high findings and the number of open suppressions, not the raw alert count.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
SDK CA security rules as errors |
Always; cheapest layer | Some legacy noise | Never skip |
| GitHub CodeQL | Repos on GitHub; best free taint analysis for public repos, part of GitHub Advanced Security for private ones | Licence for private repos, 5–15 min per run | Code not on GitHub |
| SonarQube security | Already using Sonar for quality gates | Taint analysis needs commercial edition | When you only want security and already have CodeQL |
| Secret scanning + push protection | Every repository | Low | Never skip |
| NuGetAudit + Dependabot | Every repository | Upgrade PR churn | Never skip; tune grouping instead |
I use NuGetAudit, which runs during dotnet restore and reports known vulnerabilities as NU1901-NU1904 (low to critical). With the .NET 10 SDK, net10.0 projects audit transitive packages by default (NuGetAuditMode=all). For policy, I set WarningsAsErrors for NU1903 and NU1904 in CI so high and critical findings fail the build, while low and moderate stay as warnings with tickets. Reviewed false positives get a NuGetAuditSuppress entry with the advisory URL and a recorded expiry. dotnet list package --vulnerable --include-transitive --format json feeds reports. Dependabot opens grouped upgrade PRs and security updates. If restore uses only a private feed, I add <auditSources> pointing at nuget.org. And I scan container images separately. Trade-off: strict gates on transitive findings can block a release for an unreachable code path, so exceptions must be quick, visible and time-boxed.
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.
First check whether a fixed version of the transitive package itself exists and is compatible: if so, pin it with Central Package Management transitive pinning (or a direct reference) and run the tests. If not, assess reachability and exposure: do we call the vulnerable API or code path, with untrusted input, in an internet-facing service? Then apply package-level mitigations: avoid the vulnerable API, wrap it with validation, disable the feature that uses it, or swap to an alternative library. Tell stakeholders (product owner, security lead) the risk, the mitigation and the plan in plain terms. Suppress only that advisory with NuGetAuditSuppress, a short expiry and security-lead approval, and track the upstream issue. If it's reachable, unmitigable and no fix is coming, replace the package. Longer term, a scheduled review of transitive dependencies and fewer heavyweight dependencies reduce how often this happens.
How to tell it (STAR)
**S:** At [company] we had [12] .NET repos with customer data and only default analysers, with a pen test in [six weeks]. **T:** I was asked to add security scanning without stalling delivery. **A:** I enabled CodeQL and NuGetAudit in report-only mode, ran a triage with each team, fixed a path traversal in invoice downloads and two SQL concatenations, dismissed false positives with written reasons, then made critical and high findings block PRs. **R:** Open high alerts went from [40] to [0] in [three weeks], and the pen test found [no] injection issues.
Last updated 23 Nov 2026.