Skip to content

Commit 7a9cb64

Browse files
committed
Java: Treat x.matches(regexp) as a sanitizer for request forgery
1 parent c84cec9 commit 7a9cb64

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

‎java/ql/lib/semmle/code/java/security/RequestForgery.qll‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,3 +164,24 @@ private class HostComparisonSanitizer extends RequestForgerySanitizer {
164164
this = DataFlow::BarrierGuard<isHostComparisonSanitizer/3>::getABarrierNode()
165165
}
166166
}
167+
168+
/**
169+
* A qualifier in a call to a `.matches()` method that is a sanitizer for URL redirects.
170+
*
171+
* Matches any method call where the method is named `matches`.
172+
*/
173+
private predicate isMatchesSanitizer(Guard guard, Expr e, boolean branch) {
174+
guard =
175+
any(MethodCall method |
176+
method.getMethod().getName() = "matches" and
177+
e = method.getQualifier() and
178+
branch = true
179+
)
180+
}
181+
182+
/**
183+
* A qualifier in a call to `.matches()` that is a sanitizer for URL redirects.
184+
*/
185+
private class MatchesSanitizer extends RequestForgerySanitizer {
186+
MatchesSanitizer() { this = DataFlow::BarrierGuard<isMatchesSanitizer/3>::getABarrierNode() }
187+
}

‎java/ql/test/query-tests/security/CWE-918/SanitizationTests.java‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,8 +119,30 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
119119
String unsafeUri10 = String.format("%s://%s:%s%s", "http", "myserver.com", "80", request.getParameter("baduri10")); // $ Source
120120
HttpRequest unsafer10 = HttpRequest.newBuilder(new URI(unsafeUri10)).build(); // $ Alert
121121
client.send(unsafer10, null); // $ Alert
122+
123+
// GOOD: sanitisation by regexp validation
124+
String safeUri10 = "https://example.com/";
125+
String param10 = request.getParameter("uri10");
126+
if (param10.matches("[a-zA-Z0-9/_-]+")) {
127+
safeUri10 = safeUri10 + param10;
128+
}
129+
HttpRequest r10 = HttpRequest.newBuilder(new URI(safeUri10)).build();
130+
client.send(r10, null);
131+
132+
133+
String param11 = request.getParameter("uri11");
134+
validate(param11);
135+
String safeUri11 = "https://example.com/" + param11;
136+
HttpRequest r11 = HttpRequest.newBuilder(new URI(safeUri11)).build();
137+
client.send(r11, null);
122138
} catch (Exception e) {
123139
// TODO: handle exception
124140
}
125141
}
142+
143+
private void validate(String s) {
144+
if (!s.matches("[a-zA-Z0-9/_-]+")) {
145+
throw new IllegalArgumentException("Invalid ID");
146+
}
147+
}
126148
}

0 commit comments

Comments
 (0)