JAVA.SV.XML.INVALID

XML is not validated before being unmarshalled to a Java object

XML Schema Definition (XSD) validation is crucial because it ensures that XML data adheres to a predefined structure and type constraints. The XSD is used to generate Java classes, and these classes can then be used to read XML data into Java objects, and to write Java objects to XML.

The JAVA.SV.XML.INVALID checker identifies potential XML injection vulnerabilities by checking that XML data is XDS-validated before being processed.

Vulnerability and risk

If a user-supplied XML file is directly used to unmarshal a Java object without any validation, the code is vulnerable to a potential XML injection attack. XML injection attack can lead to unauthorized data access, data corruption, denial of service, or even remote code execution. All of these conditions can severely compromise the security and integrity of your application and system.

Vulnerable code example 1

Copy
import jakarta.xml.bind.*;
import java.io.File;
 
public class Test {
    class Person {}
 
    public void test() {
        File xmlFile = new File("input.xml");
        try {
                JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
                Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                Object obj = jaxbUnmarshaller.unmarshal(xmlFile);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
      }
}

Klocwork reports a JAVA.SV.XML.INVALID defect on line 12, indicating, "XML directly used to unmarshal a Java object without any validation."

Fixed code example 1

Copy
import jakarta.xml.bind.*;
import javax.xml.XMLConstants;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
 
import java.io.File;
 
public class TestFixed {
    class Person {}
 
    public void test() {
        File xmlFile = new File("input.xml");
        try {
                 JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
 
                 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                 Schema schema = schemaFactory.newSchema(xsdFile);
 
                 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
                 jaxbUnmarshaller.setSchema(schema);
 
                Object obj = jaxbUnmarshaller.unmarshal(xmlFile);
            } catch (JAXBException e) {
                e.printStackTrace();
            }
    }
}

In this fixed example, Klocwork no longer reports a JAVA.SV.EMAIL.HOST defect because the Unmarshaller is configured with a schema that has a call to Unmarshaller::setSchema().

Security training

Application security training materials provided by Secure Code Warrior.