# C# Security Apply these rules when implementing or reviewing security-sensitive .NET code. Load the shared security rule for each affected boundary (API, auth, web, data, files, network, crypto, supply chain, AI); this file adds only .NET specifics. * Use parameters with ADO.NET (`SqlParameter`) and EF Core (`FromSql` or `FromSqlInterpolated`, never concatenation into `FromSqlRaw` or `ExecuteSqlRaw`). Select dynamic identifiers and sort expressions from a fixed allowlist. * Resolve file paths with `Path.GetFullPath(Path.Combine(root, input))` and require the result to start with the root plus a trailing directory separator, using `StringComparison.OrdinalIgnoreCase` on Windows. Account for reparse points and symlinks when the attacker can affect directory contents. * For process execution, set `ProcessStartInfo.UseShellExecute = false` explicitly (its default is `true` on .NET Framework), start the executable by absolute path, and pass arguments through `ArgumentList` (.NET Core 2.1+). On .NET Framework, build `Arguments` with correct Windows argument escaping instead of ad-hoc quoting. Never pass untrusted arguments to `.bat` or `.cmd` targets, because `cmd.exe` re-parses them; validate each argument against an allowlist. * Deserialize into explicit DTOs or allowlisted types. Prefer `System.Text.Json` and allow polymorphism only through registered `[JsonDerivedType]` types. For untrusted data never use `BinaryFormatter` (it throws since .NET 9; do not restore it through the unsupported compatibility package), `NetDataContractSerializer`, `SoapFormatter`, `LosFormatter`, or Newtonsoft.Json `TypeNameHandling` other than `None`. Bound object-graph depth and size. * For regular expressions on untrusted input on .NET 7+, use `RegexOptions.NonBacktracking` when the pattern needs no backreferences or lookarounds; otherwise pass an explicit match timeout, because there is none by default. Declare regexes with `[GeneratedRegex]` on .NET 7+. * Use `RandomNumberGenerator` for security values and `CryptographicOperations.FixedTimeEquals` for comparing secrets. Never return `true` unconditionally from `ServerCertificateCustomValidationCallback` or `RemoteCertificateValidationCallback`. * Keep secrets in user secrets during development and in a secret store such as Azure Key Vault in deployed environments; use ASP.NET Core Data Protection for application-level protection of payloads. Never embed secrets in assemblies or client bundles. * Use Razor's automatic encoding and `System.Text.Encodings.Web` encoders; avoid `Html.Raw` and `MarkupString` with untrusted content.