|
| 1 | +package io.codemodder.remediation.xxe; |
| 2 | + |
| 3 | +import com.github.javaparser.ast.CompilationUnit; |
| 4 | +import com.github.javaparser.ast.Node; |
| 5 | +import com.github.javaparser.ast.body.VariableDeclarator; |
| 6 | +import com.github.javaparser.ast.expr.Expression; |
| 7 | +import com.github.javaparser.ast.expr.MethodCallExpr; |
| 8 | +import com.github.javaparser.ast.stmt.Statement; |
| 9 | +import io.codemodder.ast.ASTs; |
| 10 | +import io.codemodder.remediation.SuccessOrReason; |
| 11 | +import java.util.List; |
| 12 | +import java.util.Optional; |
| 13 | + |
| 14 | +final class XMLInputFactoryAtNewInstanceFixStrategy |
| 15 | + extends io.codemodder.remediation.MatchAndFixStrategy { |
| 16 | + |
| 17 | + /** |
| 18 | + * Matches (XmlInputFactory | var xif) y = XMLInputFactory.newInstance(), where the node is the |
| 19 | + * newDocumentBuilder call. |
| 20 | + * |
| 21 | + * @param node the node to match |
| 22 | + * @return true if this is an assignment to an XMLInputFactory |
| 23 | + */ |
| 24 | + @Override |
| 25 | + public boolean match(final Node node) { |
| 26 | + Optional<MethodCallExpr> method = |
| 27 | + ASTs.isInitializedToType(node, "newInstance", List.of("var", "XMLInputFactory")); |
| 28 | + if (method.isEmpty()) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + MethodCallExpr newInstance = method.get(); |
| 32 | + Optional<Expression> scope = newInstance.getScope(); |
| 33 | + if (scope.isEmpty()) { |
| 34 | + return false; |
| 35 | + } |
| 36 | + return scope.get().toString().equals("XMLInputFactory"); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public SuccessOrReason fix(final CompilationUnit cu, final Node node) { |
| 41 | + MethodCallExpr newInstance = (MethodCallExpr) node; |
| 42 | + Optional<VariableDeclarator> initExpr = ASTs.isInitExpr(newInstance); |
| 43 | + if (initExpr.isEmpty()) { |
| 44 | + return SuccessOrReason.reason("Not an initialization expression"); |
| 45 | + } |
| 46 | + VariableDeclarator xmlInputFactoryVariable = initExpr.get(); |
| 47 | + Optional<Statement> variableDeclarationStmtRef = |
| 48 | + xmlInputFactoryVariable.findAncestor(Statement.class); |
| 49 | + |
| 50 | + if (variableDeclarationStmtRef.isEmpty()) { |
| 51 | + return SuccessOrReason.reason("Not assigned as part of statement"); |
| 52 | + } |
| 53 | + |
| 54 | + Statement stmt = variableDeclarationStmtRef.get(); |
| 55 | + return XMLFixBuilder.addXMLInputFactoryDisablingStatement( |
| 56 | + xmlInputFactoryVariable.getNameAsExpression(), stmt, false); |
| 57 | + } |
| 58 | +} |
0 commit comments