CA5369: Use XmlReader for Deserialize

Property Value
Rule ID CA5369
Title Use XmlReader for Deserialize
Category Security
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 No

Cause

Deserializing untrusted XML input with XmlSerializer.Deserialize instantiated without an XmlReader object can potentially lead to denial of service, information disclosure, and server-side request forgery attacks. These attacks are enabled by untrusted DTD and XML schema processing, which allows for the inclusion of XML bombs and malicious external entities in the XML. Only with XmlReader is it possible to disable DTD. Inline XML schema processing as XmlReader has the ProhibitDtd and ProcessInlineSchema property set to false by default in .NET Framework version 4.0 and later. The other options such as Stream, TextReader, and XmlSerializationReader cannot disable DTD processing.

Rule description

Processing untrusted DTD and XML schemas may enable loading dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled. This rule detects code that uses the XmlSerializer.Deserialize method and does not take XmlReader as a constructor parameter.

How to fix violations

Do not use XmlSerializer.Deserialize overloads other than Deserialize(XmlReader), Deserialize(XmlReader, String), Deserialize(XmlReader, XmlDeserializationEvents), or Deserialize(XmlReader, String, XmlDeserializationEvents).

When to suppress warnings

You can potentially suppress this warning if the parsed XML comes from a trusted source and hence cannot be tampered with.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA5369
// The code that's violating the rule is on this line.
#pragma warning restore CA5369

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA5369.severity = none

For more information, see How to suppress code analysis warnings.

Pseudo-code examples

Violation

The following pseudo-code sample illustrates the pattern detected by this rule. The type of the first parameter of XmlSerializer.Deserialize is not XmlReader or a derived class thereof.

using System.IO;
using System.Xml.Serialization;
...
new XmlSerializer(typeof(TestClass).Deserialize(new FileStream("filename", FileMode.Open));

Solution

using System.IO;
using System.Xml;
using System.Xml.Serialization;
...
new XmlSerializer(typeof(TestClass)).Deserialize(XmlReader.Create (new FileStream("filename", FileMode.Open)));