{
  "slug": "secure-csharp",
  "topic": "Secure C# and .NET",
  "status": "published",
  "order": 37,
  "capability": "coding/csharp",
  "title": "C# and .NET: which APIs and defaults turn into vulnerabilities?",
  "short": "Move off .NET 8 and 9 before support ends on 10 November 2026, never let data pick the type it deserializes into, and require authentication by default.",
  "answer": "Move every app off .NET 8 and 9 to .NET 10.0.14 or later now, as both lose support on 10 November 2026[^support][^oob], and before your next release remove `BinaryFormatter` and set a fallback authorization policy. Judge everything else by whether outside data can pick a type, reach SQL, a command line, a path, a URL or raw HTML, or skip an authorization check.",
  "audience": "Developers and tech leads writing production C# on .NET and ASP.NET Core, including legacy .NET Framework code, and the security people who review it",
  "version": "1.1",
  "lastReviewed": "2026-11-05",
  "reviewEveryDays": 30,
  "blocks": [
    {
      "type": "ranked",
      "id": "first",
      "title": "If you only do five things",
      "navTitle": "Five things",
      "items": [
        {
          "title": "Move to .NET 10 and patch every month.",
          "text": ".NET 8 and 9 lose support on 10 November 2026; .NET 10 is supported until 14 November 2028[^support]. Run 10.0.14 or later[^oob] and patch within the patching sheet's deadlines."
        },
        {
          "title": "Deserialize only into types you name.",
          "text": "`BinaryFormatter` can't be made secure[^bfsec], and CISA listed four exploited SharePoint deserialization flaws in 2026[^kev]. Use System.Text.Json; keep Json.NET's `TypeNameHandling` at `None`[^owaspdeser]."
        },
        {
          "title": "Require login by default, then check each record.",
          "text": "The default fallback policy is `null`, so endpoints without authorization metadata are public[^authz]. Set it to `RequireAuthenticatedUser()`, then check records with `IAuthorizationService.AuthorizeAsync`[^owaspdotnet]."
        },
        {
          "title": "Keep input out of SQL, command lines and paths.",
          "text": "Use LINQ or `FromSql`, not `FromSqlRaw`[^efsql], and `ArgumentList` without a shell[^owaspcmd]. SQL injection, path traversal and command injection rank 2nd, 6th and 9th in the CWE Top 25[^cwe]."
        },
        {
          "title": "Turn on the security analyzers and package audit.",
          "text": "Only some rules run by default[^msbuild]: set `<AnalysisModeSecurity>All</AnalysisModeSecurity>`, and `<NuGetAuditMode>all</NuGetAuditMode>` below `net10.0`[^nugetaudit]."
        }
      ]
    },
    {
      "type": "steps",
      "id": "review",
      "title": "Review a C# pull request",
      "navTitle": "Review",
      "items": [
        {
          "title": "Where does outside data enter?",
          "text": "Find the controllers, minimal API handlers, Razor Pages, Blazor components, SignalR hubs and queue consumers it touches. Each should bind a request type, not an EF Core entity."
        },
        {
          "title": "Who may call it, on which record?",
          "text": "Ask why for every `[AllowAnonymous]`, `AllowAnonymous()`, `DisableAntiforgery()` and `[IgnoreAntiforgeryToken]`. Neither `[Authorize]` nor the fallback policy checks the record[^owaspdotnet]."
        },
        {
          "title": "Does input reach a type name, SQL, a process or a path?",
          "text": "Search for `TypeNameHandling`, `Type.GetType`, `FromSqlRaw`, `ExecuteSqlRaw`, `CommandText`, `Process.Start`, `Path.Combine` and `ExtractToFile`."
        },
        {
          "title": "Does it reach HTML or the network?",
          "text": "Check `Html.Raw`, `MarkupString`, `HttpClient` calls to URLs from input and every `ServerCertificateCustomValidationCallback`."
        },
        {
          "title": "Does it switch off the runtime's checks?",
          "text": "`unsafe` blocks, `Unsafe` and `MemoryMarshal` calls, `[DllImport]` and `[LibraryImport]` need a second reviewer and a test."
        }
      ]
    },
    {
      "type": "list",
      "id": "traps",
      "title": "C# and .NET traps and what to use instead",
      "navTitle": "Traps",
      "span": "full",
      "items": [
        "**`BinaryFormatter` and its relatives.** `SoapFormatter`, `NetDataContractSerializer`, `LosFormatter` and `ObjectStateFormatter` also let the payload pick the type[^bfsec]. .NET 9 and later throw on `BinaryFormatter`, but the `System.Runtime.Serialization.Formatters` package restores it, risks included. Read old payloads with the NRBF reader, which creates no types[^bfmig].",
        "**Json.NET `TypeNameHandling` other than `None`.** The JSON then names the type to create, and Newtonsoft says to vet it with a `SerializationBinder`[^newtonsoft]. Keep `None`, never give a serializer `Type.GetType(name)` with a name from data[^owaspdeser], and in System.Text.Json declare subtypes with `[JsonDerivedType]`.",
        "**Known `machineKey` values in ASP.NET Framework.** Microsoft found over 3,000 public keys usable for ViewState code injection[^mskeys], and CISA lists Sitecore's default keys as exploited[^kev]. Generate unique keys, rotate them and encrypt the `machineKey` section[^mskeys].",
        "**`FromSqlRaw($\"... {id}\")`.** `FromSqlRaw` and `ExecuteSqlRaw` paste interpolated values into the SQL; `FromSql` and `ExecuteSql` send each as a `DbParameter`[^efsql], and EF Core 10 warns on concatenation[^ef10]. Map column names from a fixed list[^owaspdotnet].",
        "**`Process.Start(\"cmd.exe\", \"/c ...\")`.** Start a fixed full path with `UseShellExecute = false`, not the .NET Framework default[^useshell], use `ArgumentList` on .NET, and never pass input to `cmd.exe`, `powershell.exe` or `sh -c`[^owaspcmd].",
        "**`Path.Combine(root, name)`.** A rooted `name` discards `root`, and Microsoft says to use `Path.Join` for user input[^pathcombine]. That still lets `..` climb out, so require `Path.GetFullPath()` of the result to start with the root plus a separator.",
        "**`HttpClient.GetAsync(url)` with a URL from input.** Server-side request forgery ranks 22nd in the CWE Top 25[^cwe]. Allowlist hosts, check the resolved address in `SocketsHttpHandler.ConnectCallback` and set `AllowAutoRedirect = false`.",
        "**`Html.Raw`, `HtmlString` and `MarkupString`.** They skip Razor's encoding[^owaspdotnet][^blazor], and cross-site scripting ranks 1st in the CWE Top 25[^cwe]. Sanitize user HTML with a maintained sanitizer."
      ]
    },
    {
      "type": "list",
      "id": "tools",
      "title": "Tools that catch it",
      "navTitle": "Tools",
      "items": [
        "**.NET analyzers.** Set `<AnalysisModeSecurity>All</AnalysisModeSecurity>`[^msbuild], then fix CA2300 to CA2330 (deserializers), CA2100 and CA3001 (SQL), CA3006 (processes) and CA5359 (certificates) first[^secrules].",
        "**BannedApiAnalyzers** flags every use of the APIs listed in `BannedSymbols.txt`[^banned].",
        "**NuGet Audit** runs on every restore: add NU1903 and NU1904 to `<WarningsAsErrors>`[^nugetaudit]. The supply-chain sheet covers the rest."
      ]
    },
    {
      "type": "list",
      "id": "changed",
      "title": "What changed in 2026",
      "navTitle": "What changed",
      "items": [
        "**.NET 8 and 9 reach end of support on 10 November**[^support], and .NET Framework 4.6.2 on 12 January 2027[^fwlife].",
        "**October's two .NET 10 releases fixed 46 CVEs,** including critical Kestrel request smuggling (CVE-2026-88092)[^net1013][^kestrel]. Two fixes were complete only in 10.0.14[^oob].",
        "**Data Protection let attackers forge auth cookies** in the NuGet package 10.0.0 to 10.0.6, mainly outside the shared framework on Linux and macOS (CVE-2026-40372). If you ran it exposed, rotate the key ring and tokens issued meanwhile[^dataprot]."
      ]
    },
    {
      "type": "list",
      "id": "skip",
      "title": "What you can skip",
      "items": [
        "**`SecureString`.** Microsoft advises against it for new code, and it isn't encrypted outside Windows[^securestring].",
        "**A `SerializationBinder` to tame `BinaryFormatter`.** It may not stop code execution, and Microsoft doesn't commit to patching bypasses[^bfsec]. Migrate.",
        "**In-process sandboxes.** Code Access Security and partial trust aren't supported security boundaries[^owaspdotnet]. Use a separate process or container."
      ]
    },
    {
      "type": "list",
      "id": "mistakes",
      "title": "Mistakes that cost the most",
      "navTitle": "Mistakes",
      "items": [
        "**Patching the host but not the app.** Self-contained apps stay vulnerable until recompiled and redeployed[^kestrel], and October's Blazor WebAssembly fix needed updated package references[^oob]. Rebuild container images too.",
        "**Unprotected Data Protection keys.** Default storage encrypts them only on Windows, and naming your own store turns that off[^dpkeys]. Add `ProtectKeysWithAzureKeyVault`.",
        "**Development settings in production.** Keep the `Development` environment and unencrypted User Secrets on developer machines[^owaspdotnet]."
      ]
    },
    {
      "type": "columns",
      "id": "by-size",
      "title": "What this looks like for your code",
      "navTitle": "By codebase",
      "span": "full",
      "columns": [
        {
          "title": "New project",
          "items": [
            "Start on .NET 10 with nullable checks, all security rules and warnings as errors.",
            "Set the fallback policy before the first endpoint.",
            "Reject unknown and duplicate JSON properties, as .NET 10's `JsonSerializerOptions.Strict` does, but keep your naming policy[^net10lib]."
          ]
        },
        {
          "title": "Existing codebase",
          "items": [
            "Leave .NET 8 and 9 now; move .NET Framework 4.6.2 to 4.8 or 4.8.1 before 12 January 2027[^fwlife].",
            "Set `<NuGetAuditMode>all</NuGetAuditMode>` in `Directory.Build.props`."
          ]
        },
        {
          "title": "High-assurance or regulated",
          "items": [
            "Require CodeQL's `security-extended` suite; private code needs paid Code Security[^codeqlcli].",
            "Turn on `CheckForOverflowUnderflow` where code computes sizes or money.",
            "Keep a Key Vault-protected key ring per app and rehearse revoking it[^dataprot]."
          ]
        }
      ]
    }
  ],
  "changes": [
    {
      "date": "2026-11-05",
      "version": "1.1",
      "text": "Reviewed for company readers: CodeQL on private code needs a paid GitHub Code Security license."
    },
    {
      "date": "2026-11-05",
      "version": "1.0",
      "text": "Published after a copy edit and a source-by-source fact check, which corrected the October CVE count and the Data Protection CVE's scope and narrowed 6 statements to what the sources say."
    },
    {
      "date": "2026-11-05",
      "version": "0.1",
      "text": "First draft, based on Microsoft's .NET docs and advisories, CISA's KEV catalog, OWASP cheat sheets and the 2025 CWE Top 25."
    }
  ],
  "sources": [
    {
      "id": "support",
      "title": ".NET and .NET Core Support Policy",
      "publisher": "Microsoft",
      "date": "updated 25 Oct 2026",
      "url": "https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core"
    },
    {
      "id": "fwlife",
      "title": "Microsoft .NET Framework lifecycle",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/lifecycle/products/microsoft-net-framework"
    },
    {
      "id": "net1013",
      "title": ".NET 10.0.13 release notes",
      "publisher": "Microsoft",
      "date": "13 Oct 2026",
      "url": "https://github.com/dotnet/core/blob/main/release-notes/10.0/10.0.13/10.0.13.md"
    },
    {
      "id": "oob",
      "title": ".NET October 2026 out-of-band security updates",
      "publisher": "Microsoft",
      "date": "25 Oct 2026",
      "url": "https://github.com/dotnet/announcements/issues/496"
    },
    {
      "id": "kestrel",
      "title": "Advisory CVE-2026-88092 (Kestrel)",
      "publisher": "Microsoft",
      "date": "13 Oct 2026",
      "url": "https://github.com/dotnet/announcements/issues/472"
    },
    {
      "id": "dataprot",
      "title": "Advisory CVE-2026-40372 (Data Protection)",
      "publisher": "Microsoft",
      "date": "21 Apr 2026",
      "url": "https://github.com/dotnet/announcements/issues/395"
    },
    {
      "id": "cwe",
      "title": "2025 CWE Top 25",
      "publisher": "MITRE CWE",
      "date": "Dec 2025",
      "url": "https://cwe.mitre.org/top25/archive/2025/2025_cwe_top25.html"
    },
    {
      "id": "kev",
      "title": "Known Exploited Vulnerabilities Catalog",
      "publisher": "CISA",
      "date": "checked 5 Nov 2026",
      "url": "https://www.cisa.gov/known-exploited-vulnerabilities-catalog"
    },
    {
      "id": "bfsec",
      "title": "BinaryFormatter security guide",
      "publisher": "Microsoft Learn",
      "date": "updated 8 Aug 2024",
      "url": "https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide"
    },
    {
      "id": "bfmig",
      "title": "BinaryFormatter migration guide",
      "publisher": "Microsoft Learn",
      "date": "updated 8 Aug 2024",
      "url": "https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-migration-guide/"
    },
    {
      "id": "newtonsoft",
      "title": "TypeNameHandling Enumeration",
      "publisher": "Json.NET docs",
      "date": "checked 5 Nov 2026",
      "url": "https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_TypeNameHandling.htm"
    },
    {
      "id": "owaspdeser",
      "title": "Deserialization Cheat Sheet",
      "publisher": "OWASP",
      "date": "checked 5 Nov 2026",
      "url": "https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html"
    },
    {
      "id": "mskeys",
      "title": "Code injection attacks using publicly disclosed ASP.NET machine keys",
      "publisher": "Microsoft Threat Intelligence",
      "date": "6 Feb 2025",
      "url": "https://www.microsoft.com/en-us/security/blog/2025/02/06/code-injection-attacks-using-publicly-disclosed-asp-net-machine-keys/"
    },
    {
      "id": "owaspdotnet",
      "title": "DotNet Security Cheat Sheet",
      "publisher": "OWASP",
      "date": "checked 5 Nov 2026",
      "url": "https://cheatsheetseries.owasp.org/cheatsheets/DotNet_Security_Cheat_Sheet.html"
    },
    {
      "id": "authz",
      "title": "Policy-based authorization",
      "publisher": "Microsoft Learn",
      "date": "updated 20 Sep 2026",
      "url": "https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies"
    },
    {
      "id": "efsql",
      "title": "SQL Queries",
      "publisher": "EF Core docs",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/ef/core/querying/sql-queries"
    },
    {
      "id": "ef10",
      "title": "What's New in EF Core 10",
      "publisher": "EF Core docs",
      "date": "2 Oct 2025",
      "url": "https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-10.0/whatsnew"
    },
    {
      "id": "owaspcmd",
      "title": "OS Command Injection Defense Cheat Sheet",
      "publisher": "OWASP",
      "date": "checked 5 Nov 2026",
      "url": "https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"
    },
    {
      "id": "useshell",
      "title": "ProcessStartInfo.UseShellExecute",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.useshellexecute"
    },
    {
      "id": "pathcombine",
      "title": "Path.Combine",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine"
    },
    {
      "id": "blazor",
      "title": "Razor components: raw HTML",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/aspnet/core/blazor/components/#raw-html"
    },
    {
      "id": "net10lib",
      "title": ".NET 10 libraries: what's new",
      "publisher": "Microsoft Learn",
      "date": "7 Nov 2025",
      "url": "https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-10/libraries"
    },
    {
      "id": "msbuild",
      "title": "MSBuild properties: code analysis",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/dotnet/core/project-sdk/msbuild-props#code-analysis-properties"
    },
    {
      "id": "secrules",
      "title": "Security rules (code analysis)",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/security-warnings"
    },
    {
      "id": "banned",
      "title": "BannedApiAnalyzers help",
      "publisher": ".NET on GitHub",
      "date": "checked 5 Nov 2026",
      "url": "https://github.com/dotnet/roslyn/blob/main/src/RoslynAnalyzers/Microsoft.CodeAnalysis.BannedApiAnalyzers/BannedApiAnalyzers.Help.md"
    },
    {
      "id": "nugetaudit",
      "title": "Auditing package dependencies",
      "publisher": "NuGet docs",
      "date": "updated 5 May 2026",
      "url": "https://learn.microsoft.com/en-us/nuget/concepts/auditing-packages"
    },
    {
      "id": "securestring",
      "title": "SecureString Class",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/dotnet/api/system.security.securestring"
    },
    {
      "id": "dpkeys",
      "title": "Data Protection key management and lifetime",
      "publisher": "Microsoft Learn",
      "date": "checked 5 Nov 2026",
      "url": "https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/default-settings"
    },
    {
      "id": "codeqlcli",
      "title": "CodeQL CLI",
      "publisher": "GitHub Docs",
      "date": "checked 5 Nov 2026",
      "url": "https://docs.github.com/en/code-security/concepts/code-scanning/codeql/codeql-cli"
    }
  ]
}