Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: added reference to IDS17-J

...

The schema is available as the file schema.xsd. This compliant solution employs this schema to prevent XML injection from succeeding. It also relies on the CustomResolver class defined in IDS17-J. Prevent XML External Entity Attacks to prevent XML external entity (XXE attacks. This class, as well as XXE attacks, are described in the subsequent code examples) attacks.

Code Block
bgColor#ccccff
private void createXMLStream(BufferedOutputStream outStream,
                             String quantity) throws IOException {
  String xmlString;
  xmlString = "<item>\n<description>Widget</description>\n" +
              "<price>500.0</price>\n" +
              "<quantity>" + quantity + "</quantity></item>";
  InputSource xmlStream = new InputSource(
    new StringReader(xmlString)
  );

  // Build a validating SAX parser using our schema
  SchemaFactory sf
    = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
  DefaultHandler defHandler = new DefaultHandler() {
      public void warning(SAXParseException s)
        throws SAXParseException {throw s;}
      public void error(SAXParseException s)
        throws SAXParseException {throw s;}
      public void fatalError(SAXParseException s)
        throws SAXParseException {throw s;}
    };
  StreamSource ss = new StreamSource(new File("schema.xsd"));
  try {
    Schema schema = sf.newSchema(ss);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setSchema(schema);
    SAXParser saxParser = spf.newSAXParser();
    // To set the custom entity resolver,
    // an XML reader needs to be created
    XMLReader reader = saxParser.getXMLReader(); 
    reader.setEntityResolver(new CustomResolver());
    saxParser.parse(xmlStream, defHandler);
  } catch (ParserConfigurationException x) {
    throw new IOException("Unable to validate XML", x);
  } catch (SAXException x) {
    throw new IOException("Invalid quantity", x);
  }

  // Our XML is valid, proceed
  outStream.write(xmlString.getBytes());
  outStream.flush();
}

...