1
+ final String xmlStr = "<users>" +
2
+ " <user name=\" aaa\" pass=\" pass1\" ></user>" +
3
+ " <user name=\" bbb\" pass=\" pass2\" ></user>" +
4
+ "</users>" ;
5
+ try {
6
+ DocumentBuilderFactory domFactory = DocumentBuilderFactory .newInstance ();
7
+ domFactory .setNamespaceAware (true );
8
+ DocumentBuilder builder = domFactory .newDocumentBuilder ();
9
+ //Document doc = builder.parse("user.xml");
10
+ Document doc = builder .parse (new InputSource (new StringReader (xmlStr )));
11
+
12
+ XPathFactory factory = XPathFactory .newInstance ();
13
+ XPath xpath = factory .newXPath ();
14
+
15
+ // Injectable data
16
+ String user = request .getParameter ("user" );
17
+ String pass = request .getParameter ("pass" );
18
+ if (user != null && pass != null ) {
19
+ boolean isExist = false ;
20
+
21
+ // Bad expression
22
+ String expression1 = "/users/user[@name='" + user + "' and @pass='" + pass + "']" ;
23
+ isExist = (boolean )xpath .evaluate (expression1 , doc , XPathConstants .BOOLEAN );
24
+ System .out .println (isExist );
25
+
26
+ // Bad expression
27
+ XPathExpression expression2 = xpath .compile ("/users/user[@name='" + user + "' and @pass='" + pass + "']" );
28
+ isExist = (boolean )expression2 .evaluate (doc , XPathConstants .BOOLEAN );
29
+ System .out .println (isExist );
30
+
31
+ // Bad expression
32
+ StringBuffer sb = new StringBuffer ("/users/user[@name=" );
33
+ sb .append (user );
34
+ sb .append ("' and @pass='" );
35
+ sb .append (pass );
36
+ sb .append ("']" );
37
+ String query = sb .toString ();
38
+ XPathExpression expression3 = xpath .compile (query );
39
+ isExist = (boolean )expression3 .evaluate (doc , XPathConstants .BOOLEAN );
40
+ System .out .println (isExist );
41
+
42
+ // Good expression
43
+ String expression4 = "/users/user[@name=$user and @pass=$pass]" ;
44
+ xpath .setXPathVariableResolver (v -> {
45
+ switch (v .getLocalPart ()) {
46
+ case "user" :
47
+ return user ;
48
+ case "pass" :
49
+ return pass ;
50
+ default :
51
+ throw new IllegalArgumentException ();
52
+ }
53
+ });
54
+ isExist = (boolean )xpath .evaluate (expression4 , doc , XPathConstants .BOOLEAN );
55
+ System .out .println (isExist );
56
+
57
+
58
+ // Bad Dom4j
59
+ org .dom4j .io .SAXReader reader = new org .dom4j .io .SAXReader ();
60
+ org .dom4j .Document document = reader .read (new InputSource (new StringReader (xmlStr )));
61
+ isExist = document .selectSingleNode ("/users/user[@name='" + user + "' and @pass='" + pass + "']" ).hasContent ();
62
+ // or document.selectNodes
63
+ System .out .println (isExist );
64
+ }
65
+ } catch (ParserConfigurationException e ) {
66
+
67
+ } catch (SAXException e ) {
68
+
69
+ } catch (XPathExpressionException e ) {
70
+
71
+ } catch (org .dom4j .DocumentException e ) {
72
+
73
+ }
0 commit comments