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

📚 Interview question

Which security analysers would you run on a .NET 10 codebase in CI, and what does each kind find? Compare Roslyn security rules, CodeQL and SonarQube security analysis, secret scanning and dependency scanning, and explain how you triage false positives without letting real findings slip through.

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.

Mid-Level Theory Intermediate code-quality codeql dependency-scanning secret-scanning security-analysers static-analysis

🎯 Key points

  • Layers: Roslyn CA security rules in the build, CodeQL / Sonar taint analysis in CI, secret scanning on push, NuGetAudit + Dependabot for packages; all part of a secure SDLC with threat modelling and review
  • SDK security rules (category-Security; full list in the .NET code analysis docs): CA2100 and CA3001-CA3012 injection, CA2300-series insecure deserialisers, CA5350/CA5351 weak crypto, CA5359 disabled certificate validation, CA5394 insecure randomness
  • CodeQL tracks tainted data from sources (request input) to sinks (SQL, file paths, process start) across methods; security-extended suite in GitHub code scanning
  • Secrets workflow: user-secrets / Key Vault so nothing sensitive is in config files, optional gitleaks pre-commit hook, push protection on the server; a leaked secret is rotated, not just deleted
  • NuGetAudit runs at restore (in .NET 10 it audits transitive packages by default); Dependabot raises upgrade PRs
  • Severity policy: block critical/high on the PR, track moderate/low with an SLA; aligns with Essential Eight 'patch applications'
  • False positives: verify the data flow, then suppress at the narrowest scope with a written reason (SuppressMessage Justification, CodeQL dismissal reason, NuGetAuditSuppress for one advisory) and review suppressions
  • Feedback loop: pen-test and incident findings become new rules or CodeQL queries; scanners don't find authorisation logic flaws

⏱ 30-second answer

I run layers, because each tool sees a different kind of flaw:

  • Roslyn security rules in every build: CA2100/CA3001–CA3012 (injection), insecure deserialisers, weak crypto (CA5350/CA5351), disabled certificate validation (CA5359).
  • Taint analysis in CI: CodeQL or SonarQube follow user input from a controller to a SQL command or file path across methods.
  • Secret scanning with push protection, so keys never reach git history.
  • Dependency scanning: NuGetAudit at restore (transitive by default in .NET 10) plus Dependabot PRs.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 like BinaryFormatter and JavaScriptSerializer with a type resolver, weak hashes like MD5 and SHA-1, ServerCertificateCustomValidationCallback returning 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 Guid route 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."


What each layer finds

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

False-positive triage

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

Production example

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.

🔍 What the interviewer is checking

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

  • Distinguishes pattern rules from taint/data-flow analysis
  • Names concrete rules and tools (CA2100, CodeQL, NuGetAudit, push protection)
  • Severity-based blocking policy with an SLA for the rest
  • Narrow, justified, reviewed suppressions; rotate leaked secrets
  • Says scanners don't find authorisation flaws

Red flags

  • 'We run SonarQube so we're secure'
  • Disables noisy rules globally
  • Thinks deleting a committed secret is enough

📚 Learn in depth

1. Pattern rules versus taint analysis

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.

2. Useful .NET SDK security rules

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.

3. Secrets

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.

4. Dependencies

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.

5. The limits

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).

Try it yourself

  1. Write a minimal API endpoint that concatenates a query value into SQL; enable category-Security and see CA2100/CA3001 fire.
  2. Enable GitHub CodeQL default setup on a sample repo with the security-extended suite and read the data-flow path it reports.
  3. Reference an old vulnerable package version, run dotnet restore and read the NU190x warning; then suppress that one advisory and confirm others still fail.
  4. Commit a fake key in a test repo with push protection on and observe the block.
  5. Replace the concatenation with a parameterised query and confirm the alert closes.

💻 Code

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

⚠ Common mistakes

  • Mistake: Relying on one tool. Why it is wrong: pattern rules miss cross-method flows, taint tools miss secrets and packages. Instead: layer build rules, CI taint analysis, secret and dependency scanning.
  • Mistake: Still installing SecurityCodeScan (the Roslyn security pack many teams used around 2018–2021). Why it is wrong: it has had no meaningful releases for years, so its rules lag current APIs. Instead: use the SDK CA security rules plus CodeQL or Sonar, which are actively maintained.
  • Mistake: Dismissing alerts without a reason. Why it is wrong: nobody can tell a checked false positive from a lazy click. Instead: require a written justification and review suppressions.
  • Mistake: Lowering 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.
  • Mistake: Relying on server-side secret scanning alone. Why it is wrong: the secret is already on the developer's disk and maybe in a fork or CI log. Instead: keep secrets out of files with dotnet user-secrets and Key Vault references, add a pre-commit hook (gitleaks) and turn on push protection.
  • Mistake: Deleting a committed secret and moving on. Why it is wrong: it remains in history and clones. Instead: rotate immediately, then clean history and treat it as an incident.
  • Mistake: Blocking PRs on every low-severity finding. Why it is wrong: developers start bypassing the pipeline. Instead: block critical/high, track the rest with an SLA.
  • Mistake: Treating a clean scan as a security sign-off. Why it is wrong: authorisation and logic flaws are invisible to scanners. Instead: threat-model new features, review, pen-test, and feed what those find back into rules and queries.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions NuGetAudit or Dependabot Why: Checks they can actually set up dependency scanning and a fail policy
    How to answer

    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.

  2. When: Candidate mentions malicious packages or supply chain Why: Checks awareness of risks beyond known advisories: dependency confusion, provenance, SBOMs
    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.

  3. When: Candidate says they would block critical advisories Why: Checks what they do when no fixed version exists yet
    How to answer

    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.

🛠 Real-world problems: how you handle them

CodeQL rollout: 140 alerts, 31 real, and a path traversal in invoice downloads
Situation
A [payments and invoicing] platform with [12] .NET repositories on GitHub holding customer personal information. Only SDK analysers at default levels; an external pen test was due in [six weeks].
Signals
First CodeQL and NuGetAudit run: [140] alerts across repos, several 'critical' path-injection and SQL alerts, [9] packages with high advisories (mostly transitive), developers asking if they could just turn it off.
Investigation
Triage session with two developers per repo: followed each CodeQL data-flow path in the alert view; checked route constraints and model binding; reproduced the invoice path traversal locally with `../`; `dotnet list package --vulnerable --include-transitive` to find which parents pulled the vulnerable packages.
Resolution
Immediately: fixed the path traversal (Guid ids, blob lookup by ownership) and the [2] SQL concatenations; upgraded parent packages or pinned transitive versions. Then: dismissed false positives with reasons, set CodeQL and NU1903/NU1904 to block PRs, moderate findings on a [30-day] SLA.
Prevention
`category-Security` raised to error in `.editorconfig`; push protection on all repos; monthly suppression review; ADR describing the severity policy; pen test findings fed back as custom CodeQL queries where possible.

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.

More in Static Analysis

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me