Skip to content

Secure Coding

Rule prefix: SEC · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID

Home · Rule index · Naming cheat sheet

This chapter covers the coding conventions that keep common vulnerabilities out of C# code: secrets in source, injection, unsafe paths and archives, weak cryptography, unsafe deserialization and XML, and sensitive data in exceptions and logs. Each rule has one correct form, one incorrect form and the reason. Where an analyzer reports a violation, the rule names its diagnostic ID. Rules without a tool check are manual rules that reviewers verify (TOOL-018).

Scope. These are coding-level conventions only. They do not replace threat modelling, a security review, or SAST and DAST scans. Framework-specific controls (ASP.NET Core antiforgery, cookies and token validation, cloud storage signatures) are outside this guide; for ASP.NET Core see its security documentation (MS-ASPNET-SEC). Incorrect examples marked "Insecure, do not use" show a vulnerable pattern so you can recognize it. Do not copy them.

Exceptions and catch blocks are covered in page 10, string comparison and culture in page 07, and data-access specifics (EF Core, Dapper) in page 14. The .editorconfig severities for security diagnostics are explained in page 15.

Security rules owned by other pages

Some security topics belong to the page that covers the language feature. They are listed here so one search finds every security rule, and each rule is written once, on the page that covers its feature: guard clauses (ERR-014), catch blocks (ERR-012), rethrowing with throw; (ERR-011), disposal (ERR-020), string comparison (LANG-041, which owns CA1307 at warning), culture (LANG-043, LANG-044) and nullable reference types (VAR-050). The table below repeats their rule statements.

ID Rule statement Page
ERR-011 DO rethrow a caught exception with throw; and, when translating it to another exception type, pass the original as the inner exception. 10
ERR-012 DO catch only exception types you can handle, use when filters instead of catching and rethrowing, never leave a catch block empty or return a default without logging (expected cancellation and the Try-pattern translation of ERR-016 excepted), and catch Exception only at a process or request boundary that logs it. 10
ERR-014 DO validate the arguments of public and protected members at entry with the static throw helpers (ArgumentNullException.ThrowIfNull, ArgumentException.ThrowIfNullOrWhiteSpace, ArgumentOutOfRangeException.ThrowIfNegativeOrZero, ObjectDisposedException.ThrowIf). 10
ERR-020 DO dispose every IDisposable or IAsyncDisposable object you create or own with using or await using, and dispose disposable fields in the owning type's Dispose. 10
LANG-041 DO pass an explicit StringComparison to every string comparison, prefix test, search and Equals call, using Ordinal or OrdinalIgnoreCase for identifiers, keys, paths, roles and other non-linguistic values. 07
LANG-043 DO pass CultureInfo.InvariantCulture when formatting or parsing values that machines read (files, logs, protocols, keys) and CultureInfo.CurrentCulture for text shown to users, and never rely on the implicit current culture; parse untrusted text with TryParse. 07
LANG-044 DO normalize case with ToUpperInvariant or ToLowerInvariant, or better compare with StringComparison.OrdinalIgnoreCase, instead of calling culture-sensitive ToUpper or ToLower. 07
VAR-050 DO enable nullable reference types in every project (<Nullable>enable</Nullable>) and fix every nullable warning (CS86xx) instead of suppressing it. 05

Rule index

ID Level Rule Enforced
SEC-012 DO compare secrets, tokens, signatures and message authentication codes with CryptographicOperations.FixedTimeEquals, never with ==, string.Equals or SequenceEqual. Manual
SEC-020 DO NOT hard-code a secret, password, API key, encryption key, certificate or connection string with credentials in source code, tests or comments; read it from configuration or a secret store at run time. CA5390, CA5403
SEC-030 DO pass every value that goes into a SQL statement as a parameter (DbParameter, Dapper parameter object, EF Core FromSql interpolation), never by concatenating or interpolating it into the SQL text, and take table or column names only from an allow-list. CA2100
SEC-031 DO start an external process with ProcessStartInfo.ArgumentList and UseShellExecute = false, and never pass untrusted input through a shell (cmd /c, sh -c) or a concatenated Arguments string. Manual
SEC-033 DO give every regular expression that processes untrusted input a match timeout or RegexOptions.NonBacktracking, prefer [GeneratedRegex] over constructing Regex at run time, and pass user-supplied fragments through Regex.Escape. SYSLIB1045
SEC-040 DO combine an untrusted path segment with Path.Join, canonicalize the result with Path.GetFullPath, and accept it only if it starts with the base directory (compared with StringComparison.Ordinal, base path ending in a separator). Manual
SEC-041 DO check, before extracting each archive entry, that its full destination path stays inside the target directory. CA5389
SEC-050 DO generate tokens, keys, salts, nonces and other values that must be unguessable with RandomNumberGenerator, and use Random only for values with no security purpose. CA5394
SEC-051 DO NOT use MD5, SHA-1, DES, 3DES or RC2 for any security purpose or implement your own cryptographic algorithm; use SHA-256 or stronger (SHA256.HashData) and authenticated encryption such as AesGcm with an explicit tag size. CA5350, CA5351
SEC-053 DO hash passwords with Rfc2898DeriveBytes.Pbkdf2 using HMAC-SHA256, at least 600,000 iterations (OWASP) and a random salt of at least 16 bytes per password, and never store passwords in plain text or as a single unsalted hash. CA5379, CA5387, CA5388, CA5373
SEC-060 DO NOT use BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter or ObjectStateFormatter; serialize with System.Text.Json or another contract-based serializer. CA2300, CA2301, CA2302, CA2305, CA2310, CA2311, CA2312, CA2315
SEC-061 DO deserialize polymorphic JSON only through an explicit allow-list of derived types ([JsonPolymorphic] with [JsonDerivedType]), and keep Newtonsoft.Json TypeNameHandling at None. CA2326, CA2327, CA2328, CA2329, CA2330
SEC-062 DO read untrusted XML through XmlReader.Create with DtdProcessing = DtdProcessing.Prohibit and XmlResolver = null, and pass that reader to XmlSerializer, XmlDocument and XPathDocument instead of a stream or path. CA3075, CA3076, CA3077, CA5366, CA5369, CA5370, CA5371, CA5372, CA5374
SEC-072 DO NOT put secrets, credentials, connection strings, SQL text, full personal data or internal file paths into an exception message or error response that reaches a caller; log details internally and return a generic message with a correlation ID. Manual
SEC-073 DO log with a constant message template that names its placeholders in PascalCase ("Placed order {OrderId}"), never with interpolated or concatenated text, and use [LoggerMessage] source-generated methods on hot paths. CA2254, CA2017, CA2253
SEC-074 DO NOT write passwords, tokens, API keys, encryption keys, full card numbers or raw request and response bodies to a log; log identifiers and counts instead. Manual

Secrets and comparisons

These rules cover how to compare secrets and where to keep them.

SEC-012

DO compare secrets, tokens, signatures and message authentication codes with CryptographicOperations.FixedTimeEquals, never with ==, string.Equals or SequenceEqual.

✅ Correct

public static bool IsValidSignature(ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual)
{
    return System.Security.Cryptography.CryptographicOperations.FixedTimeEquals(expected, actual);
}

❌ Incorrect — comparison time depends on the content — Insecure, do not use

// INSECURE: comparison time leaks how many leading bytes match
public static bool IsValidSignature(ReadOnlySpan<byte> expected, ReadOnlySpan<byte> actual)
{
    return expected.SequenceEqual(actual); // comparison time depends on the first byte that differs
}

Why: ==, string.Equals and SequenceEqual stop at the first byte that differs. An attacker who measures response times can learn a valid value one byte at a time. FixedTimeEquals takes the same time for any content of the same length. It returns false at once when the lengths differ, so the length of a secret must not itself be secret. To compare a string token, encode both values to bytes first.

Exceptions: Values that are not secret (identifiers, public keys, version strings) use the ordinary comparison rules (LANG-041).

Scope: Comparisons of secrets, tokens, signatures and MACs · Enforced: Manual · Sources: MS-FIXEDTIME, MS-CA

SEC-020

DO NOT hard-code a secret, password, API key, encryption key, certificate or connection string with credentials in source code, tests or comments; read it from configuration or a secret store at run time.

✅ Correct

public static string GetOrdersConnectionString(IConfiguration configuration)
{
    string? value = configuration.GetConnectionString("Orders");

    return value ?? throw new InvalidOperationException("Connection string Orders is missing.");
}

❌ Incorrect — hard-coded encryption key — Insecure, do not use

// INSECURE: the key is compiled into the assembly, so anyone who can read the binary can read the key
using System.Security.Cryptography;

namespace Contoso.Orders;

public static class OrderProtector
{
    public static void Protect(byte[] nonce, byte[] plaintext, byte[] ciphertext, byte[] tag)
    {
        byte[] key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; // hard-coded encryption key
        using var aes = new AesGcm(key, tag.Length); // hard-coded key reaches the cipher
        aes.Encrypt(nonce, plaintext, ciphertext, tag);
    }
}

Why: A secret in source code is copied into every clone, build artifact, backup and decompiled assembly, and it stays in version history after you delete it. Changing it needs a new build. Configuration providers (environment variables, user secrets in development, a secret store in production) keep the value outside the code, so you can rotate it without a release. The same applies to tests and comments: use a placeholder such as "<from-secret-store>" and read the real value from configuration. The error message above names the missing setting and never its value. Do not reach for SecureString to protect a secret in new code: it is not recommended for new development, it is not encrypted on non-Windows platforms, and its text is exposed as plain text when you use it.

Exceptions: Values that are not secret (a public client ID, a public key, a placeholder in a sample) may appear in source.

Scope: Passwords, API keys, connection strings, encryption keys and certificates in source, tests and comments · Enforced: CA5390, CA5403 · Sources: OWASP-SECRETS, MS-SECURESTRING, MS-CA, MS-CONV

Injection

These rules cover untrusted input that reaches SQL, external processes and regular expressions.

SEC-030

DO pass every value that goes into a SQL statement as a parameter (DbParameter, Dapper parameter object, EF Core FromSql interpolation), never by concatenating or interpolating it into the SQL text, and take table or column names only from an allow-list.

✅ Correct

public static object? FindCustomerId(System.Data.Common.DbConnection connection, string name)
{
    using System.Data.Common.DbCommand command = connection.CreateCommand();
    command.CommandText = "SELECT Id FROM Customers WHERE Name = @name";

    System.Data.Common.DbParameter parameter = command.CreateParameter();
    parameter.ParameterName = "@name";
    parameter.Value = name;
    command.Parameters.Add(parameter);

    return command.ExecuteScalar();
}

✅ Correct — table or column names come from an allow-list

public static string GetSortClause(string column)
{
    return column switch
    {
        "Name" => "ORDER BY Name",
        "CreatedAt" => "ORDER BY CreatedAt",
        _ => throw new ArgumentOutOfRangeException(nameof(column), "Unsupported sort column.")
    };
}

❌ Incorrect — value concatenated into SQL — Insecure, do not use

// INSECURE: a value is concatenated into the SQL text, so input can change the statement
public static object? FindCustomerId(System.Data.Common.DbConnection connection, string name)
{
    using System.Data.Common.DbCommand command = connection.CreateCommand();
    command.CommandText = "SELECT Id FROM Customers WHERE Name = '" + name + "'"; // value concatenated into SQL

    return command.ExecuteScalar();
}

Why: A parameter travels to the database separately from the statement, so the database never parses it as SQL. Concatenated or interpolated text is parsed as part of the statement. Quoting or escaping by hand fails on the first case you did not think of. Parameters cannot stand in for identifiers (table and column names), so choose those from a fixed list in code and never from input, as the second example does. EF Core and Dapper specifics, including why FromSql($"...") is safe, are in DATA-010.

See also: DATA-010 (EF Core FromSql, ExecuteSql and Dapper).

Scope: SQL commands built in ADO.NET, Dapper and EF Core raw SQL (EF Core specifics: DATA-010) · Enforced: CA2100 · Sources: OWASP-SQLI, MS-CA, MS-EF, DAPPER

SEC-031

DO start an external process with ProcessStartInfo.ArgumentList and UseShellExecute = false, and never pass untrusted input through a shell (cmd /c, sh -c) or a concatenated Arguments string.

✅ Correct

public static ProcessStartInfo CreateGitLog(string branchName)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(branchName);
    if (branchName.StartsWith('-'))
    {
        throw new ArgumentException("The branch name must not start with '-'.", nameof(branchName));
    }

    var startInfo = new ProcessStartInfo("git") { UseShellExecute = false };
    startInfo.ArgumentList.Add("log");
    startInfo.ArgumentList.Add("--end-of-options");
    startInfo.ArgumentList.Add(branchName);

    return startInfo;
}

❌ Incorrect — input passed through a shell — Insecure, do not use

// INSECURE: the input reaches a shell, which interprets operators and separators inside it
public static ProcessStartInfo CreateGitLog(string branchName)
{
    return new ProcessStartInfo("cmd", "/c git log " + branchName); // input passed through a shell
}

Why: Each ArgumentList item reaches the program as one argument, and the runtime applies the platform's quoting rules for you. A shell, or a concatenated Arguments string, splits and interprets the text first, so input can add commands or arguments. Many programs also read an argument that starts with - as an option, so the example rejects a leading - (a stricter allow-list pattern for reference names is better still) and puts --end-of-options before the value, which Git supports from version 2.24; other tools have their own end-of-options marker. Code that runs with elevated rights should also pass the full path of the executable instead of searching PATH. The taint rule CA3006 follows only HTTP request input, so the security baseline keeps it at suggestion and no build check covers this rule.

Scope: Starting external processes · Enforced: Manual · Sources: OWASP-OSCMD, MS-ARGLIST, MS-CA

SEC-033

DO give every regular expression that processes untrusted input a match timeout or RegexOptions.NonBacktracking, prefer [GeneratedRegex] over constructing Regex at run time, and pass user-supplied fragments through Regex.Escape.

✅ Correct

using System.Text.RegularExpressions;

namespace Contoso.Orders;

public static partial class SkuPattern
{
    [GeneratedRegex("^SKU-[0-9]{4}$", RegexOptions.None, matchTimeoutMilliseconds: 100)]
    private static partial Regex Sku();

    public static bool IsSku(string text) => Sku().IsMatch(text);
}

✅ Correct — user-supplied text inside a pattern

using System.Text.RegularExpressions;

namespace Contoso.Orders;

public static class WordSearch
{
    public static bool HasWord(string text, string word)
    {
        var pattern = new Regex(Regex.Escape(word), RegexOptions.NonBacktracking);

        return pattern.IsMatch(text);
    }
}

❌ Incorrect — run-time regex without a timeout — Insecure, do not use

// INSECURE: no match timeout (the default is infinite), so a slow pattern can run unbounded on hostile input
using System.Text.RegularExpressions;

namespace Contoso.Orders;

public static class SkuPattern
{
    public static bool IsSku(string text) => Regex.IsMatch(text, "^SKU-[0-9]{4}$"); // run-time regex without a timeout
}

Why: A backtracking engine can take exponential time on some patterns and inputs, so one request can hold a CPU core for minutes. A match timeout stops the match with a RegexMatchTimeoutException, which you handle at the boundary (ERR-012). RegexOptions.NonBacktracking matches in time linear in the input, but it does not support backreferences, lookarounds or atomic groups. [GeneratedRegex] builds the matcher at compile time, which is faster to start, and diagnostic SYSLIB1045 reports run-time constructions with a constant pattern. SYSLIB1045 does not check timeouts: it asks for source generation, so you still set the timeout in the attribute. The pattern in the incorrect example cannot backtrack heavily, but any pattern added later to the same call site inherits the missing limit. Regex.Escape makes user text match literally instead of being read as pattern syntax.

Exceptions: A pattern applied only to input you control (a constant or a file shipped with the application) needs no timeout.

Scope: Regular expressions that process untrusted input · Enforced: SYSLIB1045 · Sources: MS-REGEX-BP, MS-SYSLIB-RGX, OWASP-REGEX, MS-CA

Files and paths

These rules cover paths built from untrusted text and archive extraction.

SEC-040

DO combine an untrusted path segment with Path.Join, canonicalize the result with Path.GetFullPath, and accept it only if it starts with the base directory (compared with StringComparison.Ordinal, base path ending in a separator).

✅ Correct

public static string ResolveExportPath(string baseDirectory, string fileName)
{
    ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
    string root = Path.GetFullPath(baseDirectory + Path.DirectorySeparatorChar);
    string fullPath = Path.GetFullPath(Path.Join(root, fileName));
    if (!fullPath.StartsWith(root, StringComparison.Ordinal))
    {
        throw new ArgumentException("The file name must stay inside the export directory.", nameof(fileName));
    }

    return fullPath;
}

❌ Incorrect — Path.Combine with an untrusted segment — Insecure, do not use

// INSECURE: Path.Combine lets a rooted or ../ segment escape the base directory
public static string ResolveExportPath(string baseDirectory, string fileName)
{
    return Path.Combine(baseDirectory, fileName); // a rooted or ../ segment escapes the base directory
}

Why: Path.Combine drops every earlier segment when a later one is rooted, and a .. segment climbs out of the base directory. Path.GetFullPath removes the .. segments, so the prefix check sees the real destination. The base path ends in a separator, so a sibling such as exports-old does not pass for exports. The comparison is ordinal because path text is not linguistic (LANG-041). The check works on names: GetFullPath does not resolve symbolic links. The guard clause is ERR-014, and the message names no path (SEC-072). The taint rule CA3003 follows only HTTP request input, so the security baseline keeps it at suggestion.

Scope: File paths built from untrusted segments · Enforced: Manual · Sources: OWASP-PATH, MS-PATH, MS-CA

SEC-041

DO check, before extracting each archive entry, that its full destination path stays inside the target directory.

✅ Correct

public static void ExtractEntry(System.IO.Compression.ZipArchiveEntry entry, string target)
{
    string root = Path.GetFullPath(target + Path.DirectorySeparatorChar);
    string destination = Path.GetFullPath(Path.Join(root, entry.FullName));
    if (!destination.StartsWith(root, StringComparison.Ordinal))
    {
        throw new InvalidDataException("An archive entry points outside the target directory.");
    }

    Directory.CreateDirectory(Path.GetDirectoryName(destination) ?? root);
    System.IO.Compression.ZipFileExtensions.ExtractToFile(entry, destination, overwrite: false);
}

❌ Incorrect — entry path not checked — Insecure, do not use

// INSECURE: the entry name is joined to the target path without a check, so an entry can write outside it
using System.IO.Compression;

namespace Contoso.Orders;

public static class ArchiveExtractor
{
    public static void ExtractAll(ZipArchive archive, string target)
    {
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            entry.ExtractToFile(Path.Combine(target, entry.FullName)); // entry path not checked
        }
    }
}

Why: An archive entry name is attacker-controlled text. A name such as one that starts with .. or is rooted makes the extraction write to a different directory ("zip slip"), which can replace configuration or executable files. Computing the full destination path first and comparing it with the target directory catches both cases (SEC-040 explains the check). Call ExtractEntry for each entry whose Name is not empty; entries that end in / are directories. Where you do not need per-entry control, ZipFile.ExtractToDirectory performs this check itself.

Scope: Extracting archives · Enforced: CA5389 · Sources: MS-CA, OWASP-PATH

Cryptography

These rules cover random values, hashing, encryption and password storage.

SEC-050

DO generate tokens, keys, salts, nonces and other values that must be unguessable with RandomNumberGenerator, and use Random only for values with no security purpose.

✅ Correct

public static string CreateResetToken()
{
    byte[] bytes = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32);

    return Convert.ToHexString(bytes);
}

❌ Incorrect — Random used for a security code — Insecure, do not use

// INSECURE: Random is predictable, so an attacker can guess the next code
public static int CreateResetCode()
{
    return new Random().Next(100_000, 1_000_000); // predictable number for a security code
}

Why: Random is a statistical generator. Its output follows from its internal state, so an attacker who sees a few values can predict later ones. RandomNumberGenerator draws from the operating system's cryptographic source. CA5394 flags every use of Random. For a value with no security purpose (shuffling test data, retry jitter), keep Random and suppress the diagnostic on that line with a SuppressMessage attribute that states the reason. Do not lower the severity for the whole project.

Scope: Random values for tokens, keys, salts, nonces, identifiers and passwords · Enforced: CA5394 · Sources: MS-RNG, MS-CA

SEC-051

DO NOT use MD5, SHA-1, DES, 3DES or RC2 for any security purpose or implement your own cryptographic algorithm; use SHA-256 or stronger (SHA256.HashData) and authenticated encryption such as AesGcm with an explicit tag size.

✅ Correct

public static byte[] Fingerprint(byte[] content) => System.Security.Cryptography.SHA256.HashData(content);

✅ Correct — authenticated encryption with an explicit tag size

private const int NonceSize = 12;
private const int TagSize = 16;

public static (byte[] Nonce, byte[] Ciphertext, byte[] Tag) Protect(byte[] key, byte[] plaintext)
{
    byte[] nonce = System.Security.Cryptography.RandomNumberGenerator.GetBytes(NonceSize);
    byte[] ciphertext = new byte[plaintext.Length];
    byte[] tag = new byte[TagSize];
    using var aes = new System.Security.Cryptography.AesGcm(key, TagSize);
    aes.Encrypt(nonce, plaintext, ciphertext, tag);

    return (nonce, ciphertext, tag);
}

❌ Incorrect — MD5 hash for a security purpose — Insecure, do not use

// INSECURE: MD5 is broken, so different inputs can be made to produce the same hash
public static byte[] Fingerprint(byte[] content)
{
    return System.Security.Cryptography.MD5.HashData(content); // broken hash algorithm
}

Why: Practical collision attacks exist for MD5 and SHA-1, and DES, 3DES and RC2 have short keys or blocks. A home-made algorithm has had no public analysis, so assume it is breakable. AesGcm encrypts and authenticates, so a changed ciphertext fails to decrypt. Pass the tag size to the constructor (the constructor without it is obsolete). The method creates a new random nonce for every message, so a caller cannot reuse one under the same key (with random 96-bit nonces, rotate the key well before about 2^32 messages per key, the nonce-collision bound), and it returns the nonce and the tag because decryption needs both. Keep the key in a secret store (SEC-020).

Exceptions: A legacy protocol that fixes MD5 or SHA-1 may force their use. Isolate that code, suppress the diagnostic on that line with a reason, and do not use the result to make a security decision.

Scope: Hashing, encryption and signatures for security purposes · Enforced: CA5350, CA5351 · Sources: MS-CA, MS-SYSLIB, OWASP

SEC-053

DO hash passwords with Rfc2898DeriveBytes.Pbkdf2 using HMAC-SHA256, at least 600,000 iterations (OWASP) and a random salt of at least 16 bytes per password, and never store passwords in plain text or as a single unsalted hash.

✅ Correct

using System.Security.Cryptography;

namespace Contoso.Orders;

public static class PasswordHasher
{
    private const int SaltSizeBytes = 16;
    private const int HashSizeBytes = 32;
    private const int Pbkdf2Iterations = 600_000;

    public static byte[] Hash(string password, out byte[] salt)
    {
        salt = RandomNumberGenerator.GetBytes(SaltSizeBytes);

        return Rfc2898DeriveBytes.Pbkdf2(password, salt, Pbkdf2Iterations, HashAlgorithmName.SHA256, HashSizeBytes);
    }
}

❌ Incorrect — obsolete constructor with SHA-1 — Insecure, do not use

// INSECURE: the obsolete constructor is used with SHA-1, a weak choice for password hashing
using System.Security.Cryptography;

namespace Contoso.Orders;

public static class PasswordHasher
{
    public static byte[] Hash(string password, byte[] salt)
    {
        using var kdf = new Rfc2898DeriveBytes(password, salt, 600_000, HashAlgorithmName.SHA1); // obsolete constructor

        return kdf.GetBytes(32);
    }
}

Why: A password hash must be slow, so that guessing is expensive, and salted, so that equal passwords give different hashes and precomputed tables are useless. PBKDF2 with a high iteration count does both. The OWASP Password Storage Cheat Sheet lists Argon2id as its first choice and PBKDF2-HMAC-SHA256 with 600,000 iterations where a built-in, FIPS-validated algorithm is needed; the base class library has no Argon2id. Hardware keeps getting faster, so re-check the count against the current OWASP guidance. The 16-byte salt is the 128-bit minimum that NIST SP 800-132 recommends for PBKDF2. Store the salt, the iteration count and the algorithm name next to the hash so that you can raise the count later. To check a login, hash the supplied password with the stored salt and compare with FixedTimeEquals (SEC-012). The salt comes from RandomNumberGenerator (SEC-050).

Scope: Storing passwords · Enforced: CA5379, CA5387, CA5388, CA5373 · Sources: OWASP, NIST-800-132, MS-CA, MS-SYSLIB

Deserialization and XML

These rules cover serializers that create types from the payload and the reading of untrusted XML.

SEC-060

DO NOT use BinaryFormatter, SoapFormatter, NetDataContractSerializer, LosFormatter or ObjectStateFormatter; serialize with System.Text.Json or another contract-based serializer.

✅ Correct

using System.Text.Json;

namespace Contoso.Orders;

public sealed record OrderDto(int Id, decimal Total);

public static class OrderReader
{
    public static OrderDto? ReadOrder(string json) => JsonSerializer.Deserialize<OrderDto>(json);
}

❌ Incorrect — BinaryFormatter reads types from the payload — Insecure, do not use

// INSECURE: the payload decides which types are created, which can run attacker-chosen code
#pragma warning disable SYSLIB0011
using System.Runtime.Serialization.Formatters.Binary;

namespace Contoso.Orders;

public static class OrderReader
{
    public static object ReadOrder(Stream stream) => new BinaryFormatter().Deserialize(stream); // insecure deserializer
}
#pragma warning restore SYSLIB0011

Why: These formatters write type names into the payload and create those types on read. An attacker who controls the payload controls what is instantiated, and Microsoft states that BinaryFormatter cannot be made safe. In .NET 9 and later the BinaryFormatter implementation is removed and its methods throw, so the code also fails at run time. A contract-based serializer such as System.Text.Json reads only the members of the type you name. The #pragma in the incorrect example only keeps the obsolete-API warning from hiding the security diagnostic. Never add it to real code.

Scope: Binary and other type-embedding serializers · Enforced: CA2300, CA2301, CA2302, CA2305, CA2310, CA2311, CA2312, CA2315 · Sources: MS-BF, OWASP-DESER, MS-CA, MS-SYSLIB

SEC-061

DO deserialize polymorphic JSON only through an explicit allow-list of derived types ([JsonPolymorphic] with [JsonDerivedType]), and keep Newtonsoft.Json TypeNameHandling at None.

✅ Correct

using System.Text.Json.Serialization;

namespace Contoso.Orders;

[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(CardPaymentDto), "card")]
public abstract record PaymentDto(decimal Amount);

public sealed record CardPaymentDto(decimal Amount, string MaskedNumber) : PaymentDto(Amount);

❌ Incorrect — type name read from the payload — Insecure, do not use

// INSECURE: a type name read from the payload decides which class is created
using System.Text.Json;

namespace Contoso.Orders;

public static class PaymentReader
{
    public static object? Read(string json)
    {
        using JsonDocument document = JsonDocument.Parse(json);
        string? typeName = document.RootElement.GetProperty("type").GetString();
        Type? type = typeName is null ? null : Type.GetType(typeName); // type looked up from payload text

        return type is null ? null : Activator.CreateInstance(type); // instance of the payload's type
    }
}

Why: With [JsonDerivedType], the serializer can create only the types you list, each under a name you assign. TypeNameHandling other than None makes Newtonsoft.Json read a .NET type name from the payload and create that type, which gives the sender the same power as the formatters in SEC-060. The incorrect example reproduces that mechanism with plain System.Text.Json code (look up a type by a name from the payload, then create it), so it needs no extra package. The diagnostics CA2326 to CA2330 analyze code that references Newtonsoft.Json, so they apply only to projects that use that package.

Scope: Polymorphic JSON deserialization · Enforced: CA2326, CA2327, CA2328, CA2329, CA2330 · Sources: MS-JSON-POLY, OWASP-DESER, MS-CA

SEC-062

DO read untrusted XML through XmlReader.Create with DtdProcessing = DtdProcessing.Prohibit and XmlResolver = null, and pass that reader to XmlSerializer, XmlDocument and XPathDocument instead of a stream or path.

✅ Correct

using System.Xml;
using System.Xml.Serialization;

namespace Contoso.Orders;

public static class XmlInput
{
    public static T? Read<T>(Stream stream)
        where T : class
    {
        var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null };
        using var reader = XmlReader.Create(stream, settings);

        return new XmlSerializer(typeof(T)).Deserialize(reader) as T;
    }
}

❌ Incorrect — XML read from a raw stream — Insecure, do not use

// INSECURE: the serializer reads the raw stream with reader settings you did not choose
using System.Xml.Serialization;

namespace Contoso.Orders;

public static class XmlInput
{
    public static object? ReadOrder(Stream stream)
    {
        return new XmlSerializer(typeof(Order)).Deserialize(stream); // deserializes from a raw stream
    }
}

Why: XML can declare a document type definition (DTD) that defines entities, including entities that load a file or a URL while the parser runs. Prohibiting DTDs and removing the resolver closes that route. The defaults of XmlReaderSettings are already safe on current .NET, so setting both values states the intent in the code, protects against later changes to the settings, and satisfies the analyzers, which accept a configured reader and report a stream or path. CA5369 reports XmlSerializer.Deserialize on a stream. Never enable DtdProcessing.Parse for input you do not control.

Scope: Reading XML from untrusted sources · Enforced: CA3075, CA3076, CA3077, CA5366, CA5369, CA5370, CA5371, CA5372, CA5374 · Sources: OWASP-XXE, MS-XMLSEC, MS-CA

Errors and logging

These rules cover what exception messages, error responses and logs may contain.

SEC-072

DO NOT put secrets, credentials, connection strings, SQL text, full personal data or internal file paths into an exception message or error response that reaches a caller; log details internally and return a generic message with a correlation ID.

✅ Correct

public static void Import(ILogger logger, int orderId, string correlationId, Action importOrder)
{
    try
    {
        importOrder();
    }
    catch (IOException ex)
    {
        logger.LogError(ex, "Order {OrderId} import failed: {CorrelationId}", orderId, correlationId);

        throw new InvalidOperationException($"The order file could not be imported. Reference {correlationId}.", ex);
    }
}

❌ Incorrect — SQL text and connection string in the message — Insecure, do not use

// INSECURE: the message exposes SQL text and the connection string to the caller
public static void Fail(IDbCommand command, string connectionString)
{
    string message = $"Query failed: {command.CommandText} on {connectionString}"; // SQL and connection string

    throw new InvalidOperationException(message);
}

Why: The caller of a service can be an external user, and exception text often ends up in an error page, a response body or a client log. SQL text, file paths and connection strings tell an attacker how the system is built, and a connection string can contain credentials. The log keeps the full exception for the operator, and the correlation ID in the generic message lets support find that entry. The original exception travels as the inner exception so that code inside your service can still inspect it; the boundary that turns exceptions into responses returns only the message and the correlation ID, never ToString() or the inner exception. Catch the narrowest type you can handle (ERR-012). The taint rule CA3004 follows only HTTP request input, so the security baseline keeps it at suggestion and no build check covers this rule.

See also: ERR-030 (a stable error code lets a caller tell failures apart without the internal detail that this rule keeps out of the message).

Scope: Exception messages and error responses that reach callers · Enforced: Manual · Sources: OWASP-ERR, MS-EXC

SEC-073

DO log with a constant message template that names its placeholders in PascalCase ("Placed order {OrderId}"), never with interpolated or concatenated text, and use [LoggerMessage] source-generated methods on hot paths.

✅ Correct

using Microsoft.Extensions.Logging;

namespace Contoso.Orders;

public static partial class OrderLog
{
    [LoggerMessage(Level = LogLevel.Information, Message = "Placed order {OrderId} with {LineCount} lines")]
    public static partial void OrderPlaced(ILogger logger, int orderId, int lineCount);
}

✅ Correct — constant template at a call site

public static void LogShipped(ILogger logger, int orderId) => logger.LogInformation("Shipped order {OrderId}", orderId);

❌ Incorrect — interpolated log template

public static void LogPlaced(ILogger logger, int orderId)
{
    logger.LogInformation($"Placed order {orderId}"); // interpolated log template
}

Why: A constant template keeps OrderId as a named property that a log store can filter and group, and the template text is one string for all events. An interpolated string builds a different message every time, loses the property, allocates on every call even when the level is off, and, with structured sinks that parse templates, lets user text add or change properties. [LoggerMessage] generates the formatting code at compile time, which avoids boxing and the template parse on each call. Interpolation is right for display text (VAR-033) and wrong for log templates. Diagnostic CA2254 reports a non-constant template, CA2017 a placeholder count that does not match the arguments, and CA2253 a numeric placeholder name. CA1848 asks for [LoggerMessage] on every log call; it is noisy at warning, so it ships at suggestion.

See also: VAR-033 (interpolated strings for display text).

Scope: Log calls through ILogger · Enforced: CA2254, CA2017, CA2253 · Sources: MS-CA, MS-CONV, OWASP-LOG

SEC-074

DO NOT write passwords, tokens, API keys, encryption keys, full card numbers or raw request and response bodies to a log; log identifiers and counts instead.

✅ Correct

public static void LogPasswordChanged(ILogger logger, int customerId)
{
    logger.LogInformation("Customer {CustomerId} changed the password", customerId);
}

❌ Incorrect — password written to the log — Insecure, do not use

// INSECURE: the password is written to the log in plain text
public static void LogLogin(ILogger logger, string userName, string password)
{
    logger.LogInformation("Login for {UserName} with password {Password}", userName, password); // password logged
}

Why: Logs are copied to files, search indexes and support tools, kept for months and read by many more people than the production database. A secret that reaches a log is therefore exposed to all of them and cannot be taken back. An identifier or a count still lets you trace what happened. Request and response bodies can contain any field a caller sends, so log selected fields, not the whole body. For the same reason, never pass a whole record, request object or anonymous object that holds secrets or personal data to a log call, because its generated ToString() prints every public member; a type that holds secrets overrides PrintMembers (records) or ToString().

Scope: Values written to logs · Enforced: Manual · Sources: OWASP-LOG, MS-CA

Sources

The keys cited in this chapter are listed on the Sources page.

MS-CA, MS-CONV, MS-SYSLIB, MS-SYSLIB-RGX, MS-BF, MS-EF, MS-EXC, MS-FIXEDTIME, MS-ARGLIST, MS-RNG, MS-REGEX-BP, MS-XMLSEC, MS-SECURESTRING, MS-PATH, MS-JSON-POLY, MS-ASPNET-SEC, DAPPER, OWASP, OWASP-SQLI, OWASP-OSCMD, OWASP-XXE, OWASP-DESER, OWASP-LOG, OWASP-ERR, OWASP-SECRETS, OWASP-PATH, OWASP-REGEX, NIST-800-132.

Previous: Testing Conventions · Home · Next: Data Access