Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

XML injection

ID: cs/xml-injectionKind: path-problemSecurity severity: 8.8Severity: errorPrecision: highTags:   - security   - external/cwe/cwe-091Query suites:   - csharp-code-scanning.qls   - csharp-security-extended.qls   - csharp-security-and-quality.qls

Click to see the query in the CodeQL repository

The APIs provided by the .NET libraries for XML manipulation allow the insertion of “raw” text at a specified point in an XML document. If user input is passed to this API, it could allow a malicious user to add extra content that could corrupt or supersede existing content, or enable unintended additional functionality.

Recommendation

Avoid using theWriteRaw method onSystem.Xml.XmlWriter with user input. If possible, use the high-level APIs to write new XML elements to a document, as these automatically escape user content. If that is not possible, then user input should be escaped before being included in a string that will be used with theWriteRaw API.

Example

In this example, user input is provided describing the name of an employee to add to an XML document representing a set of names. TheWriteRaw API is used to write the new employee record to the XML file.

usingSystem;usingSystem.Security;usingSystem.Web;usingSystem.Xml;publicclassXMLInjectionHandler:IHttpHandler{publicvoidProcessRequest(HttpContextctx){stringemployeeName=ctx.Request.QueryString["employeeName"];using(XmlWriterwriter=XmlWriter.Create("employees.xml")){writer.WriteStartDocument();// BAD: Insert user input directly into XMLwriter.WriteRaw("<employee><name>"+employeeName+"</name></employee>");writer.WriteEndElement();writer.WriteEndDocument();}}}

However, if a malicious user were to provide the contentBobbyPages</name></employee><employee><name>Hacker1, they would be able to add an extra entry into the XML file.

The corrected version demonstrates two ways to avoid this issue. The first is to escape user input before passing it to theWriteRaw API, which prevents a malicious user from closing or opening XML tags. The second approach uses the high level XML API to add XML elements, which ensures the content is appropriately escaped.

usingSystem;usingSystem.Security;usingSystem.Web;usingSystem.Xml;publicclassXMLInjectionHandler:IHttpHandler{publicvoidProcessRequest(HttpContextctx){stringemployeeName=ctx.Request.QueryString["employeeName"];using(XmlWriterwriter=XmlWriter.Create("employees.xml")){writer.WriteStartDocument();// GOOD: Escape user input before inserting into stringwriter.WriteRaw("<employee><name>"+SecurityElement.Escape(employeeName)+"</name></employee>");// GOOD: Use standard API, which automatically encodes valueswriter.WriteStartElement("Employee");writer.WriteElementString("Name",employeeName);writer.WriteEndElement();writer.WriteEndElement();writer.WriteEndDocument();}}

References


[8]ページ先頭

©2009-2025 Movatter.jp