寫在前面
安全測試fortify掃描接口項目代碼,暴露出標題XXE的問題, 記錄一下。官網鏈接:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J
摘要
使用配置的 XML 解析器無法預防和限制外部實體進行解析,這會使解析器暴露在 XML External Entities 攻擊之下。
解釋
XML External Entities 攻擊可利用能夠在處理時動態構建文檔的 XML 功能。XML 實體可動態包含來自給定資源的數據。外部實體允許 XML 文檔包含來自外部 URI 的數據。除非另行配置,否則外部實體會迫使 XML 解析器訪問由 URI 指定的資源,例如位於本地計算機或遠程系統上的某個文件。這一行為會將應用程序暴露給XML External Entity (XXE) 攻擊,從而用於拒絕本地系統的服務,獲取對本地計算機上文件未經授權的訪問權限,掃描遠程計算機,並拒絕遠程系統的服務。 下面的 XML 文檔介紹了 XXE 攻擊的示例。
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo>
如果 XML 解析器嘗試使用 /dev/random 文件中的內容來替代實體,則此示例會使服務器(使用 UNIX 系統)崩潰。
建議
應對 XML 解析器進行安全配置,使它不允許將外部實體包含在傳入的 XML 文檔中。 為了避免 XXEinjections,應為 XML 代理、解析器或讀取器設置下面的屬性:
factory.setFeature("http://xml.org/sax/features/external-general-entities",false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities",false);
如果不需要 inline DOCTYPE 聲明,可使用以下屬性將其完全禁用:
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
要保護 TransformerFactory,應設置下列屬性:
TransformerFactory transFact = TransformerFactory.newInstance(); transFact.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); Transformer trans = transFact.newTransformer(xsltSource); trans.transform(xmlSource, result);
或者,也可以使用安全配置的 XMLReader 來設置轉換源:
XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-general-entities",false); reader.setFeature("http://xml.org/sax/features/external-parameter-entities",false); Source xmlSource = new SAXSource(reader, new InputSource(new FileInputStream(xmlFile))); Source xsltSource = new SAXSource(reader, new InputSource(new FileInputStream(xsltFile))); Result result = new StreamResult(System.out); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); trans.transform(xmlSource, result);
感謝
參考
-
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html (官網)
-
https://docs.microsoft.com/zh-cn/dotnet/api/javax.xml.xmlconstants.featuresecureprocessing?view=xamarin-android-sdk-9
-
https://saxonica.plan.io/issues/2414
-
https://stackoverflow.com/questions/18942307/warning-jaxp-feature-xmlconstants-feature-secure-processing-on-jersey2-x-client
-
https://bbs.csdn.net/topics/394382326 (XMLConstants.ACCESS_EXTERNAL_DTD的值)
-
https://docs.oracle.com/javase/7/docs/api/javax/xml/XMLConstants.html
-
https://stackoverflow.com/questions/25453042/how-to-disable-accessexternaldtd-and-entityexpansionlimit-warnings-with-logback
-
http://www.java2s.com/Code/Jar/j/Downloadjaxpapijar.htm (jaxp jar包)