Join our Newsletter — 33% off our NHI Course
Home› Guides› .NET Security Analyser Rules Guide: Using the CA…
Guide Application Security

.NET Security Analyser Rules Guide: Using the CA Security Rules in CI

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 27 November 2026 15 min read
On this page

Most of the .NET security analyser rules that would catch SQL injection, unsafe deserialisation and weak cryptography are switched off by default, so a clean build says little about security. The Roslyn-based code quality analysers ship inside the .NET SDK and run on every build of a .NET 5 or later project, but rules in the Security category such as CA2300, CA3001 and CA5350 are not enabled by default in .NET 10. This guide shows .NET developers and application security teams how to turn the Security category on, choose the right AnalysisLevel and AnalysisMode, enforce findings as errors in CI, and keep suppressions auditable. It covers the in-box CA rules only and assumes you already follow general secure coding practice.

This is an independent guide from NHI Mgmt Group, based on Microsoft's public .NET code analysis documentation as of November 2026. It is not sponsored or reviewed by Microsoft. Product features change, so confirm settings against Microsoft's current documentation.

Key takeaways

  • Turn the Security category on explicitly. Set AnalysisModeSecurity to All (or AnalysisLevelSecurity to latest-all) because most CA security rules are off in the default mode.
  • Pin the rule set version. Use a numbered AnalysisLevel such as 10.0 or 10-recommended so an SDK upgrade does not add new build breaks without warning.
  • Fail the build on security rules only at first. Raise Security rules to error in .editorconfig rather than turning every warning into an error on day one.
  • Make every suppression explain itself. Prefer SuppressMessage with a Justification in source over severity = none, so reviewers can see why a finding was accepted.
  • Know the limits. The taint rules (CA3001 to CA3012) track HTTP request input inside one assembly only, so pair them with a cross-assembly SAST tool and code review.

What the .NET security analysers are

The .NET code quality analysers (rule IDs beginning CA) are Roslyn analysers included with the .NET SDK. For projects targeting .NET 5 or later they are enabled by default; projects targeting .NET Standard or .NET Framework need <EnableNETAnalyzers>true</EnableNETAnalyzers>. Rules are grouped into categories (Design, Performance, Reliability, Security, Usage and others), and each rule's documentation page states its category and whether it is enabled by default for a given .NET release.

The Security category contains more than ninety rules in five broad families:

  • Injection review rules (CA2100, CA3001 to CA3012): CA2100 flags CommandText built from a method argument; CA3001 to CA3012 use data flow analysis to follow HTTP request input to SQL, HTML output, file paths, process start, redirects, XPath, XML, XAML, DLL loading and regular expressions.
  • Deserialisation rules (CA2300 to CA2362, CA5360, CA5362): insecure formatters such as BinaryFormatter, LosFormatter, NetDataContractSerializer, ObjectStateFormatter, unsafe Json.NET TypeNameHandling settings, and DataSet/DataTable in untrusted object graphs.
  • XML parser rules (CA3061, CA3075 to CA3077, CA5366, CA5369 to CA5372, CA5374): DTD processing, external entities and obsolete XSLT types.
  • Cryptography and TLS rules (CA5350 to CA5400 range): weak and broken algorithms, unsafe cipher modes, disabled certificate validation, deprecated or hard-coded TLS versions, weak key derivation, hard-coded keys and insecure randomness.
  • Web framework rules (CA3147, CA5363, CA5365, CA5368, CA5382, CA5383, CA5391, CA5395, CA5396): anti-forgery tokens, request validation, header checking, ViewStateUserKey and cookie flags in ASP.NET and ASP.NET Core.

The analysers run inside the compiler, so findings appear in the IDE, in dotnet build output and in any CI log with no separate scanner. That is their main strength: feedback arrives in the same place as compiler errors, before a pull request is opened.

Key CA security rules

The table lists a selection of rules worth enforcing first, chosen because a finding usually points to an exploitable weakness rather than a style issue. Titles are from Microsoft's Security rules page.

RuleTitleRisk it addressesUsual fix
CA2100Review SQL queries for security vulnerabilitiesSQL injection through a CommandText string built from a method argumentParameterised commands or stored procedures
CA3001Review code for SQL injection vulnerabilitiesHTTP request input reaching SQL command textParameters, never concatenation; allowlist dynamic identifiers
CA3002Review code for XSS vulnerabilitiesUntrusted web input written to raw HTMLFramework encoding; avoid raw output helpers
CA3006Review code for process command injection vulnerabilitiesRequest input reaching process startFixed executable, argument list, allowlisted values
CA3007Review code for open redirect vulnerabilitiesRedirects to attacker-chosen sitesLocal-only redirect checks or allowlist
CA2300, CA2301, CA2302BinaryFormatter rulesRemote code execution and denial of service from untrusted inputReplace with System.Text.Json, XmlSerializer or DataContractSerializer
CA2326, CA2327TypeNameHandling values other than None; insecure JsonSerializerSettingsPolymorphic deserialisation gadgetsTypeNameHandling.None or a strict binder
CA3075Insecure DTD ProcessingXML external entity disclosureProhibit DTDs, null XmlResolver
CA5350Do Not Use Weak Cryptographic AlgorithmsTripleDES, SHA1, RIPEMD160AES; SHA256, SHA384 or SHA512
CA5351Do Not Use Broken Cryptographic AlgorithmsMD5, DES, RC2AES; SHA-2 family
CA5359Do not disable certificate validationA validation callback that always returns true enables interceptionRemove the callback; fix the trust chain
CA5364, CA5397Deprecated security protocols; deprecated SslProtocols valuesTLS versions older than 1.2Let the OS choose; avoid hard-coding (CA5386, CA5398)
CA5379, CA5387Key derivation algorithm strength; iteration countRfc2898DeriveBytes defaulting to SHA1 or under 100,000 iterationsSHA256 or higher, higher iteration count, or a password hasher
CA5389Do not add archive item's path to the target file system pathZip slip path traversal on extractionCanonicalise and check the destination path
CA5390Do not hard-code encryption keyKeys extracted from binariesKey vault or secrets store at runtime
CA5391Use antiforgery tokens in ASP.NET Core MVC controllersCross-site request forgery on POST, PUT, PATCH, DELETEGlobal auto-validate filter
CA5394Do not use insecure randomnessPredictable tokens from System.RandomRandomNumberGenerator

Two points shape how you treat these rules. First, the "Review" rules (CA2100, CA3001 to CA3012) are prompts for a human decision, not proof of a bug, so expect some findings to be closed as safe. Second, deserialisation findings deserve priority even in legacy code: Microsoft's BinaryFormatter security guide states that the type "is insecure and can't be made secure", and from .NET 9 the in-box implementation throws on use. A CA2300 finding in a .NET Framework service is a migration item, not a suppression candidate.

Enabling via AnalysisMode and .editorconfig

Three layers control which rules run and how loudly: the MSBuild properties in the project file (or a shared Directory.Build.props), the .editorconfig severity entries, and in-source suppressions.

MSBuild properties

PropertyValuesEffect
EnableNETAnalyzerstrue, falseTurns on SDK analysers for .NET Standard and .NET Framework projects; already on for .NET 5 and later
AnalysisLevellatest (default for .NET 5+), preview, a version such as 10.0, or a compound such as 10-recommendedChooses which release's rule set runs; a version number locks the set so no new warnings appear
AnalysisModeNone, Default, Minimum, Recommended, AllChooses how many rules are build warnings; All makes all rules warnings (with a short documented list of exceptions)
AnalysisLevelSecurity, AnalysisModeSecuritySame values as aboveApplies the level or mode to the Security category only; falls back to the general property if omitted
CodeAnalysisTreatWarningsAsErrorstrue, falseControls whether CA warnings become errors when warnings are treated as errors

A practical baseline in Directory.Build.props at the repository root, so every project inherits it:

1 Sample only, based on the public documentation cited. Assess it independently against the current official documentation, test outside production and back up first.

Sample 1
<PropertyGroup>
  <AnalysisLevel>10.0</AnalysisLevel>
  <AnalysisModeSecurity>All</AnalysisModeSecurity>
</PropertyGroup>

If you set a compound AnalysisLevel and also AnalysisMode, AnalysisLevel takes precedence. Microsoft's configuration documentation also notes that when AnalysisMode or AnalysisLevel enables all rules, bulk dotnet_analyzer_diagnostic entries are ignored, and recommends the per-category AnalysisMode<Category> property instead. That is why the category property is the reliable switch for security.

.editorconfig severities

Severity entries let you decide which rules break the build. Precedence is rule ID over category over all rules:

Sample 1
[*.{cs,vb}]
# Block the build on the highest-value security rules
dotnet_diagnostic.CA2100.severity = error
dotnet_diagnostic.CA2300.severity = error
dotnet_diagnostic.CA3001.severity = error
dotnet_diagnostic.CA3075.severity = error
dotnet_diagnostic.CA5350.severity = error
dotnet_diagnostic.CA5351.severity = error
dotnet_diagnostic.CA5359.severity = error
dotnet_diagnostic.CA5390.severity = error
# Remaining security rules stay as warnings while you burn down the backlog

Note that dotnet_analyzer_diagnostic.category-Security.severity only affects rules that are already enabled by default, so on its own it does not switch on the disabled security rules. Use it after AnalysisModeSecurity, not instead of it.

Package or SDK analysers

The analysers update with the SDK. Teams that want rule updates on their own schedule can reference the Microsoft.CodeAnalysis.NetAnalyzers NuGet package, which turns off the built-in SDK analysers for .NET 5 and later projects. Do not also set EnableNETAnalyzers when using the package; Microsoft documents that this produces a build warning. Choose one route per repository and record it.

Generated files (for example *.designer.cs or files with an auto-generated header) are usually skipped. Mark further generated paths with generated_code = true in .editorconfig rather than suppressing rules on them one by one.

Enforcing in CI builds

The analysers run during compilation, so CI enforcement means building with the same configuration developers use and treating the chosen rules as failures.

  1. Centralise configuration. Commit Directory.Build.props and a root .editorconfig so local and CI builds match. Reject pull requests that change them without application security review (a CODEOWNERS entry works well).
  2. Measure before enforcing. Enable AnalysisModeSecurity=All with every security rule at warning, run a full build, and export the counts per rule and per project. This is your baseline.
  3. Promote a first set to error. Start with the rules in the table above that have zero or few findings, so the build stays green while new code is protected immediately.
  4. Fix or justify the backlog. Work through remaining findings by rule, highest risk first (deserialisation, injection, certificate validation, hard-coded keys), and promote each rule to error once its count reaches zero.
  5. Decide on warnings as errors. Building with -warnaserror makes all analysis warnings errors. If you want style or performance warnings to stay as warnings while security rules fail, rely on explicit error severities instead, or set CodeAnalysisTreatWarningsAsErrors to false and raise security rules individually.
  6. Publish results. Write compiler diagnostics to a SARIF log through the compiler error log option so findings appear in your code scanning or pull request view alongside other tools. See the SAST Triage Guide for SARIF workflows and baselines.
  7. Pin and plan upgrades. With AnalysisLevel pinned, an SDK upgrade does not introduce new warnings. Schedule a review of the newer rule set each time you move the pin, rather than letting latest change the build under you.

Rollback: if a promoted rule blocks a release on a false positive, lower that one rule to warning in .editorconfig through a reviewed change, record a ticket, and restore it after the fix. Never remove AnalysisModeSecurity to unblock a build.

Small versus large organisations: a single-team repository can move straight to errors for the high-value rules in a sprint. A large estate with many legacy .NET Framework services should roll out by repository ring, pin AnalysisLevel centrally, and track burn-down per service owner. Build agents that compile code run with pipeline credentials, so keep them under the controls in the CI/CD Security Guide.

Triage and suppressions

Each finding should end as fixed, accepted with a recorded reason, or confirmed as a false positive. The documented suppression routes differ in how visible they are:

MethodScopeAudit valueUse when
SuppressMessage attribute with JustificationOne member or typeHigh: reason sits beside the codeDefault for accepted security findings
GlobalSuppressions.cs with Scope and TargetNamed member, type or moduleMedium: central but away from codeGenerated code with no user source
#pragma warning disable / restoreLines between the pragmasLow unless a comment explains itShort, local exceptions in test code
.editorconfig severity = noneFile, folder or whole projectLow: silences every future findingTest projects or tooling folders only
dotnet_code_quality.CAxxxx.excluded_symbol_namesNamed symbols for a rule or categoryMediumA vetted sanitiser or wrapper the taint rules cannot see through
  • Require a justification: make a missing or empty Justification a review failure for any CA2xxx, CA3xxx or CA5xxx suppression.
  • Follow the rule's own guidance: Microsoft's rule pages state when suppression is safe, for example CA5350 only when the data needs no security guarantee and CA3001 only when input is always validated against a known safe set of characters.
  • Review suppressions periodically: search for suppressions of security rules each quarter and re-test them; code around them changes.
  • Do not suppress folders of production code: folder-level none settings hide new findings in code nobody has reviewed.

Complementing with other SAST

The CA rules are fast and close to the developer, but they have documented limits. CA3001 and the related taint rules track input from HTTP requests, cannot track data across assemblies, and have a configurable interprocedural depth limit, so a value read in a web project and executed in a data access library may produce no warning. Rules also do not understand your business logic: broken authorisation, insecure direct object references and missing tenant checks are outside their reach.

  • Cross-assembly data flow: run a SAST engine that builds a whole-program model on pull requests or nightly. See SAST vs DAST for where each technique fits.
  • Dependencies: CA rules check your code, not the packages it pulls in. Pair them with software composition analysis; see SAST vs SCA.
  • Runtime versions: an unsupported .NET runtime stops receiving security fixes whatever the analysers say. Track versions with the .NET End of Support tracker.
  • Secrets: CA5390 catches hard-coded encryption keys passed to cryptographic APIs, not connection strings or API tokens in configuration. Run a secret scanner on every commit and move service credentials into a secrets manager.
  • Human review: use analyser output to focus code review on the places where untrusted input meets a dangerous sink. General practice is in the Secure Coding Guide.

Measuring that it works

  • Coverage: share of .NET repositories with AnalysisModeSecurity set and a pinned AnalysisLevel (target: all active repositories).
  • Enforced rules: number of Security rules at error, trending up as backlogs reach zero.
  • Open findings: security warnings per repository, split into deserialisation, injection, cryptography and web framework families.
  • Suppression rate: security suppressions added per month and the share with a non-empty justification (target: 100 percent).
  • Time to fix: median days from a new security finding to merge of the fix.

Framework mapping

FrameworkReferenceHow the CA rules contribute
NIST SP 800-53 Rev 5SA-11(1) Static Code Analysis; SA-15 Development Process, Standards, and ToolsAutomated static analysis on every build with documented configuration
NIST SP 800-53 Rev 5SI-10 Information Input Validation; SC-13 Cryptographic ProtectionInjection and cryptography rules detect gaps in these controls in code
NIST CSF 2.0PR.PS-06Secure development practices integrated into the life cycle and measured
CIS Controls v8.116.12 Implement Code-Level Security ChecksStatic analysis in the build pipeline
ISO/IEC 27001:2022 Annex AA.8.28 Secure coding; A.8.29 Security testing in development and acceptanceEnforced coding rules and evidence of testing

Common failure patterns

  • Assuming defaults are enough: teams see analyser warnings in the IDE and assume security is covered, while rules such as CA2300, CA3001 and CA5350 are disabled by default.
  • Category severity without the mode: adding dotnet_analyzer_diagnostic.category-Security.severity = error and expecting it to enable rules that are off by default. It does not.
  • Floating on latest: leaving AnalysisLevel at latest, so an SDK upgrade adds warnings that break a release build and pressure the team into blanket suppressions.
  • Blanket none settings: silencing a noisy rule for the whole solution in .editorconfig instead of fixing or justifying specific findings.
  • Treating a clean build as a clean application: the taint rules do not see across assemblies or into business logic, so a zero count still needs SAST, dependency scanning and review.

Practitioner checklist

  • Add AnalysisModeSecurity set to All in a root Directory.Build.props.
  • Pin AnalysisLevel to a numbered release and review new rules when you move it.
  • Set EnableNETAnalyzers for .NET Standard and .NET Framework projects, or use the NuGet package, never both.
  • Record a baseline count of security warnings per rule and per project.
  • Raise deserialisation, injection, certificate validation and hard-coded key rules to error first.
  • Require SuppressMessage with a written Justification for every accepted security finding.
  • Protect .editorconfig and Directory.Build.props with code owner review.
  • Export SARIF from CI into your code scanning view.
  • Run cross-assembly SAST, dependency scanning and secret scanning alongside the CA rules.
  • Report coverage, enforced rule count and suppression rate monthly.

Standards and references

Related NHI Mgmt Group resources: Secure Coding Guide · SAST Triage Guide · Secure Coding Standard Template · CI/CD Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.