Home > Article > Backend Development > Detailed introduction to the sample code of XML injection in Web security
XML injection attack has the same principle as SQL injection. The attacker enters malicious code to perform functions beyond his own permissions. XML is a way of storing data. If data is directly input or output without escaping when modifying or querying, it will lead to XML injection vulnerabilities. Attackers can modify the XML data format and add new XML nodes, affecting the data processing process.
Attack
The following is an example of saving registered user information in XML format:
final String GUESTROLE = "guest_role"; ... //userdata是准备保存的xml数据,接收了name和email两个用户提交来的数据。 String userdata = "<USER role="+ GUESTROLE+ "><name>"+ request.getParameter("name")+ "</name><email>"+ request.getParameter("email")+ "</email></USER>"; //保存xml userDao.save(userdata);
As you can see, this code does not perform any filtering operations. After an ordinary user registers, such a data record will be generated:
<?xml version="1.0" encoding="UTF-8"?> <USER role="guest_role"> <name>user1 </name> <email>user1@a.com </email> </USER>
When the attacker enters his or her email, he can enter the following code:
user1@a.com</email></USER><USER role="admin_role"><name>lf</name><email>user2@a.com
After the end user registers, the data becomes:
<?xml version="1.0" encoding="UTF-8"?> <USER role="guest_role"> <name>user1 </name> <email>user1@a.com</email> </USER> <USER role="admin_role"> <name>lf</name> <email>user2@a.com </email> </USER>
You can see that there is an additional administrator lf with role="admin_role". achieve the purpose of attack.
Defense
As the old saying goes, where there is attack, there is defense. The principle of defense is actually very simple, which is to escape the key string:
& --> & < --> < > --> > " --> " ' --> '
Before saving and displaying the XML, just escape the data part alone:
String userdata = "<USER role="+ GUESTROLE+ "><name>"+ StringUtil.xmlencode(request.getParameter("name"))+ "</name><email>"+ StringUtil.xmlencode(rrequest.getParameter("email"))+ "</email></USER>";
This way That’s it.
The above is the detailed content of Detailed introduction to the sample code of XML injection in Web security. For more information, please follow other related articles on the PHP Chinese website!