|
1 |
| -package com.example.demo; |
2 |
| - |
3 |
| -import java.util.regex.Matcher; |
4 | 1 | import java.util.regex.Pattern;
|
| 2 | +import javax.servlet.http.HttpServlet; |
| 3 | +import javax.servlet.http.HttpServletRequest; |
5 | 4 |
|
6 |
| -import org.springframework.web.bind.annotation.GetMapping; |
7 |
| -import org.springframework.web.bind.annotation.RequestParam; |
8 |
| -import org.springframework.web.bind.annotation.RestController; |
9 |
| - |
10 |
| -@RestController |
11 |
| -public class DemoApplication { |
12 |
| - |
13 |
| - @GetMapping("/string1") |
14 |
| - public String string1(@RequestParam(value = "input", defaultValue = "test") String input, |
15 |
| - @RequestParam(value = "pattern", defaultValue = ".*") String pattern) { |
16 |
| - // BAD: Unsanitized user input is used to construct a regular expression |
17 |
| - if (input.matches("^" + pattern + "=.*$")) |
18 |
| - return "match!"; |
19 |
| - |
20 |
| - return "doesn't match!"; |
21 |
| - } |
| 5 | +public class RegexInjectionDemo extends HttpServlet { |
22 | 6 |
|
23 |
| - @GetMapping("/string2") |
24 |
| - public String string2(@RequestParam(value = "input", defaultValue = "test") String input, |
25 |
| - @RequestParam(value = "pattern", defaultValue = ".*") String pattern) { |
26 |
| - // GOOD: User input is sanitized before constructing the regex |
27 |
| - if (input.matches("^" + escapeSpecialRegexChars(pattern) + "=.*$")) |
28 |
| - return "match!"; |
| 7 | + public boolean badExample(javax.servlet.http.HttpServletRequest request) { |
| 8 | + String regex = request.getParameter("regex"); |
| 9 | + String input = request.getParameter("input"); |
29 | 10 |
|
30 |
| - return "doesn't match!"; |
31 |
| - } |
| 11 | + // BAD: Unsanitized user input is used to construct a regular expression |
| 12 | + return input.matches(regex); |
| 13 | + } |
32 | 14 |
|
33 |
| - Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\]><-=!.+*?^$\\\\|]"); |
| 15 | + public boolean goodExample(javax.servlet.http.HttpServletRequest request) { |
| 16 | + String regex = request.getParameter("regex"); |
| 17 | + String input = request.getParameter("input"); |
34 | 18 |
|
35 |
| - String escapeSpecialRegexChars(String str) { |
36 |
| - return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0"); |
37 |
| - } |
| 19 | + // GOOD: User input is sanitized before constructing the regex |
| 20 | + return input.matches(Pattern.quote(regex)); |
| 21 | + } |
38 | 22 | }
|
0 commit comments