{"id":53354,"date":"2024-08-28T10:05:00","date_gmt":"2024-08-28T17:05:00","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/dotnet\/?p=53354"},"modified":"2024-12-13T13:59:04","modified_gmt":"2024-12-13T21:59:04","slug":"binaryformatter-removed-from-dotnet-9","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/binaryformatter-removed-from-dotnet-9\/","title":{"rendered":"BinaryFormatter removed from .NET 9"},"content":{"rendered":"<p>Starting with .NET 9, we no longer include an implementation of\n<code>BinaryFormatter<\/code> in the runtime (.NET Framework remains unchanged). The APIs\nare still present, but their implementation always throws an exception,\nregardless of project type. Hence, setting the existing backwards compatibility\nflag is no longer sufficient to use <code>BinaryFormatter<\/code>.<\/p>\n<p>In this blog post, I&#8217;ll explain why this change was made and what options you\nhave to move forward.<\/p>\n<h2>TL;DR: What should I do?<\/h2>\n<p>You have two options to address the removal of <code>BinaryFormatter<\/code>&#8216;s\nimplementation:<\/p>\n<ol>\n<li><strong>Migrate away from BinaryFormatter<\/strong>. We strongly recommend that you\ninvestigate options to stop using <code>BinaryFormatter<\/code> due to the associated\nsecurity risks. The <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/\">BinaryFormatter migration guide<\/a> lists\nseveral options.<\/li>\n<li><strong>Keep using BinaryFormatter<\/strong>. If you need to continue using\n<code>BinaryFormatter<\/code> in .NET 9, you need to depend on the unsupported\n<a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/compatibility-package\">System.Runtime.Serialization.Formatters<\/a> NuGet package,\nwhich restores the unsafe legacy functionality and replaces the throwing implementation.<\/li>\n<\/ol>\n<p><div class=\"alert alert-primary\"><p class=\"alert-divider\"><i class=\"fabric-icon fabric-icon--Info\"><\/i><strong>Note<\/strong><\/p>Please note that .NET Framework is unaffected by this change and continues to include an implementation of <code>BinaryFormatter<\/code>. However, we still strongly recommend to stop using <code>BinaryFormatter<\/code> from .NET Framework too, for the same reasons.<\/div><\/p>\n<h2>What&#8217;s the risk in using BinaryFormatter?<\/h2>\n<p>Any deserializer, binary or text, that allows its input to carry information\nabout the objects to be created is a security problem waiting to happen. There\nis a common weakness enumeration (CWE) that describes the issue: <a href=\"https:\/\/cwe.mitre.org\/data\/definitions\/502.html\">CWE-502\n&#8220;Deserialization of Untrusted Data&#8221;<\/a>. <code>BinaryFormatter<\/code>, included in the\nthe initial release of .NET Framework in 2002, is such a deserializer. We also\ncover this in the <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-security-guide\">BinaryFormatter security guide<\/a>.<\/p>\n<h2>Why we removed BinaryFormatter<\/h2>\n<p>We strongly believe that .NET should make it easy for customers to do the right\nthing and hard, if not impossible, to do the wrong thing. We generally refer to\nthis as the &#8220;pit of success&#8221;.<\/p>\n<p>Shipping a technology that is widely regarded as unsafe is counter to this goal.\nAt the same time, we also have a responsibility to ensure customers can support\nand move their existing code forward. We can&#8217;t just remove widely used\ncomponents from a .NET release, even when communicated long in advance. We also\nneed a migration plan and stop gap options.<\/p>\n<p>This removal was not a sudden change. Due to the known risks of using\n<code>BinaryFormatter<\/code>, we excluded it from .NET Core 1.0. But without a clear\nmigration path to using something safer, customer demand led to\n<code>BinaryFormatter<\/code> being included in .NET Core 2.0.<\/p>\n<p>Since then, we have been on the path to removing <code>BinaryFormatter<\/code>, slowly\nturning it off by default in multiple project types but letting consumers opt-in\nvia flags if still needed for backward compatibility:<\/p>\n<ul>\n<li><a href=\"https:\/\/github.com\/dotnet\/designs\/blob\/main\/accepted\/2020\/better-obsoletion\/binaryformatter-obsoletion.md\">2020: BinaryFormatter Obsoletion Plan<\/a><\/li>\n<li><a href=\"https:\/\/github.com\/dotnet\/announcements\/issues\/284\">2023: .NET 8 Update<\/a>: Implementation throws by default<\/li>\n<li><a href=\"https:\/\/github.com\/dotnet\/announcements\/issues\/293\">2024: .NET 9 Update<\/a>: Announced intention of removal early in the release cycle<\/li>\n<li><a href=\"https:\/\/github.com\/dotnet\/announcements\/issues\/317\">2024: .NET 9 Update<\/a>: Removal completed<\/li>\n<li><a href=\"https:\/\/learn.microsoft.com\/dotnet\/core\/compatibility\/serialization\/9.0\/binaryformatter-removal\">2024: .NET 9 Breaking Change<\/a>: In-box BinaryFormatter implementation removed and always throws<\/li>\n<\/ul>\n<p>In .NET 9 we removed all remaining in-box dependencies on <code>BinaryFormatter<\/code> and\nreplaced the implementation with one that always throws.<\/p>\n<h2>Options to move forward<\/h2>\n<p>New code should not take a dependency on <code>BinaryFormatter<\/code>. For existing code,\nyou should first investigate alternatives to <code>BinaryFormatter<\/code>. In case you\ndon&#8217;t control the serializer but only perform deserialization, you can consider\nonly reading the <code>BinaryFormatter<\/code> payload, without performing any\ndeserialization. And if none of this works for you can bring the implementation\nback by depending on an (unsupported) <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/compatibility-package\">compatibility package<\/a>.<\/p>\n<p>I&#8217;ll explore these options in more detail below.<\/p>\n<h3>Migrate-Away<\/h3>\n<p>You should first investigate whether you can replace <code>BinaryFormatter<\/code> with\nanother serializer. We have four recommendations:<\/p>\n<ul>\n<li><strong>Text-based<\/strong>. If a binary serialization format is not a requirement, you can\nconsider using JSON or XML serialization formats. These serializers are\nincluded in .NET and are supported by us.<\/p>\n<ul>\n<li><a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/migrate-to-system-text-json\">JSON using\u202fSystem.Text.Json<\/a><\/li>\n<li><a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/migrate-to-datacontractserializer\">XML using\u202fSystem.Runtime.Serialization.DataContractSerializer<\/a><\/li>\n<\/ul>\n<\/li>\n<li><strong>Binary<\/strong> If a compact binary representation is important for your scenarios,\nthe following serialization formats and open-source serializers are\nrecommended:<\/p>\n<ul>\n<li><a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/migrate-to-messagepack\">MessagePack\u202fusing\u202fMessagePack for C#<\/a><\/li>\n<li><a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/migrate-to-protobuf-net\">Protocol Buffers\u202fusing\u202fprotobuf-net<\/a><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Since <code>DataContractSerializer<\/code> honors the same attribute and interface as\n<code>BinaryFormatter<\/code> (namely <code>[Serializable]<\/code> and <code>ISerializable<\/code>), it&#8217;s probably\nthe easiest one to migrate to. If your migration goals include adopting a\nmodern and performant serializer or a format with better cross-platform\ninteroperability, the other options should be considered.<\/p>\n<h3>Read BinaryFormatter Payloads<\/h3>\n<p>If your code doesn&#8217;t control the serialization but only the deserialization,\nuse the new <a href=\"https:\/\/learn.microsoft.com\/dotnet\/api\/system.formats.nrbf.nrbfdecoder\"><code>NrbfDecoder<\/code><\/a> to <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/read-nrbf-payloads\">read BinaryFormatter\npayloads<\/a>. This allows you to read the encoded data without any\ndeserialization. It&#8217;s the equivalent of using a JSON\/XML reader without the\ndeserializer:<\/p>\n<pre><code class=\"language-C#\">using System.Formats.Nrbf;\r\n\r\nvoid Read(Stream payload)\r\n{\r\n    SerializationRecord rootObject = NrbfDecoder.Decode(payload);\r\n\r\n    if (rootObject is PrimitiveTypeRecord primitiveRecord)\r\n    {\r\n        Console.WriteLine($\"It was a primitive value: '{primitiveRecord.Value}'\");\r\n    }\r\n    else if (rootObject is ClassRecord classRecord)\r\n    {\r\n        Console.WriteLine($\"It was a class record of '{classRecord.TypeName.AssemblyQualifiedName}' type name.\");\r\n    }\r\n    else if (rootObject is SZArrayRecord&lt;byte&gt; arrayOfBytes)\r\n    {\r\n        Console.WriteLine($\"It was an array of `{arrayOfBytes.Length}`-many bytes.\");\r\n    }\r\n}<\/code><\/pre>\n<p>For more details, check out the <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/read-nrbf-payloads\">Nrbf documentation<\/a>.<\/p>\n<h3>BinaryFormatter compatibility package<\/h3>\n<p>If you have explored the options and determined you can&#8217;t migrate away from\n<code>BinaryFormatter<\/code>, you can also install the unsupported\n<a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/compatibility-package\">System.Runtime.Serialization.Formatters<\/a> NuGet package and set the\ncompatibility switch to true:<\/p>\n<pre><code class=\"language-XML\">&lt;PropertyGroup&gt;\r\n  &lt;TargetFramework&gt;net9.0&lt;\/TargetFramework&gt;\r\n  &lt;EnableUnsafeBinaryFormatterSerialization&gt;true&lt;\/EnableUnsafeBinaryFormatterSerialization&gt;\r\n&lt;\/PropertyGroup&gt;\r\n\r\n&lt;ItemGroup&gt;\r\n  &lt;PackageReference Include=\"System.Runtime.Serialization.Formatters\" Version=\"9.0.0\" \/&gt;\r\n&lt;\/ItemGroup&gt;<\/code><\/pre>\n<p>The package replaces the in-box implementation of <code>BinaryFormatter<\/code> with a\nfunctioning one, including its vulnerabilities and risks. It&#8217;s meant as a\nstopgap if you can&#8217;t wait with migrating to .NET 9 while not having replaced the\nusages of <code>BinaryFormatter<\/code> yet.<\/p>\n<p>Since the <code>BinaryFormatter<\/code> API still exists and this package only replaces the\nin-box implementation you only need to reference it from application projects.\nExisting code that is compiled against <code>BinaryFormatter<\/code> will continue to work.\n<div class=\"alert alert-danger\"><p class=\"alert-divider\"><i class=\"fabric-icon fabric-icon--ErrorBadge\"><\/i><strong>Caution<\/strong><\/p>The compatibility package is not supported and unsafe. We strongly recommend\nagainst taking a dependency on this package and to instead migrate away from\n<code>BinaryFormatter<\/code>.<\/div><\/p>\n<h2>Summary<\/h2>\n<p>Since the start of .NET Core we have been on a path of deprecating\n<code>BinaryFormatter<\/code>, due to <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-security-guide\">its security risks<\/a>.<\/p>\n<p>Starting with .NET 9, we no longer ship an implementation with the runtime. We\nrecommend that you <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/\">migrate away from BinaryFormatter<\/a>. If that\ndoesn&#8217;t work for you can either start <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/read-nrbf-payloads\">reading the binary payloads without\ndeserializing<\/a> or you can take a dependency on the <a href=\"https:\/\/learn.microsoft.com\/dotnet\/standard\/serialization\/binaryformatter-migration-guide\/compatibility-package\">unsupported\ncompatibility package<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Starting with .NET 9, we no longer include an implementation of BinaryFormatter in the runtime. This post covers what options you have to move forward.<\/p>\n","protected":false},"author":335,"featured_media":53355,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[685,326],"tags":[],"class_list":["post-53354","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dotnet","category-security"],"acf":[],"blog_post_summary":"<p>Starting with .NET 9, we no longer include an implementation of BinaryFormatter in the runtime. This post covers what options you have to move forward.<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/53354","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/335"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=53354"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/53354\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/53355"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=53354"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=53354"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=53354"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}