Skip to content

Commit

Permalink
Merge pull request #31 from NASA-AMMOS/login-redirects
Browse files Browse the repository at this point in the history
Sanitize login redirect targets
  • Loading branch information
galenatjpl authored Mar 5, 2021
2 parents 8a5a124 + baf1ae4 commit 315fde0
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 315fde0

Please sign in to comment.