教育行业网站电商平台
如果用户有能力使用结构化XML 文档作为输入,那么他能够通过在数据字段中插入 XML 标签来 重写这个 XML 文档的内容。 XML 解析器会将这些标签按照正常标签进行解析。下面是一段在线商 店的 XML 代码,主要用于查询后台数据库。
<item)<description>Widget</description)<price)500.0</price><quantity>1</quantity)</item)
恶意用户可以在<quantity)元素中输入以下字符串:1</quantity)<price>1.0</price〉<quantity>1 会生成以下的 XML 文档:
<item)<description>Widget</description)<price)500.0</price><quantity)1</quantity)<price)1.0</price 〉<quantity)1</quantity)</item)
通过使用简单的API 解析器(org.xml.sax and javax.xml.parsers.SAXParser)可以解析该 XML 文 件,如果解析XML 的代码获取的是最后一个元素<price)的值,那么商品价格就被设置为1.0。
对于预防 XML 注入的情况,示例1给出了不规范用法(Java 语言)示例。示例2给出了规范用法 (Java 语言)示例。
示例1:public class OnlineStore {private static void createXMLStreamBad(final BufferedOutputStreamoutStream, final String quantity) throws IO- Exception {String xmlString ="<item 〉\n(description>Widget</description)\n"+"<price)500</price 〉\n"+"<quantity)"+ +"</quantity)</item)";outStream.write(xmlString.getBytes());outStream.flush();}}
上面的代码样例中,一个方法简单的使用了字符串拼接来创建一个 XML 查询,然后将其发送到服务器。在这时就有可能出现XML注入问题,因为这个方法没有进行任何输入验证。
当XML可能已经载入还未处理的输入数据时,一般情况下使用XML模板或者DTD验证 XML。如果还没有创建这样的XML字符串,那么应在创建 XML之前处理输入,这种方式性能较高。
示例2(输入验证):public class OnlineStore {private static void createXMLStream(final BufferedOutputStreamoutStream,final String quantity) throws IOException, NumberFormatException {// Write XML string only if quantity is an unsigned integer(count).int count = Integer.parseUnsignedInt(quantity);String xmlString ="<item 〉\n(description>Widget</description)\n"+"<price)500(/price 〉\n"+"〈quantity)"+ count+"</quantity)</item)";outStream.write(xmlString.getBytes());outStream.flush();}}
代码的解决方案是验证 quantity 是一个无符号整数。