Skip to content

Commit 0b04c30

Browse files
authored
Merge pull request #499 from SEMOSS/fix-snyk-headers-redirects
fix(security): strip CR/LF from response headers, validate redirects, contain uploads (Snyk)
2 parents 0590c51 + 7053b30 commit 0b04c30

24 files changed

Lines changed: 323 additions & 86 deletions

‎WebContent/samlLogin/index.html‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
<title>SAML Login</title>
55
<script>
66
function redirectSAML() {
7-
var xhttp = new XMLHttpRequest(),
8-
origin = window.location.href;
9-
endpoint = origin.substring(0, origin.lastIndexOf('/samlLogin')) + '/IdpSSOServlet',
10-
window.location.replace(endpoint);
11-
xhttp.open('GET', endpoint, true);
12-
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
7+
// sibling endpoint only, never built from the href (query or fragment text)
8+
if (window.location.pathname.endsWith('/samlLogin')) {
9+
window.location.replace('./IdpSSOServlet');
10+
} else {
11+
var trailingSlashes = window.location.pathname.match(/\/+$/);
12+
var levels = trailingSlashes ? trailingSlashes[0].length : 1;
13+
window.location.replace('../'.repeat(levels) + 'IdpSSOServlet');
14+
}
1315
}
1416
</script>
1517
</head>

‎WebContent/samlSPLogin/index.html‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,14 @@
44
<title>SAML Login</title>
55
<script>
66
function redirectSAML() {
7-
var xhttp = new XMLHttpRequest(),
8-
origin = window.location.href;
9-
endpoint = origin.substring(0, origin.lastIndexOf('/samlSPLogin')) + '/SPSSOServlet',
10-
window.location.replace(endpoint);
11-
xhttp.open('GET', endpoint, true);
12-
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
7+
// sibling endpoint only, never built from the href (query or fragment text)
8+
if (window.location.pathname.endsWith('/samlSPLogin')) {
9+
window.location.replace('./SPSSOServlet');
10+
} else {
11+
var trailingSlashes = window.location.pathname.match(/\/+$/);
12+
var levels = trailingSlashes ? trailingSlashes[0].length : 1;
13+
window.location.replace('../'.repeat(levels) + 'SPSSOServlet');
14+
}
1315
}
1416
</script>
1517
</head>

‎WebContent/setAdmin/index.html‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,19 @@
219219
return '/';
220220
}
221221

222+
// relative so the destination never comes from page text
223+
function returnToBase() {
224+
var path = window.location.pathname;
225+
if (path.indexOf('/setAdmin') < 0) {
226+
window.location.replace('/');
227+
} else if (path.endsWith('/setAdmin')) {
228+
window.location.replace('./');
229+
} else {
230+
var trailingSlashes = path.match(/\/+$/);
231+
window.location.replace('../'.repeat(trailingSlashes ? trailingSlashes[0].length : 1));
232+
}
233+
}
234+
222235
function xhr(method, url, body, headers, callback) {
223236
var req = new XMLHttpRequest();
224237
req.open(method, url, true);
@@ -281,7 +294,7 @@
281294
return;
282295
}
283296

284-
window.location.replace(getBasePrefix());
297+
returnToBase();
285298
return;
286299
}
287300

‎src/prerna/semoss/web/services/local/NameServer.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,9 @@ public Response downloadFile(@QueryParam("insightId") String insightId, @QueryPa
145145

146146
String exportName = FilenameUtils.getName(filePath);
147147
return Response.status(200).entity(exportFile)
148-
.header("Content-Disposition", "attachment; filename=\"" + exportName + "\"").build();
148+
.header("Content-Disposition",
149+
WebUtility.responseHeaderValue("attachment; filename=\"" + exportName + "\""))
150+
.build();
149151
} catch (Exception e) {
150152
Map<String, String> errorMap = new HashMap<>();
151153
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());

‎src/prerna/semoss/web/services/local/ProjectResource.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -761,7 +761,7 @@ public Response downloadProjectImage(@Context final Request coreRequest, @Contex
761761
EntityTag etag = new EntityTag(Integer.toHexString(exportFile.getAbsolutePath().hashCode()) + "-"
762762
+ exportFile.lastModified() + "-" + exportFile.length());
763763
return CatalogImageResponse.withBrowserCache(coreRequest, Response.ok(exportFile)
764-
.header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build());
764+
.header("Content-Disposition", WebUtility.responseHeaderValue("attachment; filename=" + exportName)).tag(etag).build());
765765
} else {
766766
Map<String, String> errorMap = new HashMap<>();
767767
errorMap.put(Constants.ERROR_MESSAGE, "error sending image file");
@@ -869,7 +869,7 @@ public Response downloadInsightImage(@Context final Request coreRequest, @Contex
869869
}
870870

871871
return CatalogImageResponse.withContentType(Response.ok(exportFile)
872-
.header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build());
872+
.header("Content-Disposition", WebUtility.responseHeaderValue("attachment; filename=" + exportName)).tag(etag).build());
873873
} else {
874874
Map<String, String> errorMap = new HashMap<>();
875875
errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file");

‎src/prerna/semoss/web/services/local/SessionResource.java‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ public void invalidateSession(@Context HttpServletRequest request, @Context Http
250250

251251
String customUrl = DBLoader.getCustomLogoutUrl();
252252
if (customUrl != null && !customUrl.isEmpty()) {
253-
response.setHeader("redirect", customUrl);
253+
response.setHeader("redirect", WebUtility.responseHeaderValue(customUrl));
254254
response.sendError(302, "Need to redirect to " + customUrl);
255255
} else {
256256
String scheme = WebUtility.inputSQLSanitizer(request.getScheme()); // http
@@ -270,15 +270,15 @@ public void invalidateSession(@Context HttpServletRequest request, @Context Http
270270
}
271271
redirectUrl += contextPath + "/logout/";
272272
redirectUrl = WebUtility.cleanHttpResponse(redirectUrl);
273-
response.setHeader("redirect", redirectUrl);
273+
response.setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl));
274274
response.sendError(302, "Need to redirect to " + redirectUrl);
275275
}
276276
} else {
277277
classLogger.info("Session ended. Redirect to login page");
278278

279279
redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request);
280280
String encodedRedirectUrl = Encode.forHtml(redirectUrl);
281-
response.setHeader("redirect", encodedRedirectUrl);
281+
response.setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl));
282282
response.sendError(302, "Need to redirect to " + encodedRedirectUrl);
283283
}
284284

‎src/prerna/semoss/web/services/local/UserResource.java‎

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,7 @@
9999
import prerna.util.linotp.LinOTPUtil;
100100
import prerna.web.conf.DBLoader;
101101
import prerna.web.conf.UserSessionLoader;
102+
import prerna.web.services.util.RedirectUtility;
102103
import prerna.web.services.util.WebUtility;
103104
import waffle.servlet.WindowsPrincipal;
104105

@@ -243,7 +244,7 @@ public Response logout(@PathParam("provider") String provider,
243244

244245
String customUrl = DBLoader.getCustomLogoutUrl();
245246
if (customUrl != null && !customUrl.isEmpty()) {
246-
response.setHeader("redirect", customUrl);
247+
response.setHeader("redirect", WebUtility.responseHeaderValue(customUrl));
247248
response.sendError(302, "Need to redirect to " + customUrl);
248249
} else {
249250
String redirectUrl = WebUtility.inputSanitizer(request.getHeader("referer"));
@@ -262,12 +263,12 @@ public Response logout(@PathParam("provider") String provider,
262263
redirectUrl += ":" + serverPort;
263264
}
264265
redirectUrl += contextPath + "/logout/";
265-
response.setHeader("redirect", redirectUrl);
266+
response.setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl));
266267
response.sendError(302, "Need to redirect to " + redirectUrl);
267268
} else {
268269
redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request);
269270
String encodedRedirectUrl = Encode.forHtml(redirectUrl);
270-
response.setHeader("redirect", encodedRedirectUrl);
271+
response.setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl));
271272
response.sendError(302, "Need to redirect to " + encodedRedirectUrl);
272273
}
273274
}
@@ -434,7 +435,8 @@ public Response userinfoGeneric(@PathParam("provider") String provider, @Context
434435
*/
435436
private HttpSession initializeOAuthLoginSession(HttpServletRequest request) {
436437
HttpSession session = request.getSession(false);
437-
String customRedirect = WebUtility.cleanHttpResponse(request.getParameter("redirect"));
438+
// checked raw: html-encoding first would corrupt valid urls, and the check refuses control characters
439+
String customRedirect = RedirectUtility.allowedReturnUrl(request, request.getParameter("redirect"));
438440
if (customRedirect != null && !customRedirect.isEmpty()) {
439441
if (session == null) {
440442
session = request.getSession();
@@ -1350,7 +1352,8 @@ public Response loginNative(@Context HttpServletRequest request, @Context HttpSe
13501352
try {
13511353
String username = WebUtility.inputSQLSanitizer(request.getParameter("username"));
13521354
String password = WebUtility.inputSQLSanitizer(request.getParameter("password"));
1353-
String redirect = WebUtility.cleanHttpResponse(request.getParameter("redirect"));
1355+
// validated raw in setMainPageRedirect
1356+
String redirect = request.getParameter("redirect");
13541357
// so that the default is to redirect
13551358
Boolean disableRedirect = Boolean.parseBoolean(request.getParameter("disableRedirect") + "");
13561359

@@ -1587,7 +1590,8 @@ public Response loginLinOTP(@Context HttpServletRequest request, @Context HttpSe
15871590
return WebUtility.getResponse(returnMap, 400);
15881591
}
15891592

1590-
String redirect = WebUtility.cleanHttpResponse(request.getParameter("redirect"));
1593+
// validated raw in setMainPageRedirect
1594+
String redirect = request.getParameter("redirect");
15911595
// so that the default is to redirect
15921596
Boolean disableRedirect = Boolean.parseBoolean(request.getParameter("disableRedirect") + "");
15931597
boolean autoAdd = Boolean.parseBoolean(socialData.getProperty("linotp_auto_add", "true"));
@@ -1935,7 +1939,8 @@ public synchronized Response getAllLoginProperties(@Context HttpServletRequest r
19351939
* @param response outbound HTTP response
19361940
*/
19371941
private void setMainPageRedirect(@Context HttpServletRequest request, @Context HttpServletResponse response) {
1938-
String customRedirect = WebUtility.cleanHttpResponse(request.getParameter("redirect"));
1942+
// validated raw in setMainPageRedirect(request, response, customRedirect)
1943+
String customRedirect = request.getParameter("redirect");
19391944
if (customRedirect == null || customRedirect.isEmpty()) {
19401945
customRedirect = (String) request.getSession().getAttribute(CUSTOM_REDIRECT_SESSION_KEY);
19411946
// also remove the attribute so additional logins dont do the redirect as well
@@ -1958,18 +1963,20 @@ private void setMainPageRedirect(@Context HttpServletRequest request, @Context H
19581963
// otherwise, we send them back to the FE
19591964
HttpSession session = request.getSession();
19601965

1966+
// the redirect can come from the request or the session, only return to an allowed destination
1967+
customRedirect = RedirectUtility.allowedReturnUrl(request, customRedirect);
19611968
boolean useCustom = customRedirect != null && !customRedirect.isEmpty();
19621969
boolean endpoint = session.getAttribute(Constants.ENDPOINT_REDIRECT_KEY) != null;
19631970
response.setStatus(302);
19641971
try {
19651972
addSessionCookieHeader(request, response, session);
19661973
if (useCustom) {
1967-
response.addHeader("redirect", customRedirect);
1974+
response.addHeader("redirect", WebUtility.responseHeaderValue(customRedirect));
19681975
String encodedCustomRedirect = Encode.forHtml(customRedirect);
19691976
response.sendError(302, "Need to redirect to " + encodedCustomRedirect);
19701977
} else if (endpoint) {
19711978
String redirectUrl = session.getAttribute(Constants.ENDPOINT_REDIRECT_KEY) + "";
1972-
response.addHeader("redirect", redirectUrl);
1979+
response.addHeader("redirect", WebUtility.responseHeaderValue(redirectUrl));
19731980
response.sendError(302, "Need to redirect to " + redirectUrl);
19741981
} else {
19751982
response.sendRedirect(socialData.getProperty("redirect"));
@@ -1994,7 +2001,7 @@ private void addSessionCookieHeader(HttpServletRequest request, HttpServletRespo
19942001
+ ((ClusterUtil.IS_CLUSTER || secureRequest)
19952002
? ("; Secure; SameSite=" + Utility.getSameSiteCookieValue())
19962003
: "");
1997-
response.addHeader("Set-Cookie", setCookieString);
2004+
response.addHeader("Set-Cookie", WebUtility.responseHeaderValue(setCookieString));
19982005
}
19992006

20002007
//////////////////////////////////////////////////////////////////////

‎src/prerna/semoss/web/services/saml/IdpSSOServlet.java‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
import prerna.util.Constants;
4545
import prerna.util.Utility;
4646
import prerna.web.conf.util.SSOUtil;
47-
import prerna.web.services.util.WebUtility;
47+
import prerna.web.services.util.RedirectUtility;
4848

4949
/**
5050
* Handles the IdP-initiated login entry point.
@@ -98,9 +98,8 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
9898
String redirect = request.getParameter("redirect");
9999
boolean hasRedirect = (redirect != null && !(redirect = redirect.trim()).isEmpty());
100100
if (hasRedirect) {
101-
try {
102-
WebUtility.checkIfValidDomain(redirect);
103-
} catch (IllegalArgumentException | IllegalStateException e) {
101+
// one policy: relative, this origin, the configured UI, redirect_allowed_origins or WHITE_LIST_DOMAINS
102+
if (RedirectUtility.allowedReturnUrl(request, redirect) == null) {
104103
response.sendError(HttpServletResponse.SC_FORBIDDEN, " Provided redirect is unauthorized");
105104
return;
106105
}

‎src/prerna/semoss/web/services/saml/SamlVerifierServlet.java‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@
7878
import prerna.util.Utility;
7979
import prerna.web.conf.AdminStartupFilter;
8080
import prerna.web.conf.util.SSOUtil;
81+
import prerna.web.services.util.RedirectUtility;
82+
import prerna.web.services.util.WebUtility;
8183

8284
/**
8385
* Receives the SAML assertion callback from the IdP and finalizes login in this
@@ -161,7 +163,8 @@ public void verifySamlOutput(HttpServletRequest request, HttpServletResponse res
161163
if ((relayUrl != null) && (relayUrl.length() != 0)) {
162164
// something special for validation to send redirect
163165
int stringPos = relayUrl.indexOf("sendRedirectForValidationNow=true");
164-
if (stringPos != -1) {
166+
// RelayState is not signed, so only follow it to an allowed destination
167+
if (stringPos != -1 && RedirectUtility.allowedReturnUrl(request, relayUrl) != null) {
165168
response.sendRedirect(relayUrl);
166169
return;
167170
}
@@ -245,8 +248,10 @@ public void verifySamlOutput(HttpServletRequest request, HttpServletResponse res
245248
// Complete the SSO transaction by returning the user to their original target.
246249
String encodedRedirectUrl = Encode.forHtml(originalRedirect);
247250
AdminStartupFilter.setSuccessfulRedirectUrl(encodedRedirectUrl);
248-
response.setHeader("redirect", encodedRedirectUrl);
249-
response.sendRedirect(encodedRedirectUrl);
251+
// the stored value was checked when it was saved; html-encoding it here would break query strings
252+
String redirectHeader = WebUtility.responseHeaderValue(originalRedirect);
253+
response.setHeader("redirect", redirectHeader);
254+
response.sendRedirect(redirectHeader);
250255

251256
} catch (SAML2Exception | IOException | SessionException | ServletException sme) {
252257
classLogger.error("Failed to process SAML verification response.", sme);

‎src/prerna/upload/FileUploader.java‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -842,14 +842,20 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> fileItems,
842842
// Check for viruses on upload
843843
checkForViruses(fi);
844844

845+
// normalize the name first so the uniqueness check, the write and the reply use the same name
846+
String baseName = name == null ? null : FilenameUtils.getName(name);
847+
name = baseName == null ? null : WebUtility.normalizePath(baseName);
848+
if (!WebUtility.isSafePathSegment(name)) {
849+
throw new IllegalArgumentException("Invalid upload file name");
850+
}
845851
String fileLocation = Utility.getUniqueFilePath(filePath, name);
846-
File file = new File(WebUtility.normalizePath(fileLocation));
852+
File file = containedUploadFile(filePath, fileLocation);
847853

848854
// instead of adding unique
849855
// we will do what a normal OS system does
850856
writeFile(fi, file);
851857

852-
String savedName = FilenameUtils.getName(fileLocation);
858+
String savedName = file.getName();
853859
Map<String, String> fileMap = new HashMap<String, String>();
854860
fileMap.put("fileName", savedName);
855861
if (fePath.endsWith(DIR_SEPARATOR)) {
@@ -868,11 +874,11 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> fileItems,
868874

869875
String fileLocation = Utility.getUniqueFilePath(filePath, "AutoGeneratedFile.txt");
870876

871-
File file = new File(WebUtility.normalizePath(fileLocation));
877+
File file = containedUploadFile(filePath, fileLocation);
872878
writeFile(fi, file);
873879
classLogger.info("Saved Pasted Data To {}", Utility.cleanLogString(file.toString()));
874880

875-
String savedName = FilenameUtils.getName(fileLocation);
881+
String savedName = file.getName();
876882
Map<String, String> fileMap = new HashMap<String, String>();
877883
fileMap.put("fileName", savedName);
878884
if (fePath.endsWith(DIR_SEPARATOR)) {
@@ -889,6 +895,24 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> fileItems,
889895
return retData;
890896
}
891897

898+
// the upload target must be a direct child of the upload folder, and the binary write
899+
// (which normalizes the path again) must land on exactly the path that was checked
900+
private static File containedUploadFile(String folder, String fileLocation) throws IOException {
901+
java.nio.file.Path root = Paths.get(WebUtility.normalizePath(folder));
902+
Files.createDirectories(root);
903+
String normalized = WebUtility.normalizePath(fileLocation);
904+
String name = normalized == null ? null : FilenameUtils.getName(normalized);
905+
if (!WebUtility.isSafePathSegment(name)) {
906+
throw new IllegalArgumentException("Invalid upload file name");
907+
}
908+
java.nio.file.Path target = WebUtility.resolveWithin(root, name);
909+
// compare as paths so Windows separators do not matter
910+
if (!Paths.get(WebUtility.normalizePath(target.toString())).equals(target)) {
911+
throw new IllegalArgumentException("Invalid upload file name");
912+
}
913+
return target.toFile();
914+
}
915+
892916
/**
893917
* Checks a file for viruses.
894918
*

0 commit comments

Comments
 (0)