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
AnalysisModeSecuritytoAll(orAnalysisLevelSecuritytolatest-all) because most CA security rules are off in the default mode. - Pin the rule set version. Use a numbered
AnalysisLevelsuch as10.0or10-recommendedso an SDK upgrade does not add new build breaks without warning. - Fail the build on security rules only at first. Raise Security rules to
errorin.editorconfigrather than turning every warning into an error on day one. - Make every suppression explain itself. Prefer
SuppressMessagewith aJustificationin source overseverity = 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
CommandTextbuilt 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.NETTypeNameHandlingsettings, andDataSet/DataTablein 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,
ViewStateUserKeyand 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.
| Rule | Title | Risk it addresses | Usual fix |
|---|---|---|---|
| CA2100 | Review SQL queries for security vulnerabilities | SQL injection through a CommandText string built from a method argument | Parameterised commands or stored procedures |
| CA3001 | Review code for SQL injection vulnerabilities | HTTP request input reaching SQL command text | Parameters, never concatenation; allowlist dynamic identifiers |
| CA3002 | Review code for XSS vulnerabilities | Untrusted web input written to raw HTML | Framework encoding; avoid raw output helpers |
| CA3006 | Review code for process command injection vulnerabilities | Request input reaching process start | Fixed executable, argument list, allowlisted values |
| CA3007 | Review code for open redirect vulnerabilities | Redirects to attacker-chosen sites | Local-only redirect checks or allowlist |
| CA2300, CA2301, CA2302 | BinaryFormatter rules | Remote code execution and denial of service from untrusted input | Replace with System.Text.Json, XmlSerializer or DataContractSerializer |
| CA2326, CA2327 | TypeNameHandling values other than None; insecure JsonSerializerSettings | Polymorphic deserialisation gadgets | TypeNameHandling.None or a strict binder |
| CA3075 | Insecure DTD Processing | XML external entity disclosure | Prohibit DTDs, null XmlResolver |
| CA5350 | Do Not Use Weak Cryptographic Algorithms | TripleDES, SHA1, RIPEMD160 | AES; SHA256, SHA384 or SHA512 |
| CA5351 | Do Not Use Broken Cryptographic Algorithms | MD5, DES, RC2 | AES; SHA-2 family |
| CA5359 | Do not disable certificate validation | A validation callback that always returns true enables interception | Remove the callback; fix the trust chain |
| CA5364, CA5397 | Deprecated security protocols; deprecated SslProtocols values | TLS versions older than 1.2 | Let the OS choose; avoid hard-coding (CA5386, CA5398) |
| CA5379, CA5387 | Key derivation algorithm strength; iteration count | Rfc2898DeriveBytes defaulting to SHA1 or under 100,000 iterations | SHA256 or higher, higher iteration count, or a password hasher |
| CA5389 | Do not add archive item's path to the target file system path | Zip slip path traversal on extraction | Canonicalise and check the destination path |
| CA5390 | Do not hard-code encryption key | Keys extracted from binaries | Key vault or secrets store at runtime |
| CA5391 | Use antiforgery tokens in ASP.NET Core MVC controllers | Cross-site request forgery on POST, PUT, PATCH, DELETE | Global auto-validate filter |
| CA5394 | Do not use insecure randomness | Predictable tokens from System.Random | RandomNumberGenerator |
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
| Property | Values | Effect |
|---|---|---|
EnableNETAnalyzers | true, false | Turns on SDK analysers for .NET Standard and .NET Framework projects; already on for .NET 5 and later |
AnalysisLevel | latest (default for .NET 5+), preview, a version such as 10.0, or a compound such as 10-recommended | Chooses which release's rule set runs; a version number locks the set so no new warnings appear |
AnalysisMode | None, Default, Minimum, Recommended, All | Chooses how many rules are build warnings; All makes all rules warnings (with a short documented list of exceptions) |
AnalysisLevelSecurity, AnalysisModeSecurity | Same values as above | Applies the level or mode to the Security category only; falls back to the general property if omitted |
CodeAnalysisTreatWarningsAsErrors | true, false | Controls 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.
<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:
[*.{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 backlogNote 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.
- Centralise configuration. Commit
Directory.Build.propsand a root.editorconfigso local and CI builds match. Reject pull requests that change them without application security review (a CODEOWNERS entry works well). - Measure before enforcing. Enable
AnalysisModeSecurity=Allwith every security rule atwarning, run a full build, and export the counts per rule and per project. This is your baseline. - 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.
- 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
erroronce its count reaches zero. - Decide on warnings as errors. Building with
-warnaserrormakes all analysis warnings errors. If you want style or performance warnings to stay as warnings while security rules fail, rely on expliciterrorseverities instead, or setCodeAnalysisTreatWarningsAsErrorstofalseand raise security rules individually. - 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.
- Pin and plan upgrades. With
AnalysisLevelpinned, an SDK upgrade does not introduce new warnings. Schedule a review of the newer rule set each time you move the pin, rather than lettinglatestchange 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:
| Method | Scope | Audit value | Use when |
|---|---|---|---|
SuppressMessage attribute with Justification | One member or type | High: reason sits beside the code | Default for accepted security findings |
GlobalSuppressions.cs with Scope and Target | Named member, type or module | Medium: central but away from code | Generated code with no user source |
#pragma warning disable / restore | Lines between the pragmas | Low unless a comment explains it | Short, local exceptions in test code |
.editorconfig severity = none | File, folder or whole project | Low: silences every future finding | Test projects or tooling folders only |
dotnet_code_quality.CAxxxx.excluded_symbol_names | Named symbols for a rule or category | Medium | A vetted sanitiser or wrapper the taint rules cannot see through |
- Require a justification: make a missing or empty
Justificationa 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
nonesettings 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
AnalysisModeSecurityset and a pinnedAnalysisLevel(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
| Framework | Reference | How the CA rules contribute |
|---|---|---|
| NIST SP 800-53 Rev 5 | SA-11(1) Static Code Analysis; SA-15 Development Process, Standards, and Tools | Automated static analysis on every build with documented configuration |
| NIST SP 800-53 Rev 5 | SI-10 Information Input Validation; SC-13 Cryptographic Protection | Injection and cryptography rules detect gaps in these controls in code |
| NIST CSF 2.0 | PR.PS-06 | Secure development practices integrated into the life cycle and measured |
| CIS Controls v8.1 | 16.12 Implement Code-Level Security Checks | Static analysis in the build pipeline |
| ISO/IEC 27001:2022 Annex A | A.8.28 Secure coding; A.8.29 Security testing in development and acceptance | Enforced 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 = errorand expecting it to enable rules that are off by default. It does not. - Floating on latest: leaving
AnalysisLevelatlatest, 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
.editorconfiginstead 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
AnalysisModeSecurityset toAllin a rootDirectory.Build.props. - Pin
AnalysisLevelto a numbered release and review new rules when you move it. - Set
EnableNETAnalyzersfor .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
errorfirst. - Require
SuppressMessagewith a writtenJustificationfor every accepted security finding. - Protect
.editorconfigandDirectory.Build.propswith 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
- Microsoft Learn: Security rules (code analysis)
- Microsoft Learn: Overview of .NET source code analysis
- Microsoft Learn: Configuration options for code analysis
- Microsoft Learn: MSBuild reference for .NET SDK projects
- Microsoft Learn: How to suppress code analysis warnings
- Microsoft Learn: Deserialization risks in use of BinaryFormatter and related types
- OWASP: .NET Security Cheat Sheet
Related NHI Mgmt Group resources: Secure Coding Guide · SAST Triage Guide · Secure Coding Standard Template · CI/CD Security Guide