github-actions[bot] 64f9977e49
Create rule S6399(C#): XML operations should not be vulnerable to injection attacks (#2860)
You can preview this rule
[here](https://sonarsource.github.io/rspec/#/rspec/S6399/csharp)
(updated a few minutes after each push).

## Review

A dedicated reviewer checked the rule description successfully for:

- [ ] logical errors and incorrect information
- [ ] information gaps and missing content
- [ ] text style and tone
- [ ] PR summary and labels follow [the
guidelines](https://github.com/SonarSource/rspec/#to-modify-an-existing-rule)

---------

Co-authored-by: daniel-teuchert-sonarsource <daniel-teuchert-sonarsource@users.noreply.github.com>
Co-authored-by: Daniel Teuchert <daniel.teuchert@sonarsource.com>
Co-authored-by: daniel-teuchert-sonarsource <141642369+daniel-teuchert-sonarsource@users.noreply.github.com>
Co-authored-by: Loris S. <91723853+loris-s-sonarsource@users.noreply.github.com>
2023-08-18 11:31:42 +02:00

76 lines
2.1 KiB
Plaintext

== How to fix it in Java SE
=== Code examples
include::../../common/fix/code-rationale.adoc[]
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String xml =
"""<user>
<username>"""+req.getParameter("username")+"""</username>
<role>user</role>
</user>""";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
builder.parse(new InputSource(new StringReader(xml))); // Noncompliant
} catch (ParserConfigurationException | SAXException e) {
resp.sendError(400);
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element user = doc.createElement("user");
doc.appendChild(user);
Element usernameElement = doc.createElement("username");
user.appendChild(usernameElement);
username_element.setTextContent(req.getParameter("username"));
Element role = doc.createElement("role");
user.appendChild(role);
role.setTextContent("user");
} catch (ParserConfigurationException e) {
resp.sendError(400);
}
}
----
=== How does this work?
include::../../common/fix/introduction.adoc[]
include::../../common/fix/object.adoc[]
The example compliant code takes advantage of the `javax.xml` and `org.w3c.dom`
libraries capabilities to programmatically build XML documents.
include::../../common/fix/casting.adoc[]