|
| 1 | +/** Provides classes to reason about partial path traversal vulnerabilities. */ |
| 2 | + |
| 3 | +import java |
| 4 | +private import semmle.code.java.dataflow.DataFlow |
| 5 | +private import semmle.code.java.environment.SystemProperty |
| 6 | + |
| 7 | +private class MethodStringStartsWith extends Method { |
| 8 | + MethodStringStartsWith() { |
| 9 | + this.getDeclaringType() instanceof TypeString and |
| 10 | + this.hasName("startsWith") |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +private class MethodFileGetCanonicalPath extends Method { |
| 15 | + MethodFileGetCanonicalPath() { |
| 16 | + this.getDeclaringType() instanceof TypeFile and |
| 17 | + this.hasName("getCanonicalPath") |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +private class MethodAccessFileGetCanonicalPath extends MethodAccess { |
| 22 | + MethodAccessFileGetCanonicalPath() { this.getMethod() instanceof MethodFileGetCanonicalPath } |
| 23 | +} |
| 24 | + |
| 25 | +abstract private class FileSeparatorExpr extends Expr { } |
| 26 | + |
| 27 | +private class SystemPropFileSeparatorExpr extends FileSeparatorExpr { |
| 28 | + SystemPropFileSeparatorExpr() { this = getSystemProperty("file.separator") } |
| 29 | +} |
| 30 | + |
| 31 | +private class StringLiteralFileSeparatorExpr extends FileSeparatorExpr, StringLiteral { |
| 32 | + StringLiteralFileSeparatorExpr() { |
| 33 | + this.getValue().matches("%/") or this.getValue().matches("%\\") |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +private class CharacterLiteralFileSeparatorExpr extends FileSeparatorExpr, CharacterLiteral { |
| 38 | + CharacterLiteralFileSeparatorExpr() { this.getValue() = "/" or this.getValue() = "\\" } |
| 39 | +} |
| 40 | + |
| 41 | +private class FileSeparatorAppend extends AddExpr { |
| 42 | + FileSeparatorAppend() { this.getRightOperand() instanceof FileSeparatorExpr } |
| 43 | +} |
| 44 | + |
| 45 | +private predicate isSafe(Expr expr) { |
| 46 | + DataFlow::localExprFlow(any(Expr e | |
| 47 | + e instanceof FileSeparatorAppend or e instanceof FileSeparatorExpr |
| 48 | + ), expr) |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * A method access that returns a boolean that incorrectly guards against Partial Path Traversal. |
| 53 | + */ |
| 54 | +class PartialPathTraversalMethodAccess extends MethodAccess { |
| 55 | + PartialPathTraversalMethodAccess() { |
| 56 | + this.getMethod() instanceof MethodStringStartsWith and |
| 57 | + DataFlow::localExprFlow(any(MethodAccessFileGetCanonicalPath gcpma), this.getQualifier()) and |
| 58 | + not isSafe(this.getArgument(0)) |
| 59 | + } |
| 60 | +} |
0 commit comments