├── .gitignore
├── LICENSE
├── README.md
├── img
├── 001.png
└── 002.png
├── pom.xml
└── src
└── main
├── java
└── com
│ └── emyiqing
│ ├── Main.java
│ ├── core
│ ├── sqli
│ │ └── JdbcSqlInject.java
│ └── xss
│ │ ├── AdvancedServletXss.java
│ │ └── SimpleServletXss.java
│ ├── dto
│ └── Result.java
│ ├── input
│ ├── Command.java
│ ├── FilePathExist.java
│ └── Logo.java
│ ├── parser
│ └── ParseUtil.java
│ └── util
│ └── FileUtil.java
└── resources
└── log4j.properties
/.gitignore:
--------------------------------------------------------------------------------
1 | # Operating System Files
2 |
3 | *.DS_Store
4 | Thumbs.db
5 | *.sw?
6 | .#*
7 | *#
8 | *~
9 | *.sublime-*
10 |
11 | # Build Artifacts
12 |
13 | .gradle/
14 | build/
15 | target/
16 | bin/
17 | dependency-reduced-pom.xml
18 |
19 | # Eclipse Project Files
20 |
21 | .classpath
22 | .project
23 | .settings/
24 |
25 | # IntelliJ IDEA Files
26 |
27 | *.iml
28 | *.ipr
29 | *.iws
30 | *.idea
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # XVulnFinder
2 |
3 | # 介绍
4 |
5 | 静态Java代码安全审计工具(开发中)
6 |
7 | 语法分析基于:https://github.com/javaparser/javaparser
8 |
9 | 暂时只写了个开头,能对单个文件的基础Servlet XSS和JDBC SQL注入进行分析
10 |
11 | # 案例
12 |
13 | ## XSS
14 |
15 | 对`XssServlet1.java`文件的分析:`java -jar xxx.jar -f XssServlet1.java`
16 |
17 | 
18 |
19 | ```java
20 | package testcode.xss.servlets;
21 |
22 | import java.io.IOException;
23 | import javax.servlet.ServletException;
24 | import javax.servlet.http.HttpServlet;
25 | import javax.servlet.http.HttpServletRequest;
26 | import javax.servlet.http.HttpServletResponse;
27 | import org.apache.commons.lang.StringEscapeUtils;
28 | import org.owasp.esapi.ESAPI;
29 |
30 | public class XssServlet1 extends HttpServlet {
31 |
32 | @Override
33 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
34 | String input1 = req.getParameter("input1");
35 |
36 | resp.getWriter().write(input1);
37 |
38 | resp.getWriter().write(ESAPI.encoder().encodeForHTML(input1));
39 | resp.getWriter().write(StringEscapeUtils.escapeHtml(input1));
40 |
41 | resp.getOutputStream().print(input1);
42 | resp.getOutputStream().println(input1);
43 | }
44 | }
45 |
46 | ```
47 |
48 | ## SQLi
49 |
50 | 对`Jdbc.java`文件的分析:`java -jar xxx.jar -f Jdbc.java`
51 |
52 | 
53 |
54 | ```java
55 | package testcode.sqli;
56 |
57 | import java.sql.Connection;
58 | import java.sql.ResultSet;
59 | import java.sql.SQLException;
60 | import java.sql.Statement;
61 |
62 | public class Jdbc {
63 |
64 | Connection con;
65 |
66 | public void query1(String input) throws SQLException {
67 | Statement stmt = con.createStatement();
68 | ResultSet rs = stmt.executeQuery("select * from Users where name = '" + input + "'");
69 | }
70 |
71 | }
72 | ```
73 |
--------------------------------------------------------------------------------
/img/001.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/j5s/XVulnFinder/5c56b35bf3f38a8255aaa7717682b470153f9f81/img/001.png
--------------------------------------------------------------------------------
/img/002.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/j5s/XVulnFinder/5c56b35bf3f38a8255aaa7717682b470153f9f81/img/002.png
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | org.example
8 | XVulnFinder
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 8
13 | 8
14 |
15 |
16 |
17 |
18 | log4j
19 | log4j
20 | 1.2.17
21 |
22 |
23 |
24 |
25 | com.beust
26 | jcommander
27 | 1.81
28 |
29 |
30 |
31 | com.github.javaparser
32 | javaparser-symbol-solver-core
33 | 3.23.0
34 |
35 |
36 |
37 |
38 |
39 |
40 | maven-assembly-plugin
41 |
42 | false
43 |
44 | jar-with-dependencies
45 |
46 |
47 |
48 | com.emyiqing.Main
49 |
50 |
51 |
52 |
53 |
54 | make-assembly
55 | package
56 |
57 | assembly
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/Main.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing;
2 |
3 | import com.beust.jcommander.JCommander;
4 | import com.emyiqing.core.sqli.JdbcSqlInject;
5 | import com.emyiqing.core.xss.SimpleServletXss;
6 | import com.emyiqing.dto.Result;
7 | import com.emyiqing.input.Command;
8 | import com.emyiqing.input.Logo;
9 | import com.emyiqing.util.FileUtil;
10 | import com.github.javaparser.StaticJavaParser;
11 | import com.github.javaparser.ast.CompilationUnit;
12 | import org.apache.log4j.Logger;
13 |
14 | import java.io.IOException;
15 | import java.util.List;
16 | import java.util.concurrent.ExecutionException;
17 | import java.util.concurrent.ExecutorService;
18 | import java.util.concurrent.Executors;
19 | import java.util.concurrent.Future;
20 |
21 | public class Main {
22 | static Logger logger = Logger.getLogger(Main.class);
23 |
24 | public static void main(String[] args) {
25 | Logo.PrintLogo();
26 | Command command = new Command();
27 | JCommander jc = JCommander.newBuilder().addObject(command).build();
28 | jc.parse(args);
29 | if (command.help) {
30 | jc.usage();
31 | }
32 | String code;
33 | try {
34 | code = FileUtil.readFile(command.filename);
35 | } catch (IOException e) {
36 | logger.error("read code error");
37 | return;
38 | }
39 |
40 | CompilationUnit compilationUnit = StaticJavaParser.parse(code);
41 |
42 | ExecutorService executor = Executors.newFixedThreadPool(5);
43 | Future> simpleServletXssTask = executor.submit(() -> SimpleServletXss.check(compilationUnit));
44 | Future> jdbcSqlInjectTask = executor.submit(() -> JdbcSqlInject.check(compilationUnit));
45 |
46 | List result;
47 | try {
48 | result = simpleServletXssTask.get();
49 | printResult(result);
50 |
51 | result = jdbcSqlInjectTask.get();
52 | printResult(result);
53 | executor.shutdown();
54 | } catch (InterruptedException | ExecutionException e) {
55 | e.printStackTrace();
56 | }
57 | }
58 |
59 | private static void printResult(List result) {
60 | result.stream().filter(Result::isSuccess).forEach(r -> {
61 | String format = String.format("class: %s method %s keyword: %s",
62 | r.getClassName(), r.getMethodName(), r.getKeyword());
63 | logger.info(format);
64 | });
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/core/sqli/JdbcSqlInject.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.core.sqli;
2 |
3 | import com.emyiqing.dto.Result;
4 | import com.emyiqing.parser.ParseUtil;
5 | import com.github.javaparser.ast.CompilationUnit;
6 | import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
7 | import com.github.javaparser.ast.body.FieldDeclaration;
8 | import com.github.javaparser.ast.expr.BinaryExpr;
9 | import com.github.javaparser.ast.expr.MethodCallExpr;
10 | import com.github.javaparser.ast.expr.VariableDeclarationExpr;
11 | import org.apache.log4j.Logger;
12 |
13 | import java.util.*;
14 |
15 | @SuppressWarnings("all")
16 | public class JdbcSqlInject {
17 | // todo: 添加新规则
18 | private static Logger logger = Logger.getLogger(JdbcSqlInject.class);
19 |
20 | private static final String STATEMENT_IMPORT = "java.sql.Statement";
21 |
22 | public static List check(CompilationUnit compilationUnit) {
23 | List results = new ArrayList<>();
24 | // 是否导入servlet依赖
25 | boolean imported = ParseUtil.isImported(compilationUnit, STATEMENT_IMPORT);
26 | if (!imported) {
27 | logger.warn("no jdbc sql inject");
28 | return results;
29 | }
30 |
31 | compilationUnit.findAll(ClassOrInterfaceDeclaration.class).stream()
32 | // 接口和抽象类不考虑
33 | .filter(c -> !c.isInterface() && !c.isAbstract()).forEach(c -> {
34 | Map globalVar = new HashMap<>();
35 | c.findAll(FieldDeclaration.class).forEach(f -> {
36 | // 全局变量中是否包含Connection(这是常见操作)
37 | if (f.getVariables().get(0).getType().asString().equals("Connection")) {
38 | globalVar.put("Connection", f.getVariables().get(0).getNameAsString());
39 | }
40 | });
41 | // 遍历方法,不考虑main方法
42 | c.getMethods().stream().filter(m -> !m.getName().asString().equals("main")).forEach(m -> {
43 | Map methodVar = new HashMap<>();
44 | Map paramVar = new HashMap<>();
45 | m.getParameters().forEach(p -> {
46 | paramVar.put(p.getType().asString(), p.getName().asString());
47 | });
48 | // 遍历方法中的赋值语句
49 | m.findAll(VariableDeclarationExpr.class).forEach(v -> {
50 | String left = v.getVariables().get(0).getNameAsString();
51 | MethodCallExpr next;
52 | if (v.getVariables().get(0).getInitializer().get() instanceof MethodCallExpr) {
53 | next = (MethodCallExpr) v.getVariables().get(0).getInitializer().get();
54 | } else {
55 | return;
56 | }
57 | String right = v.getVariables().get(0).getInitializer().get().toString();
58 | if (v.getVariables().get(0).getType().asString().equals("Statement")) {
59 | methodVar.put("Statement", v.getVariables().get(0).getNameAsString());
60 | }
61 | if (next.getScope().get().toString().equals(globalVar.get("Connection"))) {
62 | if (next.getName().asString().equals("createStatement")) {
63 | logger.debug("call createStatement method");
64 | }
65 | if (next.getName().asString().equals("prepareStatement")) {
66 | logger.debug("call prepareStatement method");
67 | return;
68 | }
69 | }
70 | // stat.executeQuery("SELECT ..." + param)
71 | if (next.getScope().get().toString().equals(methodVar.get("Statement"))) {
72 | if (next.getName().asString().equals("executeQuery")) {
73 | logger.debug("call executeQuery method");
74 | next.findAll(BinaryExpr.class).forEach(b -> {
75 | String sql = b.getLeft().toString();
76 | if (!sql.toUpperCase(Locale.ROOT).contains("SELECT")) {
77 | return;
78 | }
79 | if (!b.getOperator().asString().equals("+")) {
80 | return;
81 | }
82 | // 存在SQL语句拼接
83 | if (b.getLeft() instanceof BinaryExpr) {
84 | BinaryExpr sqlLeft = (BinaryExpr) b.getLeft();
85 | String sqlRight = sqlLeft.getRight().toString();
86 | // 输入是否可控
87 | if (!paramVar.containsValue(sqlRight)) {
88 | return;
89 | }
90 | logger.debug("find jdbc sql inject");
91 | Result result = new Result();
92 | result.setSuccess(true);
93 | result.setClassName(c.getNameAsString());
94 | result.setMethodName(m.getNameAsString());
95 | String keyword = String.format("%s.%s",
96 | next.getScope().get().toString(),
97 | next.getName().asString());
98 | result.setKeyword(keyword);
99 | results.add(result);
100 | }
101 | });
102 | }
103 | }
104 | });
105 | });
106 | });
107 | return results;
108 | }
109 | }
110 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/core/xss/AdvancedServletXss.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.core.xss;
2 |
3 | @SuppressWarnings("all")
4 | public class AdvancedServletXss {
5 | }
6 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/core/xss/SimpleServletXss.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.core.xss;
2 |
3 | import com.emyiqing.dto.Result;
4 | import com.emyiqing.parser.ParseUtil;
5 | import com.github.javaparser.ast.CompilationUnit;
6 | import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
7 | import com.github.javaparser.ast.expr.*;
8 | import org.apache.log4j.Logger;
9 |
10 | import java.util.ArrayList;
11 | import java.util.HashMap;
12 | import java.util.List;
13 | import java.util.Map;
14 | import java.util.concurrent.atomic.AtomicInteger;
15 |
16 | @SuppressWarnings("all")
17 | public class SimpleServletXss {
18 | private static Logger logger = Logger.getLogger(SimpleServletXss.class);
19 |
20 | private static final String SERVLET_REQUEST_IMPORT = "javax.servlet.http.HttpServletRequest";
21 | private static final String SERVLET_RESPONSE_IMPORT = "javax.servlet.http.HttpServletResponse";
22 | private static final String SERVLET_REQUEST_CLASS = "HttpServletRequest";
23 | private static final String SERVLET_RESPONSE_CLASS = "HttpServletResponse";
24 |
25 | public static List check(CompilationUnit compilationUnit) {
26 | List results = new ArrayList<>();
27 | // 是否导入servlet依赖
28 | boolean imported = ParseUtil.isImported(compilationUnit, SERVLET_REQUEST_IMPORT) &&
29 | ParseUtil.isImported(compilationUnit, SERVLET_RESPONSE_IMPORT);
30 | if (!imported) {
31 | logger.warn("no servlet xss");
32 | return results;
33 | }
34 | compilationUnit.findAll(ClassOrInterfaceDeclaration.class).stream()
35 | // 接口和抽象类不考虑
36 | .filter(c -> !c.isInterface() && !c.isAbstract()).forEach(c -> {
37 | // 遍历方法,不考虑main方法
38 | c.getMethods().stream().filter(m -> !m.getName().asString().equals("main")).forEach(m -> {
39 | // 请求和相应的具体参数
40 | Map params = new HashMap();
41 | m.getParameters().forEach(p -> {
42 | if (p.getType().asString().equals(SERVLET_RESPONSE_CLASS)) {
43 | params.put("response", p.getName().asString());
44 | }
45 | if (p.getType().asString().equals(SERVLET_REQUEST_CLASS)) {
46 | params.put("request", p.getName().asString());
47 | }
48 | });
49 | // 参数校验
50 | if (params.get("request") != null && params.get("request").equals("") ||
51 | params.get("response") != null && params.get("response").equals("")) {
52 | return;
53 | }
54 | Map data = new HashMap<>();
55 | AtomicInteger flag = new AtomicInteger(0);
56 | // 遍历方法中的赋值语句
57 | m.findAll(VariableDeclarationExpr.class).forEach(a -> {
58 | // 左值名
59 | String left = a.getVariables().get(0).getNameAsString();
60 | data.put("name", left);
61 | // 遍历赋值语句中的方法调用
62 | a.findAll(MethodCallExpr.class).forEach(am -> {
63 | // 判断是否调用getParameter方法
64 | if (am.getScope().get().toString().equals(params.get("request"))) {
65 | if (am.getName().asString().equals("getParameter")) {
66 | flag.getAndIncrement();
67 | }
68 | }
69 | });
70 | if (flag.get() != 0) {
71 | logger.info("find servlet parameter: " + data.get("name"));
72 | }
73 | });
74 | // 遍历方法调用
75 | m.findAll(MethodCallExpr.class).forEach(im -> {
76 | if (im.getScope().get().toString().equals(params.get("response"))) {
77 | // 如果调用了response.getWriter
78 | if (im.getName().asString().equals("getWriter")) {
79 | MethodCallExpr method;
80 | if (im.getParentNode().get() instanceof MethodCallExpr) {
81 | method = (MethodCallExpr) im.getParentNode().get();
82 | } else {
83 | return;
84 | }
85 | // response.getWriter.print();
86 | // response.getWriter.write();
87 | if (method.getName().asString().equals("print") ||
88 | method.getName().asString().equals("write")) {
89 | if (method.getChildNodes().size() == 3) {
90 | String target = method.getChildNodes().get(2).toString();
91 | if (target.equals(data.get("name"))) {
92 | // 封装结果
93 | Result result = new Result();
94 | result.setSuccess(true);
95 | result.setClassName(c.getNameAsString());
96 | result.setMethodName(m.getNameAsString());
97 | String keyword = String.format("%s.%s",
98 | im.getNameAsString(), method.getNameAsString());
99 | result.setKeyword(keyword);
100 | results.add(result);
101 | }
102 | }
103 | }
104 | }
105 | if (im.getName().asString().equals("getOutputStream")) {
106 | MethodCallExpr method = (MethodCallExpr) im.getParentNode().get();
107 | // response.getOutputStream.print();
108 | // response.getOutputStream.println();
109 | if (method.getName().asString().equals("print") ||
110 | method.getName().asString().equals("println")) {
111 | if (method.getChildNodes().size() == 3) {
112 | String target = method.getChildNodes().get(2).toString();
113 | if (target.equals(data.get("name"))) {
114 | // 封装结果
115 | Result result = new Result();
116 | result.setSuccess(true);
117 | result.setClassName(c.getNameAsString());
118 | result.setMethodName(m.getNameAsString());
119 | String keyword = String.format("%s.%s",
120 | im.getNameAsString(), method.getNameAsString());
121 | result.setKeyword(keyword);
122 | results.add(result);
123 | }
124 | }
125 | }
126 | }
127 | }
128 | });
129 | });
130 | });
131 | return results;
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/dto/Result.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.dto;
2 |
3 | public class Result {
4 | private boolean success;
5 | private String className;
6 | private String methodName;
7 | private String keyword;
8 |
9 | public String getKeyword() {
10 | return keyword;
11 | }
12 |
13 | public void setKeyword(String keyword) {
14 | this.keyword = keyword;
15 | }
16 |
17 | public boolean isSuccess() {
18 | return success;
19 | }
20 |
21 | public void setSuccess(boolean success) {
22 | this.success = success;
23 | }
24 |
25 | public String getClassName() {
26 | return className;
27 | }
28 |
29 | public void setClassName(String className) {
30 | this.className = className;
31 | }
32 |
33 | public String getMethodName() {
34 | return methodName;
35 | }
36 |
37 | public void setMethodName(String methodName) {
38 | this.methodName = methodName;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/input/Command.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.input;
2 |
3 | import com.beust.jcommander.Parameter;
4 |
5 | public class Command {
6 | @Parameter(names = {"-h", "--help"}, description = "Help Info",help = true)
7 | public boolean help;
8 |
9 | @Parameter(names = {"-f", "--file"}, description = "Scan Java File",
10 | validateWith = FilePathExist.class,required = true)
11 | public String filename;
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/input/FilePathExist.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.input;
2 |
3 | import com.beust.jcommander.IParameterValidator;
4 | import com.beust.jcommander.ParameterException;
5 | import org.apache.log4j.Logger;
6 |
7 | import java.io.File;
8 |
9 | public class FilePathExist implements IParameterValidator {
10 | Logger logger= Logger.getLogger(FilePathExist.class);
11 |
12 | @Override
13 | public void validate(String name, String value) throws ParameterException {
14 | File file = new File(value);
15 | if (!file.exists()) {
16 | logger.error("input file not exists");
17 | throw new ParameterException("input file not exists");
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/input/Logo.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.input;
2 |
3 | public class Logo {
4 | public static void PrintLogo(){
5 | System.out.println("___________.__ .___ \n" +
6 | "\\_ _____/|__| ____ __| _/___________ \n" +
7 | " | __) | |/ \\ / __ |/ __ \\_ __ \\\n" +
8 | " | \\ | | | \\/ /_/ \\ ___/| | \\/\n" +
9 | " \\___ / |__|___| /\\____ |\\___ >__| \n" +
10 | " \\/ \\/ \\/ \\/ ");
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/parser/ParseUtil.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.parser;
2 |
3 | import com.github.javaparser.ast.CompilationUnit;
4 |
5 | public class ParseUtil {
6 | /**
7 | * 是否导入了某类
8 | * @param compilationUnit cu
9 | * @param fullName 类全名
10 | * @return bool
11 | */
12 | public static boolean isImported(CompilationUnit compilationUnit, String fullName) {
13 | final boolean[] flag = new boolean[1];
14 | compilationUnit.getImports().forEach(i -> {
15 | if (i.getName().asString().equals(fullName)) {
16 | flag[0] = true;
17 | }
18 | });
19 | return flag[0];
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/com/emyiqing/util/FileUtil.java:
--------------------------------------------------------------------------------
1 | package com.emyiqing.util;
2 |
3 | import java.io.*;
4 | import java.nio.charset.StandardCharsets;
5 |
6 | public class FileUtil {
7 | public static String readFile(String filename) throws IOException {
8 | InputStream r = new FileInputStream(filename);
9 | ByteArrayOutputStream byteData = new ByteArrayOutputStream();
10 | byte[] temp = new byte[1024];
11 | byte[] context;
12 | int i;
13 | while ((i = r.read(temp)) > 0) {
14 | byteData.write(temp, 0, i);
15 | }
16 | context = byteData.toByteArray();
17 | String str = new String(context, StandardCharsets.UTF_8);
18 | r.close();
19 | byteData.close();
20 | return str;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/resources/log4j.properties:
--------------------------------------------------------------------------------
1 | log4j.rootLogger=INFO,console
2 | log4j.additivity.org.apache=true
3 | log4j.appender.console=org.apache.log4j.ConsoleAppender
4 | log4j.appender.console.Threshold=INFO
5 | log4j.appender.console.ImmediateFlush=true
6 | log4j.appender.console.Target=System.out
7 | log4j.appender.console.layout=org.apache.log4j.PatternLayout
8 | log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss} [%p] [%c] %m%n
--------------------------------------------------------------------------------