The entity “nbsp” was referenced, but not declared in liferay 6.2 - java

While downloading a file I am getting the error:
The entity “nbsp” was referenced, but not declared.
I am able to download the file but I am not able to preview the file.
Below is my snippet:
is = new ByteArrayInputStream(articleHtml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc = builder.parse(is, null);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(doc, null);
renderer.layout();
try {
renderer.createPDF(outputStream);
} catch (com.lowagie.text.DocumentException e) {
e.printStackTrace();
}
I have tried with replacing the with  . Please help me to solve this problem.

Have you tried declaring entity as error says?
<!DOCTYPE test [
<!ENTITY nbsp " ">
]>
<test>The Spanish word for "Spain" is "Espa a" Dagon his Name, Sea Monster</test>
Taken from The entity "nbsp" was referenced, but not declared

Related

how to fix 'Disable XML external entity (XXE) processing' vulnerabilities in java

I ran my java code against sonarqube and I got 'Disable XML external entity (XXE) processing' as vulnerability. I spend some time on google to resolve the issue. I have been trying alot of approach but nothing is working for me. I don't know what I'm missing
My Code:
final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
docFactory.setFeature(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
docFactory.setFeature(XMLInputFactory.SUPPORT_DTD, false);
docFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
docFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
docFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
final Document doc = docBuilder.parse(filepath);
I'm using java 1.8, Any help is appreciated. Thanks
I end up adding all of the following attributes in order to avoid Sonar complaining about this vulnerability:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//REDHAT
//https://www.blackhat.com/docs/us-15/materials/us-15-Wang-FileCry-The-New-Age-Of-XXE-java-wp.pdf
factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
//OWASP
//https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// Disable external DTDs as well
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Java 9+ solution:
For me changing DocumentBuilderFactory.newInstance() to DocumentBuilderFactory.newDefaultInstance() was enough to red rid of this warning.
It should be enough to just set this two properties:
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
I have fixed this issue by adding the below code snippet :
saxParserFactory = SAXParserFactory.newInstance();
saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
saxParserFactory.setXIncludeAware(false);

Java parse a xml with file drop

Having the filedrop already implemented in my code, I need to parse the xml file I drop in the main().
Main()
case "XML":
text.append("Processing file type XML: "+files[i].getCanonicalPath() + "\n" );
ReadXml read_xml = new ReadXml();
read_xml.read(files[i].getCanonicalPath(), text);
break;
ReadXml.java
public class ReadXml {
ProgramDocument programDocument = new ProgramDocument();
public void read(String FILE, javax.swing.JTextArea text ) {
try {
JAXBContext context = JAXBContext.newInstance(ProgramDocument.class);
Unmarshaller u = context.createUnmarshaller();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(FILE);
Object o = u.unmarshal( doc );
doc.getDocumentElement().normalize();
text.append("Account : " +doc.getElementsByTagName("Account").item(0));
}
catch(Exception e) {
text.append("XML file not parsed correctly.\n");
}
}
}
I am not able to print anything, and when I am, I see "NULL" or just empty row or some path#numbers
I am not a developer, I just need to try opening a xml a send contents to a DB, but this is too far already.
EDIT: added part of xml
<?xml version="1.0" encoding="UTF-8"?>
<ARRCD Version="48885" Release="38">
<Identification v="ORCOZIO"/>
<Version v="013"/>
<Account v="OCTO">
<Type v="MAJO"/>
<Date v="2016-05-14"/>
</AARCD>
There are no elements tagged "Account" in the element "Account".
What you want to read here are the Attributes of Account, not other elements.
Thus you should use eElement.getAttribute("v") if you want to read attribute v, not getElementsByTagName()

How to prevent XML Injection like XML Bomb and XXE attack

I am developing an android application with
android:minSdkVersion="14"
In this app in need to parse an xml.For that I am using a DOM parser like this
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = null;
Document doc = null;
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
But when the code is checked for security I got two security issues on line
dBuilder = dbFactory.newDocumentBuilder();, which are
1.XML Entity Expansion Injection (XML Bomb)
2.XML External Entity Injection (XXE attack)
After some researching I added the line
dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
But now I am getting an exception when this line is executed
javax.xml.parsers.ParserConfigurationException: http://javax.xml.XMLConstants/feature/secure-processing
Can anybody help me?
Did you try the following snippet from OWASP page?
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; // catching unsupported features
...
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
// Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(FEATURE, true);
// If you can't completely disable DTDs, then at least do the following:
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
FEATURE = "http://xml.org/sax/features/external-general-entities";
dbf.setFeature(FEATURE, false);
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
FEATURE = "http://xml.org/sax/features/external-parameter-entities";
dbf.setFeature(FEATURE, false);
// and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference below)
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
// And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
// ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
// (http://cwe.mitre.org/data/definitions/918.html) and denial
// of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."
// remaining parser logic
...
catch (ParserConfigurationException e) {
// This should catch a failed setFeature feature
logger.info("ParserConfigurationException was thrown. The feature '" +
FEATURE +
"' is probably not supported by your XML processor.");
...
}
catch (SAXException e) {
// On Apache, this should be thrown when disallowing DOCTYPE
logger.warning("A DOCTYPE was passed into the XML document");
...
}
catch (IOException e) {
// XXE that points to a file that doesn't exist
logger.error("IOException occurred, XXE may still possible: " + e.getMessage());
...
}
String jaxbContext = "com.fnf.dfbatch.jaxb";
JAXBContext jc = null;
Unmarshaller u = null;
String FEATURE_GENERAL_ENTITIES = "http://xml.org/sax/features/external-general-entities";
String FEATURE_PARAMETER_ENTITIES = "http://xml.org/sax/features/external-parameter-entities";
try {
jc = JAXBContext.newInstance(jaxbContext);
u = jc.createUnmarshaller();
/*jobsDef = (BatchJobs) u.unmarshal(DfBatchDriver.class
.getClassLoader().getResourceAsStream(
DfJobManager.configFile));*/
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature(FEATURE_GENERAL_ENTITIES, false);
dbf.setFeature(FEATURE_PARAMETER_ENTITIES, false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(DfBatchDriver.class
.getClassLoader().getResourceAsStream(
DfJobManager.configFile));
jobsDef = (BatchJobs) u.unmarshal(document);

Can't seem to parse a xml file in android without getting a saxparser unexpected token error

I've been fighting trying to parse a basic xml file in a little test android app.
The code I have is the following:
InputStream is = getResources().openRawResource(R.xml.content);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is,"UTF-8"); //Blows up right here.
// Bunch more stuff here
}
My xml looks like the following:
<?xml version="1.0" ?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
The problem is that when I try to parse this I get an org.xml.sax.SAXParseException: Unexpected token (position:TEXT unprintable characters here ...#3:252 in java.io.InputStreamReader#411f3898) error.
I googled around and all the other solutions I found don't seem to work.
I double checked that the file is UTF-8, and changed it's encoding back and forth between UTF-16 and UTF-8 (tried both with and without BOM) with notepad++, and updated the program to properly reflect this, but no matter what I do, I always get this error. I'm sure I must just be missing something very obvious, but no matter what series of combinations I try this always fails.
First put your content.xml file in res/raw folder then parse it as:
Your xml file res/raw/content.xml :
<?xml version="1.0" encoding="utf-8"?>
<main>
<background>
<defintion>This is a test</defintion>
</background>
</main>
and parse it as:
InputStream is = getResources().openRawResource(R.raw.content);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
try {
dBuilder = dbFactory.newDocumentBuilder();
try {
Document doc = dBuilder.parse(is,"UTF-8");
NodeList nl = doc.getElementsByTagName("main");
System.out.println("NodeList NodeList"+nl.getLength());
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //Blows up right here.
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I've encountered the same problem as yours. I finally found the solution:
Never put your xml in res/xml. The xml file will be encoded by android sdk, thus can't be read correctly. However, when you put it in res/raw, the xml file exported to the app will be intact.

validation a xml with several xsd schema DOM java

After search on internet and in differnets forums, have not found my answer.
I have a XML file which is define by two XSD schema.
For write the XML file, there are two ways to write the XML file :
(I have to delete the "<" charactere to display the XML file)
First methode to write it :
?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Policy xmlns="http://www.W3C.com/Policy/v3#" xmlns:ns2="http://www.W3C.com /PolicyExtension/v3#">
DigestAlg Algorithm="http://test"/>
Transforms>
Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"></Transform>
/Transforms>
ns2:Validation>
ns2:ConditionID>1.0.1</ns2:ConditionID>
ns2:TConditionID>1.0.2</ns2:TConditionID>
/ns2:Validation>
/Policy>"
second methodes :
?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Policy xmlns="http://www.W3C.com/Policy/v3#">
DigestAlg Algorithm="http://test"/>
Transforms>
Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n20010315"></Transform>
/Transforms>
Validation xmlns:ns2="http://www.W3C.com/PolicyExtension/v3#">
ConditionID>1.0.1</ns2:ConditionID>
TConditionID>1.0.2</ns2:TConditionID>
/Validation>
/Policy>
For pasring my XML files, i use :
InputStream doc = new FileInputStream(myXMLFile);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
List<Source> sourceListSchema = new ArrayList<Source>();
sourceListSchema.add(new StreamSource(SignaturePolicy.class.getResourceAsStream(MY_XSD_SCHEMA_1)));
sourceListSchema.add(new StreamSource(SignaturePolicy.class.getResourceAsStream(MY_XSD_SCHEMA_2)));
Schema schema;
try {
Source[] sourceTmp = new Source[1];
schema = sf.newSchema(sourceListSchema.toArray(sourceTmp));
} catch (SAXException e) {
LogMachine.logger.severe(
"SAXException : The schema can not be parse :"+e.getMessage());
}
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringComments(true);
dbf.setSchema(schema);
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
documentPolicy = db.parse(Doc);
} catch (ParserConfigurationException e) {
LogMachine.logger.severe(
"ParserConfigurationException : the file can not be parse by DOM :"+e.getMessage());
} catch (SAXException e) {
LogMachine.logger.severe(
"SAXException : the file can not be parse by DOM :"+e.getMessage());
} catch (IOException e) {
LogMachine.logger.severe(
"IOException : the file can not be open like a file :"+e.getMessage());
}
When I want to parse this documents with DOM, the first XML file display an error
Exception in thread "main" org.w3c.dom.ls.LSException: The prefix "ns2" for element "ns2:Validation" is not bound.
But the second XML file is well parse.
Someone can help me to parse the two documents ??
Thank you for you help

Categories

Resources