XML外部实体注入防护

XML文件的解析与XXE防护

DOM 

DOM的全称是Document Object Model,也即文档对象模型。在应用程序中,基于DOM的XML分析器将一个XML文档转换成一个对象模型的集合(通常称DOM树),应用程序正是通过对这个对象模型的操作,来实现对XML文档数据的操作。


import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException; // catching unsupported features

...

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    String FEATURE = null;

    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

      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

      // JDK7+ - http://xml.org/sax/features/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

      // JDK7+ - http://xml.org/sax/features/external-parameter-entities   

      FEATURE = "http://xml.org/sax/features/external-parameter-entities";

      dbf.setFeature(FEATURE, false);

      // Disable external DTDs as well

      FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";

      dbf.setFeature(FEATURE, false);

      // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"

      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());

            ...

        }

      DocumentBuilder safebuilder = dbf.newDocumentBuilder();


Note: The above defenses require Java 7 update 67, Java 8 update 20, or above, because the above countermeasures for DocumentBuilderFactory and SAXParserFactory are broken in earlier Java versions, per: CVE-2014-6517.

XMLInputFactory (a StAX parser)

StAX parsers such as XMLInputFactory allow various properties and features to be set.

To protect a Java XMLInputFactory from XXE, do this:

xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // This disables DTDs entirely for that factory

xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); // disable external entities

TransformerFactory

To protect a javax.xml.transform.TransformerFactory from XXE, do this:

TransformerFactory tf = TransformerFactory.newInstance();

tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");

tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

Validator

To protect a javax.xml.validation.Validator from XXE, do this:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");Schema schema = factory.newSchema();Validator validator = schema.newValidator();validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

SchemaFactory

To protect a javax.xml.validation.SchemaFactory from XXE, do this:

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");Schema schema = factory.newSchema(Source);

SAXTransformerFactory

To protect a javax.xml.transform.sax.SAXTransformerFactory from XXE, do this:

SAXTransformerFactory sf = SAXTransformerFactory.newInstance();

sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");

sf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

sf.newXMLFilter(Source);

Note: Use of the following XMLConstants requires JAXP 1.5, which was added to Java in 7u40 and Java 8:

javax.xml.XMLConstants.ACCESS_EXTERNAL_DTD

javax.xml.XMLConstants.ACCESS_EXTERNAL_SCHEMA

javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET

XMLReader

To protect a Java org.xml.sax.XMLReader from XXE, do this:

XMLReader reader = XMLReaderFactory.createXMLReader();reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // This may not be strictly required as DTDs shouldn't be allowed at all, per previous line.reader.setFeature("http://xml.org/sax/features/external-general-entities", false);reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

SAXReader

To protect a Java org.dom4j.io.SAXReader from XXE, do this:

saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false);saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

Based on testing, if you are missing one of these, you can still be vulnerable to an XXE attack.

SAXBuilder

To protect a Java org.jdom2.input.SAXBuilder from XXE, do this:

SAXBuilder builder = new SAXBuilder();builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);builder.setFeature("http://xml.org/sax/features/external-general-entities", false);builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);Document doc = builder.build(new File(fileName));


SAX 

SAX的全称是Simple APIs for XML,也即XML简单应用程序接口。与DOM不同,SAX提供的访问模式是一种顺序模式,这是一种快速读写XML数据的方式。当使用SAX分析器对XML文档进行分析时,会触发一系列事件,并激活相应的事件处理函数,应用程序通过这些事件处理函数实现对XML文档的访问,因而SAX接口也被称作事件驱动接口。

防护参考以上:


官网链接:

https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#JAXP_DocumentBuilderFactory.2C_SAXParserFactory_and_DOM4J

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容

  • 1、不安全的随机数生成,在CSRF TOKEN生成、password reset token生成等,会造成toke...
    nightmare丿阅读 3,680评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,633评论 18 139
  • mean to add the formatted="false" attribute?.[ 46% 47325/...
    ProZoom阅读 2,694评论 0 3
  • 那一天,我躺在暗红色的靠椅上,借着那有点昏暗的灯光,看master of love。J说这盏灯很值钱,不过我一点不...
    萝卜mama阅读 393评论 0 1
  • 一直心心念念又不敢尝试的独木舟之旅,终于在昨天日落时分实现,又是一个自我突破。我们一行五人,在距离小城开车一小时不...
    枫叶国的雪君阅读 390评论 0 0