Security rules
Cryptography, regex safety, and untrusted input.
Rules
| Rule | Title | Code fix |
|---|---|---|
| E128071 | Use an approved cryptographic algorithm | Yes |
| E128075 | Use RandomNumberGenerator instead of Random in crypto context | Yes |
| E128091 | Use ArgumentList instead of a built Arguments string on ProcessStartInfo | Yes |
| E128142 | Do not instantiate a Managed or CNG cryptography type | Yes |
| E128143 | Use an RSA key of at least 3072 bits or an approved curve | No |
| E128144 | Use an authenticated cipher mode | No |
| E128145 | Use a strong PBKDF2 configuration | No |
| E128146 | Use TLS 1.2 or later | Yes |
| E128147 | RNGCryptoServiceProvider is deprecated | Yes |
| E128148 | Do not use a cipher excluded by policy | No |
| E128149 | Use the full 16-byte AES-GCM tag | Yes |
| E128150 | Do not use SHA-3, SHAKE or KMAC | Yes |
| E128151 | Use an HMAC key at least as long as the hash output | No |
| E128156 | HttpClient certificate validation accepts every certificate (default: Error) | Yes |
| E128157 | Fixed-time comparison of a secret-derived value | Yes |
| E128164 | Hardcoded absolute URL in source | No |
| E128165 | Hardcoded secret or connection string in source | No |
| E128166 | Sensitive value passed to a logger call | No |
| E128167 | Deferred-work comment with no work-item reference | No |
| E128168 | Skipped test with no work-item reference in its reason | No |
| E128169 | [Obsolete] with no message | No |
| E128184 | Recursive delete outside a proven safe root (default: Info) | No |
| E128191 | PFX import without EphemeralKeySet | No |
| E128202 | Unvalidated JWT claims used as an identity | No |
| E128222 | Path.Combine of a root .FullName and an uncontained leaf | Yes |
| E128227 | HTTP body read without a size bound | Yes |
| E128228 | Token validation flag set to constant false | No |
| E128241 | CORS policy allows any origin with credentials | No |
| E128242 | Antiforgery missing on a state-changing action | Yes |
| E128256 | Local filesystem path passed to a logger call | Yes |
| E128263 | Containment test compares a root with no directory separator | Yes |
| E128264 | [GeneratedRegex] repeated group has overlapping alternatives | No |
| E128265 | Non-constant regex pattern with no timeout | No |
| E128266 | Certificate chain result ignored or policy weakened | Yes |
| E128267 | Decompression loop has no output bound | Yes |
| E128268 | Symmetric key set from a text encoding | No |
| E128272 | Post-quantum migration review (opt-in, default: Info) | No |
Rule details
E128071: Approved cryptographic algorithm
Flags algorithms that cryptography policy blocks: MD5, SHA1, RIPEMD160, DES, RC2, TripleDES, the MAC types built on them, ChaCha20Poly1305 and PasswordDeriveBytes. It covers constructors, static Create and HashData members, method groups, legacy factories that select a weak algorithm by default, and any cryptography API that takes a blocked HashAlgorithmName.
It also flags a constant blocked XML-DSig or XML-Enc URI, CmsSigner.DigestAlgorithm set to a blocked object identifier, PbeEncryptionAlgorithm.TripleDes3KeyPkcs12, RSAEncryptionPadding.Pkcs1 on an RSA encryption call, the PKCS#1 key exchange formatters, and DSA signature generation. DSA verification stays allowed.
// Before (warns)
using var md5 = MD5.Create();
using var hmac = new HMACSHA1(key);
var cipher = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
// After
using var sha256 = SHA256.Create();
using var hmac = new HMACSHA256(key);
var cipher = rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256);
E128075: Random in crypto context
Flags System.Random, and a class derived from it, in two cases. First, a random value flows into a variable, field, property or buffer with a security-sensitive name such as token, salt, sessionId or key. Second, a new instance or Random.Shared appears in a file that references a type from System.Security.Cryptography or Microsoft.AspNetCore.Cryptography. A file also counts as a cryptography file when it names a member of a cryptography type. System.Random is not cryptographically secure. Use RandomNumberGenerator instead.
The check is a heuristic. It judges only the receiving name, and the file check reports every Random creation in a cryptography file. A sensitive name matches as a whole word, so secretKey reports and secretary does not. The name set also comes from the referenced assemblies.
The code fix replaces Random.Shared.Next with RandomNumberGenerator.GetInt32. Next() becomes GetInt32(int.MaxValue). The fix declines a variable bound, an empty range and NextDouble.
// Before (warns)
var token = Random.Shared.Next(100000, 999999).ToString();
// After
var token = RandomNumberGenerator.GetInt32(100000, 999999).ToString();
E128091: ProcessStartInfo.Arguments built string
Flags a ProcessStartInfo object initializer where Arguments is assigned a non-empty string (literal, interpolated, identifier, or otherwise) and ArgumentList isn’t populated in the same initializer. A hand-built Arguments string needs its own shell-style quoting/escaping; ArgumentList passes each argument through untouched, avoiding injection risk from unescaped or mis-escaped values.
A fix is offered only when the assigned expression is a plain string literal or a single interpolated string with a whitespace/quote-splittable shape — arbitrary concatenation, method calls, and identifiers still get the diagnostic but no automatic fix.
// Before (warns)
var startInfo = new ProcessStartInfo
{
FileName = "tool",
Arguments = $"-x \"{value}\""
};
// After
var startInfo = new ProcessStartInfo
{
FileName = "tool",
ArgumentList = { "-x", value }
};
E128142: Do not instantiate a Managed or CNG cryptography type
Flags a direct new of a type whose name ends in Managed or Cng. A concrete type fixes one implementation. The abstract factory lets the platform select its cryptographic module. A Cng constructor that takes a CngKey or a CngProvider is not reported, because the factory cannot open a persisted key. When no factory overload matches the constructor arguments, the message names the abstract base factory instead of an overload. Rijndael and RijndaelManaged are reported because AES does not allow their block sizes. Types that E128071 already blocks are skipped.
The code fix replaces the creation with the abstract factory call and keeps an int key-size or ECCurve argument. It declines a construction that flows into a concretely typed declaration, a field or property target, an argument pass-through to a concrete-typed parameter, and a creation that carries an object initializer. The rule still reports those declined shapes.
// Before (warns)
using var sha = new SHA256Managed();
// After
using var sha = SHA256.Create();
E128143: Use an RSA key of at least 3072 bits or an approved curve
Flags an RSA key below 3072 bits and an elliptic curve key below 384 bits. Approved curves are P-384 and P-521. A key size or a curve name that the rule cannot read at compile time is reported, including a key size created by name, imported from parameters, a handle, a blob, PEM text or a certificate, and a curve held by friendly name, object identifier, parameter reference or struct initializer. A factory or constructor without a curve argument uses the default P-256 curve and is reported.
// Before (warns)
using var rsa = RSA.Create(2048);
// After
using var rsa = RSA.Create(3072);
E128144: Use an authenticated cipher mode
Flags CipherMode.ECB, CipherMode.OFB and CipherMode.CFB, the EncryptEcb, DecryptEcb, EncryptCfb and DecryptCfb methods, and a constant cast such as (CipherMode)2, including a cast from another enum. ECB reveals plaintext structure. Use authenticated encryption such as AES-GCM. A comparison reads the mode and is not reported.
// Before (warns)
aes.Mode = CipherMode.ECB;
// After
using var gcm = new AesGcm(key, 16);
E128145: Use a strong PBKDF2 configuration
Flags a PBKDF2 iteration count below 600,000 and an overload that defaults to 1,000 iterations. It also flags SHA-1 as the PRF and an iteration count that the rule cannot read at compile time. An IterationCount assignment on the same object replaces the default-count report.
// Before (warns)
using var kdf = new Rfc2898DeriveBytes("pw", salt, 1000, HashAlgorithmName.SHA256);
// After
using var kdf = new Rfc2898DeriveBytes("pw", salt, 600_000, HashAlgorithmName.SHA256);
E128146: Use TLS 1.2 or later
Flags SslProtocols.Ssl2, Ssl3, Tls, Tls11 and Default, and the matching SecurityProtocolType members. It also flags a numeric cast that sets a weak protocol bit and a complement that enables every weak protocol. A comparison and a mask removal are not reported. AppContext.SetSwitch("Switch.System.Net.DontEnableSchUseStrongCrypto", true) is reported.
The code fix deletes the constant-true weak-TLS switch statement. It applies only to the two switch names the rule isolates. The literal and cast shapes stay manual, because the compliant protocol choice belongs to the caller.
// Before (warns)
var protocols = SslProtocols.Tls11;
// After
var protocols = SslProtocols.Tls12;
E128147: RNGCryptoServiceProvider is deprecated
Flags new RNGCryptoServiceProvider() where the target framework marks the type [Obsolete], as on .NET 6 and later. On .NET Framework and netstandard2.0 the type is supported and the rule stays silent.
Code fix replaces the parameterless constructor with RandomNumberGenerator.Create(). It declines a construction that flows into a concretely typed declaration, because Create() returns the base type.
// Before (warns)
using var rng = new RNGCryptoServiceProvider();
// After
var bytes = RandomNumberGenerator.GetBytes(32);
E128148: Do not use a cipher excluded by policy
Flags a type whose name contains a whole word from the excluded list: Blowfish, RC4, Arcfour, CAST5, CAST6, IDEA and Skipjack. Third-party libraries such as BouncyCastle expose these ciphers. IDEA is also an ordinary word, so it needs a cipher role word at the end of the type name, a cipher base type, a cipher interface or a cryptography namespace. IdeaEngine reports, and IdeaRankingAlgorithm does not.
The rule inspects a constructor, a static member in Create, HashData, TryHashData or HashDataAsync, and a method group. Types that E128071 already blocks are skipped, so one type produces one diagnostic.
// Before (warns)
var cipher = new BlowfishEngine();
// After
using var aes = Aes.Create();
E128149: Use the full 16-byte AES-GCM tag
Flags an AesGcm constructor whose tagSizeInBytes constant is below 16. It also flags an Encrypt or Decrypt call whose constant tag buffer is below 16 bytes. A tag size or buffer held in an unreassigned local or a readonly field resolves to its initializer.
The code fix replaces the tag size constant with 16, the API maximum. It also resizes a literal-sized tag buffer argument. It declines a computed size, because the buffer length must then be re-derived at the call sites.
// Before (warns)
using var aes = new AesGcm(key, 12);
// After
using var aes = new AesGcm(key, 16);
E128150: Do not use SHA-3, SHAKE or KMAC
Flags the SHA3_*, Shake*, HMACSHA3_* and Kmac* types, the OaepSHA3_* paddings, and a SHA-3 hash name stored in a variable. NIST SP 800-131A Rev. 2 accepts SHA-3. This rule is organizational policy, not a NIST statement. A read of IsSupported is not reported.
Code fix maps SHA3_*, HMACSHA3_*, and OaepSHA3_* to the same-size SHA-2 member. Shake* and Kmac* have no same-length counterpart, so they get no fix.
// Before (warns)
var hash = SHA3_256.HashData(data);
// After
var hash = SHA256.HashData(data);
E128151: Use an HMAC key at least as long as the hash output
Flags an HMAC key shorter than the hash output: 32 bytes for SHA-256, 48 for SHA-384 and 64 for SHA-512. The rule reads the constructor, the static HashData family, and a Key property assignment. A key whose length is not a compile-time constant is not reported.
// Before (warns)
using var hmac = new HMACSHA256(new byte[16]);
// After
using var hmac = new HMACSHA256(new byte[32]);
E128156: HttpClient certificate validation accepts every certificate
Flags a certificate validation callback that accepts every certificate. The rule reads three callback targets: HttpClientHandler.ServerCertificateCustomValidationCallback, SslClientAuthenticationOptions.RemoteCertificateValidationCallback (for example SocketsHttpHandler.SslOptions), and the userCertificateValidationCallback argument of the SslStream constructor. The rule reads three accepting shapes: an expression whose constant value is true (including x || true), the framework DangerousAcceptAnyServerCertificateValidator member, and a function that returns such an expression. The function may be a lambda, an anonymous method, or a method, local, or field that resolves to one. A callback that reads the certificate chain or the policy errors is not reported. This rule is an error, so the build fails.
Code fix removes the accepting callback assignment, or drops the SslStream callback argument. A setup that accepted a self-signed certificate fails on the next request, which is the purpose of the rule.
// Before (warns)
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
// After
var handler = new HttpClientHandler();
E128157: Fixed-time comparison of a secret-derived value
Flags SequenceEqual over a byte array or a span (the extension form and the static Enumerable and MemoryExtensions forms), and a string ==, !=, or Equals, when one side holds a secret. The equality operator on a span or a byte array compares address and length, not content, in constant time, so the rule does not report that shape. A value counts as a secret in three cases: the name ends with Mac, Hmac, Tag, or Signature in any case, the name holds one of those words as a segment, or an HMAC produced the value. An HMAC type call (including ComputeHash on an HMAC instance), the Hash property of an HMAC, an IncrementalHash.CreateHMAC result, and a hex or base64 encoding of such a value all count. Two string names that each hold token, digest, expected, computed, or hash also count, unless both hold only hash. A string comparison with a constant is not reported. A content hash comparison is not reported, because it is not a forgery check. The code fix handles SequenceEqual only and declines when an operand may be null.
// Before (warns)
return computedTag == expectedTag;
// After
return CryptographicOperations.FixedTimeEquals(computedTag, expectedTag);
E128164: Hardcoded absolute URL in source
Flags a string literal, or the text part of an interpolated string, that starts with http:// or https:// and carries a host. The project rules require a URL to come from an options class bound to configuration. The rule skips attribute arguments, the namespace and schema hosts w3.org, schemas.microsoft.com, schemas.openxmlformats.org, schemas.xmlsoap.org, and json-schema.org, and the reserved hosts example.com, example.org, and example.net. It also skips a property initializer on a type whose name ends in Options, and a const or static readonly string field: each declares one fixed value in one place, which is the shape the rule asks for. A local const inside a method is still reported, because it hides a value in a code path. An interpolated host such as $"https://{host}/items" is not reported. The rule is silent in a compilation that references xUnit, NUnit, or MSTest. No code fix.
// Before (warns)
var uri = new Uri("https://api.contoso.com/v1");
// After
var uri = options.Value.BaseAddress;
E128165: Hardcoded secret or connection string in source
Flags two shapes. The first is a string literal of 8 or more characters, with no whitespace, that is assigned to a name holding password, passwd, pwd, secret, apikey, accesskey, privatekey, connectionstring, token, credential, or bearer. The assignment can be a variable, a property initializer, an expression-bodied property, a property getter return, a plain assignment, an indexer key such as ["Password"], or a named argument. The rule looks through parentheses, ??, and ?:. It also reads u8 literals. A name that ends in Name, Header, Claim, Type, Prefix, Scheme, Path, Label, Format, Field, Param, Parameter, Setting, Pattern, Regex, Arn, Id, Count, Length, Expiry, or Hint names a lookup key and is not reported. A literal that looks like a header name (X-Api-Key, Some-Header) or a config path (Auth:Password) is not reported, and neither is a value of uppercase letters joined by underscores such as BRAVE_API_KEY, which names a setting rather than holding a credential. The second shape is a connection string literal of key=value pairs separated by ; that holds a Server, Data Source, or Host key and a Password or Pwd value. Space around = is allowed. A URL query string is not a connection string. An empty value or a {0} placeholder is not reported. The rule is silent in a compilation that references xUnit, NUnit, or MSTest. No code fix.
// Before (warns)
const string AdminPassword = "hunter2hunter2";
// After
var password = options.Value.AdminPassword;
E128166: Sensitive value passed to a logger call
Flags an ILogger call, through LoggerExtensions, ILogger.Log, or a [LoggerMessage] method, that passes a value named for a credential or personal-data word. The words are password, passwd, pwd, secret, apikey, accesskey, privatekey, connectionstring, token, ssn, creditcard, and cardnumber. The short words pwd and ssn match only as a whole word, so processNumber is not reported. The rule reads an identifier, the last segment of a member access or conditional access, and each hole of an interpolated message. It looks through a cast, parentheses, and a ToString() or Trim() call with no arguments. It reads the elements of the params object[] array. It skips the EventId, Exception, and message template arguments. A name that holds cancellation, or ends in Name, Type, Count, Length, Expiry, Header, Id, or Hint, is not reported. The rule is silent in a compilation that references xUnit, NUnit, or MSTest. No code fix.
// Before (warns)
logger.LogInformation("Login {Password}", password);
// After
logger.LogInformation("Login for {UserId}", userId);
E128167: Deferred-work comment with no work-item reference
Flags a // or /* */ comment that holds the word TODO, FIXME, or HACK in any case and carries no work-item reference. The word must stand alone, so hackathon is not reported. A reference counts when it matches the regex in the e128_tracked_ref_pattern option. The default pattern is #\d+, which accepts AB#123 and #123. An invalid pattern falls back to the default pattern. A match that exceeds the one-second timeout counts the text as tracked, so the rule stays silent. Sonar S1135 and S1134 report every marker, so keep them off when you turn this rule on. No code fix.
// Before (warns)
// TODO handle the empty case
// After
// TODO(AB#1234) handle the empty case
# .editorconfig
e128_tracked_ref_pattern = PROJ-\d+
E128168: Skipped test with no work-item reference in its reason
Flags an xUnit [Fact] or [Theory] whose Skip argument is a constant string that does not match e128_tracked_ref_pattern. An invalid pattern falls back to the default #\d+. A match that exceeds the one-second timeout counts the reason as tracked, so the rule stays silent. An empty reason is reported. A Skip value that is not a constant is not reported. No code fix.
// Before (warns)
[Fact(Skip = "flaky on CI")]
// After
[Fact(Skip = "AB#4521 flaky on CI")]
E128169: [Obsolete] with no message
Flags System.ObsoleteAttribute with no message argument, or with a null, empty, or whitespace message. The rule finds the message by position or by the name message, so [Obsolete(error: true, message: "")] is reported. Named arguments such as DiagnosticId do not count as a message. No code fix.
// Before (warns)
[Obsolete]
void Old() { }
// After
[Obsolete("Use New instead.")]
void Old() { }
E128184: Recursive delete outside a recognized safe root
Flags a recursive Directory.Delete or DirectoryInfo.Delete when the path is a parameter that no safe call site bounds, a field read, a property read, or a Path.Combine whose first argument is one of those. The severity is Info, because a false positive on a build gate blocks work for no gain.
A path under Path.GetTempPath(), a relative string literal, a const field, and a Path.GetFullPath over a safe value are recognized as safe. A local that holds one of those is also safe, and a local alias counts as the value it holds. A DirectoryInfo created over a safe path is safe too. A parameter of a private method is safe when every call site in the same type part passes a safe path, so a cleanup helper keeps the provenance of its caller. A rooted literal reports, for example "/etc/nginx" or "C:\Data", because the rule cannot prove the directory is disposable. A readonly field, a get-only property, and a mutable field report, because the value is computed at run time.
A guard counts only when it proves the test passed. The comparison must use StringComparison.Ordinal or OrdinalIgnoreCase, and the root must end at a separator boundary, so a prefix test cannot pass for a sibling directory. An enclosing if that holds the call alone or joined by && counts, and so does a preceding if with no else that exits when the call is false. The guard must be the statement before the delete. A write to the guarded symbol between the guard and the delete voids the guard. A negated test around the delete and an || condition do not count.
A Path.Combine under a temp path stays silent even when a later segment comes from a variable. The rule cannot see a .. or a rooted value in that segment. An unknown shape stays silent. No code fix.
// Before (reports)
Directory.Delete(root, recursive: true);
// After
var temp = Path.GetTempPath();
Directory.Delete(Path.Combine(temp, "build"), recursive: true);
E128191: PFX import without EphemeralKeySet
Flags an X509Certificate2 constructor that imports a PFX file, and an X509CertificateLoader.LoadPkcs12, LoadPkcs12FromFile, LoadPkcs12Collection, or LoadPkcs12CollectionFromFile call, when the flags omit X509KeyStorageFlags.EphemeralKeySet. Without the flag, the import persists the private key in the key store, and the key outlives the process. The flag is not supported for PFX loading on macOS. A flags constant that includes EphemeralKeySet and a non-constant flags value are skipped. A constructor that takes a byte array, and a constructor with no flags parameter, are skipped. No code fix.
// Before (warns)
using var certificate = new X509Certificate2(
path,
password,
X509KeyStorageFlags.MachineKeySet);
// After
using var certificate = new X509Certificate2(
path,
password,
X509KeyStorageFlags.EphemeralKeySet);
E128202: Unvalidated JWT Claims Used as an Identity
Reports decoded JWT claims that reach an authenticated identity in HttpContext.User or an AuthenticationTicket. Token readers (ReadJwtToken, ReadJsonWebToken, and ReadToken) and string token constructors decode without validation. The rule follows every decoded source through local claims, identity collections, conditional access, foreach, and lambda inputs. It tracks AddClaim, AddClaims, Add, AddRange, AddIdentity, and AddIdentities. An identity needs an authentication type that is not constant null or empty. Subclasses count too. Claim reads from a token (Subject, Claims, Payload, GetClaim, TryGetClaim, and other members) count. A pattern variable counts as a local, whether it comes from an is expression, a switch statement, or a switch expression.
A synchronous ValidateToken call clears the report only when it precedes the sink and validates the same unchanged token. ValidateTokenAsync needs an IsValid check, including its SecurityToken overload. The rule accepts a true branch, an else branch after a failed check, or a failed-check branch that returns or throws. A bare async validation call does not clear the report. A write to the token between the validation and its check removes the clearance. A field or auto-property token, such as request.Token, clears only when the same receiver reads it again. A write to the member or its receiver voids the clearance. The synchronous JsonWebTokenHandler.ValidateToken call returns a result object, so it needs an unchanged IsValid check like the async form. A ConfigureAwait call on the validation task is accepted. A synchronous validation inside a try block clears the report when every catch returns or throws. A goto or label in the block stops the scan. Lambdas inherit earlier parent validation. Local functions inherit only parent guards that contain their declaration.
A later local definition hides earlier definitions only when its block contains the use. Claims and identity additions count after the sink because the sink retains references. Compound assignment, deconstruction, and ref writes stop tracking the affected local after the write position. An out argument of a claim reader such as TryGetClaim defines the local instead. A ??= assignment and a lambda write to a parent local count as definitions. A claim collection that a later Add or AddRange call fills does not reach an identity that already copied it. A captured local that the parent redefines after a lambda or local function counts. A conditional or coalesce principal reports per branch. A definition later in a shared loop reaches the sink on the next iteration, unless a later definition in the same loop replaces it or the loop declares the local. A token read after the sink needs validation before that read. A token rewritten after the sink voids a validation that sits outside the loop. The rule skips a local function that no call or method group reaches from the method body. It does not follow helper-method flows. No code fix applies because validation needs application policy.
// Before (warns)
var parsed = handler.ReadJwtToken(token);
context.User = new ClaimsPrincipal(new ClaimsIdentity(parsed.Claims, "jwt"));
// After
context.User = handler.ValidateToken(token, parameters, out _);
E128222: Path.Combine of a root and a run-time leaf
Flags Path.Combine(root.FullName, leaf) when the leaf arrives at run time and no containment check consumes the join. A leaf from a caller can hold a separator, a parent reference, or a rooted prefix. The join then returns a path outside the root directory.
A constant leaf stays silent. An interpolated string whose holes are all numeric stays silent. A leaf from the namer family stays silent: GetFileName, GetFileNameWithoutExtension, GetRandomFileName, GetTempFileName, ChangeExtension, SanitizeFileName, and ToKebabCase.
A guard call silences the report only when it receives the join itself, or a local or field that the join reaches through an assignment. The guard family is IsInside, ValidateDomainPath, and ResolveInside. An unrelated guard call in the same method does not silence the report. E128161 covers a constant segment that is rooted or climbs. This rule covers the run-time leaf.
The code fix rewrites the one shape new FileInfo(Path.Combine(root.FullName, leaf)) to FilePathContainment.ResolveInside(root, leaf) and adds using Pug.Core;. It never calls Path.GetFileName on the leaf, because flattening a multi-segment leaf retargets the read or the delete. The fix stays absent when the target cannot resolve Pug.Core.FilePathContainment or when the join does not feed a FileInfo construction.
// Before (warns)
var file = new FileInfo(Path.Combine(root.FullName, callerName));
// After
var file = FilePathContainment.ResolveInside(root, callerName);
E128227: HTTP body read without a size bound
Flags an HttpContent.ReadAsStringAsync or HttpContent.ReadAsByteArrayAsync call that buffers the whole body with no cap. An untrusted server can answer with a body large enough to exhaust the heap.
The rule resolves the read and the bound by symbol, not by name. A bound must precede the read. A bound is a resolved HttpContent.LoadIntoBufferAsync call with the long cap overload, with or without a trailing CancellationToken, or a null-safe ContentLength comparison on the same content chain. A plain greater-than guard does not bound the read, because ContentLength is null for a chunked response and the guard passes through. A MaxResponseContentBufferSize setting does not bound a direct content read, because it caps the client buffer only. An in-memory content type (StringContent, ByteArrayContent, ReadOnlyMemoryContent, JsonContent) needs no bound, because its size is already known.
The code fix inserts await content.LoadIntoBufferAsync(cap); before the statement that reads the body. The cap comes from the e128_http_body_max_bytes option, which defaults to 134,217,728. An oversized body then throws instead of exhausting the heap. The fix declines a read outside an awaited context, an underivable receiver chain, a field initializer, and a read that already has a bound. It offers no fix-all.
// Before (warns)
var json = await response.Content.ReadAsStringAsync(cancellationToken);
// After option 1: cap the buffer load.
await response.Content.LoadIntoBufferAsync(MaxBodyBytes, cancellationToken);
var json = await response.Content.ReadAsStringAsync(cancellationToken);
// After option 2: fail closed when ContentLength is unknown.
if (response.Content.Headers.ContentLength is not > MaxBodyBytes)
{
throw new InvalidOperationException("Response body is too large.");
}
var json = await response.Content.ReadAsStringAsync(cancellationToken);
E128228: Token validation flag set to constant false
Flags a TokenValidationParameters flag assigned a literal false. Five flags default to true, so a literal false disables the check with no build warning and no runtime warning. The token handler then accepts a token that the caller believes it rejects.
ValidateIssuerSigningKey defaults to false. The rule reports that flag with a distinct message, because the assignment matches the default value.
The rule resolves the property symbol against TokenValidationParameters and reports only a literal false. A value read from configuration or a variable stays silent. The rule carries no code fix, because the safe value depends on the deployment.
// Before (warns)
var parameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
};
// After
var parameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
};
E128241: CORS wildcard with credentials
Flags one CorsPolicyBuilder chain that calls both AllowAnyOrigin and AllowCredentials, in either order. A browser rejects a credentialed request to a wildcard origin, so the policy cannot work as written. It also states an intent to trust every origin with credentials.
The rule resolves Microsoft.AspNetCore.Cors.Infrastructure.CorsPolicyBuilder, so it stays silent without an ASP.NET Core reference. It reports the chain once, at the AllowAnyOrigin call. The rule carries no code fix, because the remedy needs the allowed origin list.
// Before (warns)
builder.AllowAnyOrigin().AllowCredentials();
// After
builder.WithOrigins("https://example.test").AllowCredentials();
E128242: Antiforgery missing on a state-changing action
Flags an MVC action with [HttpPost], [HttpPut], [HttpPatch], or [HttpDelete] and no antiforgery validation on the method or its containing type.
[ValidateAntiForgeryToken] and [AutoValidateAntiforgeryToken] clear the report. [IgnoreAntiforgeryToken] is an explicit opt-out. A type marked [ApiController] stays silent, because a token-authenticated API is not a cookie CSRF surface. The fix adds [ValidateAntiForgeryToken] and the MVC using.
// Before (warns)
[HttpPost]
public void Save() { }
// After
[ValidateAntiForgeryToken]
[HttpPost]
public void Save() { }
E128256: Local filesystem path passed to a logger call
Flags FileInfo.FullName, DirectoryInfo.FullName, or Path.GetFullPath(...) passed to an ILogger call or a [LoggerMessage] argument. A log entry outlives the request, so a full path leaks the local directory layout.
The rule also flags a FileSystemInfo passed directly or in an interpolation hole, a FileSystemInfo.ToString() argument, and a local staged from a path, when the local is the argument itself. A path reduced by Path.GetFileName, Path.GetFileNameWithoutExtension, Path.GetRelativePath, or Path.GetExtension stays silent. It stays silent on an exception message, on a file name, on nameof, and on a transformed local such as Path.GetFileName(local). It does not follow a LoggerMessage.Define delegate.
The fix replaces .FullName with .Name only when the access is a direct argument of the logger call. A staged local offers no fix, because the local can feed other code. The Path.GetFullPath form offers no fix, because the replacement depends on the value.
E128263: Containment test compares a root with no directory separator
Flags string.StartsWith where the receiver is a resolved path and the root argument carries no trailing directory separator. A resolved receiver is a Path.GetFullPath(...) call, a FileSystemInfo.FullName, or a local initialized from either. Without the separator, a sibling whose name extends the root passes the test: /var/app/uploads_evil matches /var/app/uploads.
The rule reads only declarations in the same syntax tree as the test. A root that is declared in another file, or that another part of a partial type mentions by name, counts as unverified and reports. A caller trace covers private methods only.
The rule stays silent when the argument or an earlier assignment appends Path.DirectorySeparatorChar or Path.AltDirectorySeparatorChar, when the argument is a constant that ends with a separator, and when the receiver is not a resolved path. It also stays silent when a += assignment guarded by a separator test appends one, when a guarded conditional selects the bare root or the appended root, and when every caller of a local helper passes a safe root.
The fix wraps the root with Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar and adds using System.IO;. The fix is absent when the target framework has no Path.TrimEndingDirectorySeparator.
E128264: Overlapping alternatives in a repeated group
Flags a [GeneratedRegex] pattern whose quantified group has a top-level alternation where two branches can match the same first text, such as ^(a|ab)+$. Branches that are plain literals overlap only when one is a prefix of the other, so &|< stays silent. A leading anchor such as \b is skipped, and an optional leading atom also counts the atom after it. The engine then tries every split of the shared prefix. An atomic group (?>a|ab)+ stays silent, because it already prevents the split. No code fix: the safe branch order depends on the language the pattern accepts.
E128265: Non-constant regex pattern with no timeout
Flags a Regex constructor or a static Regex.Match, Matches, IsMatch, Count, EnumerateMatches, Replace, Split, or EnumerateSplits call when the pattern is not a constant, is not a Regex.Escape result, and is not a static readonly literal field, the call passes no TimeSpan, and the options carry no NonBacktracking. A constant pattern is owned by E128123 and MA0110, which force [GeneratedRegex]. No code fix, because the caller chooses between escaping, validation, and a timeout.
E128266: Certificate chain result ignored or policy weakened
Flags a bare X509Chain.Build(...) statement, a VerificationFlags value that sets AllowUnknownCertificateAuthority, IgnoreNotTimeValid, IgnoreWrongUsage, or IgnoreCtlNotTimeValid, and a RevocationMode.NoCheck assignment. The rule also flags an |= assignment, an object initializer, and any other nonzero VerificationFlags value. A Build result that feeds a branch or a return stays silent, and so does a later read of ChainStatus on the same chain.
The code fix replaces a constant weakening with X509VerificationFlags.NoFlag and deletes an |= statement. It offers no fix for the RevocationMode.NoCheck and discarded-Build shapes, because offline revocation checking and a handled failure branch can be intentional.
E128267: Decompression loop has no output bound
Flags a read loop over GZipStream, DeflateStream, BrotliStream, or ZLibStream that writes into a MemoryStream with no comparison against a length, a positive literal, or a named cap. A direct decompressionStream.CopyTo(memoryStream) call also reports, because it has no bound. A ThrowIfGreaterThan call counts as a bound when its first argument is a running total that the loop increments. A loop that checks memory.Length or a max/limit/cap/bound value stays silent. The rule reads a MemoryStream destination only; a ZipArchiveEntry stream and a file destination stay silent.
The code fix introduces a running total before the loop, adds the chunk count after each write, and throws with ArgumentOutOfRangeException.ThrowIfGreaterThan past the cap. The cap comes from the e128_decompression_max_output_bytes option, which defaults to 1,073,741,824. It offers no fix for the CopyTo shape, a write count that is not an identifier or a literal, and a write statement that is not in a statement list, such as the body of a braceless if. It offers no fix-all.
E128268: Symmetric key set from a text encoding
Flags a SymmetricAlgorithm.Key assignment, an object initializer, or a CreateEncryptor or CreateDecryptor key argument whose value comes from GetBytes(...) on any Encoding, directly or through a local. A text encoding carries the low entropy and the structure of the source text, with no salt and no work factor. A key from RandomNumberGenerator, Rfc2898DeriveBytes, or HKDF stays silent. No code fix.
E128272: Post-Quantum Migration Review
This opt-in rule reports RSA encryption, RSA and ECDSA signing, and ECDH key agreement calls. It suggests System.Security.Cryptography.MLKem for key encapsulation and System.Security.Cryptography.MLDsa for signatures. The rule reports at info and is disabled by default. To enable it, add this setting to your .editorconfig:
[*.cs]
dotnet_diagnostic.E128272.severity = suggestion
The rule reads Encrypt, TryEncrypt, SignData, TrySignData, SignHash, and TrySignHash. For ECDH, it reads DeriveKeyMaterial, DeriveKeyFromHash, DeriveKeyFromHmac, DeriveKeyTls, and DeriveRawSecretAgreement. The rule matches the framework method symbol, so an override reports and an unrelated method with the same name stays silent. A framework provider overload also reports, such as RSACryptoServiceProvider.Encrypt(byte[], bool). Verification, decryption, key import, key export, key creation, symmetric cryptography, and generated code stay silent.
The rule reports a family only when the compilation exposes a public GenerateKey factory on the suggested type. API presence does not prove runtime support. Check IsSupported before you use the built-in provider. The post-quantum platform matrix lists the provider requirements.
No code fix applies. ML-KEM encapsulates a shared secret. It does not encrypt application data as RSA does. A migration needs a protocol design, compatible peers, new keys, and a review of data formats and security policy. Check the experimental diagnostics for your .NET version. E128150 still allows provider-backed post-quantum calls, and this rule changes no FIPS policy rule.
// Reports when enabled
byte[] signature = ecdsa.SignData(data, HashAlgorithmName.SHA256);
// Review target after protocol and platform checks
using MLDsa key = MLDsa.GenerateKey(MLDsaAlgorithm.MLDsa65);
byte[] pqSignature = key.SignData(data);