Skip to content

Commit

Permalink
Sanitize login redirect targets to only allow relative paths and quer…
Browse files Browse the repository at this point in the history
…y parameters
  • Loading branch information
ztaylor54 committed Mar 5, 2021
1 parent 28485f9 commit 88f6b85
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cws-service/src/main/java/jpl/cws/controller/MvcService.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -99,9 +101,33 @@ public ModelAndView logintotarget(
.singleResult();
log.debug("user: " + user);

String pattern = // first part: some/relative/path
"^" // Anchor at the beginning of the string
+ "(?!\\/)" // Assert the first character isn't a '/' (negative lookahead)
+ "(?!.*\\/\\/)" // Assert there are no "//" present anywhere (negative lookahead)
+ "[A-Za-z0-9-\\/]+" // Match one or more allowed characters
+ "(?<!\\/)" // Assert the last character isn't a '/'
// second part: ?key=value
+ "(\\?" // Match '?' (start capture group 1)
+ "[A-Za-z0-9-]+=[A-Za-z0-9-]+" // Match key=value format one or more times
+ "(&[A-Za-z0-9-]+=[A-Za-z0-9-]+)*" // Followed by &key=value zero or more times
+ "){0,1}" // Match capture group 1 zero or 1 times
+ "$"; // Anchor at the end of the string

// if target page is not null, then redirect to target page
//
if (targetPage != null) {

// input validation for targetPage - make sure only relative paths with query params are allowed
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(targetPage);

if (!m.find()) {
// inavalid redirect, redirect to home instead
log.warn("invalid redirect target at login (targetPage = " + targetPage + "), routing to home instead. was this a phishing attempt?");
return buildHomeModel("Welcome " + (user == null ? username : user.getFirstName()));
}

try {
log.debug("redirecting successful login (of user '" + username + "') to " + targetPage);
response.sendRedirect(targetPage);
Expand Down

0 comments on commit 88f6b85

Please sign in to comment.