From f9df8887f5f6602abcbf0c391074f103e44864be Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:54:15 -0500 Subject: [PATCH 1/4] fix(upload): keep upload targets inside the upload folder --- src/prerna/upload/FileUploader.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/prerna/upload/FileUploader.java b/src/prerna/upload/FileUploader.java index a391983a..7974b06b 100644 --- a/src/prerna/upload/FileUploader.java +++ b/src/prerna/upload/FileUploader.java @@ -843,7 +843,7 @@ private List> processFileItems(List fileItems, checkForViruses(fi); String fileLocation = Utility.getUniqueFilePath(filePath, name); - File file = new File(WebUtility.normalizePath(fileLocation)); + File file = containedUploadFile(filePath, fileLocation); // instead of adding unique // we will do what a normal OS system does @@ -868,7 +868,7 @@ private List> processFileItems(List fileItems, String fileLocation = Utility.getUniqueFilePath(filePath, "AutoGeneratedFile.txt"); - File file = new File(WebUtility.normalizePath(fileLocation)); + File file = containedUploadFile(filePath, fileLocation); writeFile(fi, file); classLogger.info("Saved Pasted Data To {}", Utility.cleanLogString(file.toString())); @@ -889,6 +889,13 @@ private List> processFileItems(List fileItems, return retData; } + // the upload target must be a direct child of the upload folder + private static File containedUploadFile(String folder, String fileLocation) throws IOException { + java.nio.file.Path root = Paths.get(WebUtility.normalizePath(folder)); + Files.createDirectories(root); + return WebUtility.resolveWithin(root, FilenameUtils.getName(fileLocation)).toFile(); + } + /** * Checks a file for viruses. * From 63aa67a915cd0973fd7159e8df8a5a32e4518730 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 09:54:15 -0500 Subject: [PATCH 2/4] fix(security): strip CR/LF from response headers and validate redirect targets --- WebContent/samlLogin/index.html | 14 +- WebContent/samlSPLogin/index.html | 14 +- WebContent/setAdmin/index.html | 15 +- .../semoss/web/services/local/NameServer.java | 4 +- .../web/services/local/ProjectResource.java | 4 +- .../web/services/local/SessionResource.java | 6 +- .../web/services/local/UserResource.java | 18 ++- .../web/services/saml/IdpSSOServlet.java | 6 + src/prerna/web/conf/AccountLockedFilter.java | 2 +- src/prerna/web/conf/MemoryCheckFilter.java | 2 +- .../web/conf/NoUserInSessionFilter.java | 9 +- src/prerna/web/conf/SSOFilter.java | 15 +- .../conf/SessionCounterExceededFilter.java | 2 +- src/prerna/web/conf/ShareSessionFilter.java | 31 ++-- src/prerna/web/conf/StartUpSuccessFilter.java | 2 +- src/prerna/web/conf/UserExistsFilter.java | 5 +- .../web/services/util/RedirectUtility.java | 142 ++++++++++++++++++ src/prerna/web/services/util/WebUtility.java | 9 +- 18 files changed, 237 insertions(+), 63 deletions(-) create mode 100644 src/prerna/web/services/util/RedirectUtility.java diff --git a/WebContent/samlLogin/index.html b/WebContent/samlLogin/index.html index 887dbc00..c32ffc3c 100644 --- a/WebContent/samlLogin/index.html +++ b/WebContent/samlLogin/index.html @@ -4,12 +4,14 @@ SAML Login diff --git a/WebContent/samlSPLogin/index.html b/WebContent/samlSPLogin/index.html index 100cd162..f5ef66be 100644 --- a/WebContent/samlSPLogin/index.html +++ b/WebContent/samlSPLogin/index.html @@ -4,12 +4,14 @@ SAML Login diff --git a/WebContent/setAdmin/index.html b/WebContent/setAdmin/index.html index 61a4ec76..d3ac3f06 100644 --- a/WebContent/setAdmin/index.html +++ b/WebContent/setAdmin/index.html @@ -219,6 +219,19 @@ return '/'; } + // relative so the destination never comes from page text + function returnToBase() { + var path = window.location.pathname; + if (path.indexOf('/setAdmin') < 0) { + window.location.replace('/'); + } else if (path.endsWith('/setAdmin')) { + window.location.replace('./'); + } else { + var trailingSlashes = path.match(/\/+$/); + window.location.replace('../'.repeat(trailingSlashes ? trailingSlashes[0].length : 1)); + } + } + function xhr(method, url, body, headers, callback) { var req = new XMLHttpRequest(); req.open(method, url, true); @@ -281,7 +294,7 @@ return; } - window.location.replace(getBasePrefix()); + returnToBase(); return; } diff --git a/src/prerna/semoss/web/services/local/NameServer.java b/src/prerna/semoss/web/services/local/NameServer.java index 2a2838c7..0dddbf12 100644 --- a/src/prerna/semoss/web/services/local/NameServer.java +++ b/src/prerna/semoss/web/services/local/NameServer.java @@ -145,7 +145,9 @@ public Response downloadFile(@QueryParam("insightId") String insightId, @QueryPa String exportName = FilenameUtils.getName(filePath); return Response.status(200).entity(exportFile) - .header("Content-Disposition", "attachment; filename=\"" + exportName + "\"").build(); + .header("Content-Disposition", + WebUtility.responseHeaderValue("attachment; filename=\"" + exportName + "\"")) + .build(); } catch (Exception e) { Map errorMap = new HashMap<>(); errorMap.put(Constants.ERROR_MESSAGE, e.getMessage()); diff --git a/src/prerna/semoss/web/services/local/ProjectResource.java b/src/prerna/semoss/web/services/local/ProjectResource.java index c8e1cf84..ee502fca 100644 --- a/src/prerna/semoss/web/services/local/ProjectResource.java +++ b/src/prerna/semoss/web/services/local/ProjectResource.java @@ -761,7 +761,7 @@ public Response downloadProjectImage(@Context final Request coreRequest, @Contex EntityTag etag = new EntityTag(Integer.toHexString(exportFile.getAbsolutePath().hashCode()) + "-" + exportFile.lastModified() + "-" + exportFile.length()); return CatalogImageResponse.withBrowserCache(coreRequest, Response.ok(exportFile) - .header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build()); + .header("Content-Disposition", WebUtility.responseHeaderValue("attachment; filename=" + exportName)).tag(etag).build()); } else { Map errorMap = new HashMap<>(); errorMap.put(Constants.ERROR_MESSAGE, "error sending image file"); @@ -869,7 +869,7 @@ public Response downloadInsightImage(@Context final Request coreRequest, @Contex } return CatalogImageResponse.withContentType(Response.ok(exportFile) - .header("Content-Disposition", "attachment; filename=" + exportName).tag(etag).build()); + .header("Content-Disposition", WebUtility.responseHeaderValue("attachment; filename=" + exportName)).tag(etag).build()); } else { Map errorMap = new HashMap<>(); errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file"); diff --git a/src/prerna/semoss/web/services/local/SessionResource.java b/src/prerna/semoss/web/services/local/SessionResource.java index afceb683..01ebd2d6 100644 --- a/src/prerna/semoss/web/services/local/SessionResource.java +++ b/src/prerna/semoss/web/services/local/SessionResource.java @@ -250,7 +250,7 @@ public void invalidateSession(@Context HttpServletRequest request, @Context Http String customUrl = DBLoader.getCustomLogoutUrl(); if (customUrl != null && !customUrl.isEmpty()) { - response.setHeader("redirect", customUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(customUrl)); response.sendError(302, "Need to redirect to " + customUrl); } else { String scheme = WebUtility.inputSQLSanitizer(request.getScheme()); // http @@ -270,7 +270,7 @@ public void invalidateSession(@Context HttpServletRequest request, @Context Http } redirectUrl += contextPath + "/logout/"; redirectUrl = WebUtility.cleanHttpResponse(redirectUrl); - response.setHeader("redirect", redirectUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); response.sendError(302, "Need to redirect to " + redirectUrl); } } else { @@ -278,7 +278,7 @@ public void invalidateSession(@Context HttpServletRequest request, @Context Http redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request); String encodedRedirectUrl = Encode.forHtml(redirectUrl); - response.setHeader("redirect", encodedRedirectUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl)); response.sendError(302, "Need to redirect to " + encodedRedirectUrl); } diff --git a/src/prerna/semoss/web/services/local/UserResource.java b/src/prerna/semoss/web/services/local/UserResource.java index 566f0555..391016a7 100644 --- a/src/prerna/semoss/web/services/local/UserResource.java +++ b/src/prerna/semoss/web/services/local/UserResource.java @@ -99,6 +99,7 @@ import prerna.util.linotp.LinOTPUtil; import prerna.web.conf.DBLoader; import prerna.web.conf.UserSessionLoader; +import prerna.web.services.util.RedirectUtility; import prerna.web.services.util.WebUtility; import waffle.servlet.WindowsPrincipal; @@ -243,7 +244,7 @@ public Response logout(@PathParam("provider") String provider, String customUrl = DBLoader.getCustomLogoutUrl(); if (customUrl != null && !customUrl.isEmpty()) { - response.setHeader("redirect", customUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(customUrl)); response.sendError(302, "Need to redirect to " + customUrl); } else { String redirectUrl = WebUtility.inputSanitizer(request.getHeader("referer")); @@ -262,12 +263,12 @@ public Response logout(@PathParam("provider") String provider, redirectUrl += ":" + serverPort; } redirectUrl += contextPath + "/logout/"; - response.setHeader("redirect", redirectUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); response.sendError(302, "Need to redirect to " + redirectUrl); } else { redirectUrl = redirectUrl + WebUtility.determineLoginExtension(request); String encodedRedirectUrl = Encode.forHtml(redirectUrl); - response.setHeader("redirect", encodedRedirectUrl); + response.setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl)); response.sendError(302, "Need to redirect to " + encodedRedirectUrl); } } @@ -434,7 +435,8 @@ public Response userinfoGeneric(@PathParam("provider") String provider, @Context */ private HttpSession initializeOAuthLoginSession(HttpServletRequest request) { HttpSession session = request.getSession(false); - String customRedirect = WebUtility.cleanHttpResponse(request.getParameter("redirect")); + String customRedirect = RedirectUtility.allowedReturnUrl(request, + WebUtility.cleanHttpResponse(request.getParameter("redirect"))); if (customRedirect != null && !customRedirect.isEmpty()) { if (session == null) { session = request.getSession(); @@ -1958,18 +1960,20 @@ private void setMainPageRedirect(@Context HttpServletRequest request, @Context H // otherwise, we send them back to the FE HttpSession session = request.getSession(); + // the redirect can come from the request or the session, only return to an allowed destination + customRedirect = RedirectUtility.allowedReturnUrl(request, customRedirect); boolean useCustom = customRedirect != null && !customRedirect.isEmpty(); boolean endpoint = session.getAttribute(Constants.ENDPOINT_REDIRECT_KEY) != null; response.setStatus(302); try { addSessionCookieHeader(request, response, session); if (useCustom) { - response.addHeader("redirect", customRedirect); + response.addHeader("redirect", WebUtility.responseHeaderValue(customRedirect)); String encodedCustomRedirect = Encode.forHtml(customRedirect); response.sendError(302, "Need to redirect to " + encodedCustomRedirect); } else if (endpoint) { String redirectUrl = session.getAttribute(Constants.ENDPOINT_REDIRECT_KEY) + ""; - response.addHeader("redirect", redirectUrl); + response.addHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); response.sendError(302, "Need to redirect to " + redirectUrl); } else { response.sendRedirect(socialData.getProperty("redirect")); @@ -1994,7 +1998,7 @@ private void addSessionCookieHeader(HttpServletRequest request, HttpServletRespo + ((ClusterUtil.IS_CLUSTER || secureRequest) ? ("; Secure; SameSite=" + Utility.getSameSiteCookieValue()) : ""); - response.addHeader("Set-Cookie", setCookieString); + response.addHeader("Set-Cookie", WebUtility.responseHeaderValue(setCookieString)); } ////////////////////////////////////////////////////////////////////// diff --git a/src/prerna/semoss/web/services/saml/IdpSSOServlet.java b/src/prerna/semoss/web/services/saml/IdpSSOServlet.java index 3bc76c66..a1288637 100644 --- a/src/prerna/semoss/web/services/saml/IdpSSOServlet.java +++ b/src/prerna/semoss/web/services/saml/IdpSSOServlet.java @@ -44,6 +44,7 @@ import prerna.util.Constants; import prerna.util.Utility; import prerna.web.conf.util.SSOUtil; +import prerna.web.services.util.RedirectUtility; import prerna.web.services.util.WebUtility; /** @@ -104,6 +105,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) response.sendError(HttpServletResponse.SC_FORBIDDEN, " Provided redirect is unauthorized"); return; } + // only return to this host, the configured UI or an allow-listed origin + if (RedirectUtility.allowedReturnUrl(request, redirect) == null) { + response.sendError(HttpServletResponse.SC_FORBIDDEN, " Provided redirect is unauthorized"); + return; + } } // if already logged in diff --git a/src/prerna/web/conf/AccountLockedFilter.java b/src/prerna/web/conf/AccountLockedFilter.java index d32f7123..d7162d20 100644 --- a/src/prerna/web/conf/AccountLockedFilter.java +++ b/src/prerna/web/conf/AccountLockedFilter.java @@ -76,7 +76,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 // we redirect to the index.html page where we have pushed the admin page String redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + SET_ACCOUNT_LOCKED_HTML; - ((HttpServletResponse) arg1).setHeader("redirect", redirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Redirect required"); return; } diff --git a/src/prerna/web/conf/MemoryCheckFilter.java b/src/prerna/web/conf/MemoryCheckFilter.java index 65b37798..395bab43 100644 --- a/src/prerna/web/conf/MemoryCheckFilter.java +++ b/src/prerna/web/conf/MemoryCheckFilter.java @@ -97,7 +97,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 // we redirect to the index.html page where we have pushed the admin page String redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + NO_MORE_MEMORY; - ((HttpServletResponse) arg1).setHeader("redirect", redirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Redirect required"); return; } diff --git a/src/prerna/web/conf/NoUserInSessionFilter.java b/src/prerna/web/conf/NoUserInSessionFilter.java index fd2d0261..f9281b0e 100644 --- a/src/prerna/web/conf/NoUserInSessionFilter.java +++ b/src/prerna/web/conf/NoUserInSessionFilter.java @@ -46,6 +46,7 @@ import prerna.util.Constants; import prerna.util.SocialPropertiesUtil; import prerna.util.openshell.OpenShellUserSandboxes; +import prerna.web.services.util.RedirectUtility; import prerna.web.services.util.WebUtility; public class NoUserInSessionFilter implements Filter { @@ -160,15 +161,15 @@ private void setInvalidEntryRedirect(ServletContext context, ServletRequest arg0 if (loginRedirect != null) { ((HttpServletResponse) arg1).sendRedirect(loginRedirect); } else { - String contextPath = context.getContextPath(); - redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + NO_USER_HTML; - ((HttpServletResponse) arg1).sendRedirect(redirectUrl); + // own context page, relative so no host is taken from the request + RedirectUtility.sendLocalRedirect((HttpServletResponse) arg1, context.getContextPath() + NO_USER_HTML, + HttpServletResponse.SC_MOVED_TEMPORARILY); } } else { // are we in public home - if no, we dont include ! in the redirect redirectUrl = redirectUrl + WebUtility.determineLoginExtension((HttpServletRequest) arg0); String encodedRedirectUrl = Encode.forHtml(redirectUrl); - ((HttpServletResponse) arg1).setHeader("redirect", encodedRedirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Need to redirect to " + encodedRedirectUrl); // invalidate the session if necessary diff --git a/src/prerna/web/conf/SSOFilter.java b/src/prerna/web/conf/SSOFilter.java index d656a403..8f21d3c8 100644 --- a/src/prerna/web/conf/SSOFilter.java +++ b/src/prerna/web/conf/SSOFilter.java @@ -53,6 +53,7 @@ import prerna.web.conf.util.CACTrackingUtil; import prerna.web.conf.util.SSOUtil; import prerna.web.conf.util.UserFileLogUtil; +import prerna.web.services.util.RedirectUtility; import prerna.web.services.util.WebUtility; /** @@ -148,8 +149,10 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha Utility.cleanLogString(fullUrl)); redirectAfterLogin = fullUrl; } else if (referer != null) { - classLogger.info("Setting session redirect value to referer = {}", Utility.cleanLogString(referer)); - redirectAfterLogin = referer; + // the referer is attacker controllable, only return to an allowed destination + redirectAfterLogin = RedirectUtility.allowedReturnUrl((HttpServletRequest) request, referer); + classLogger.info("Setting session redirect value to referer = {}", + Utility.cleanLogString(String.valueOf(redirectAfterLogin))); } else { classLogger.info("No session redirect value found..."); redirectAfterLogin = null; @@ -198,8 +201,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha // 1) configured external login URL, or // 2) internal SAML login page that routes into IdpSSOServlet/SPSSOServlet. if (loginUrl != null && !(loginUrl = loginUrl.trim()).isEmpty()) { - ((HttpServletResponse) response).setHeader("redirect", loginUrl); - ((HttpServletResponse) response).setHeader("location", loginUrl); + ((HttpServletResponse) response).setHeader("redirect", WebUtility.responseHeaderValue(loginUrl)); + ((HttpServletResponse) response).setHeader("location", WebUtility.responseHeaderValue(loginUrl)); ((HttpServletResponse) response).sendError(302, "Need to redirect to " + loginUrl); } else { // if no login url defined @@ -207,9 +210,9 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha // we redirect to the index.html page specifically created for the SAML call. String redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + loginPath; - ((HttpServletResponse) response).setHeader("redirect", redirectUrl); + ((HttpServletResponse) response).setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); if (addLocation) { - ((HttpServletResponse) response).setHeader("location", redirectUrl); + ((HttpServletResponse) response).setHeader("location", WebUtility.responseHeaderValue(redirectUrl)); } ((HttpServletResponse) response).sendError(302, "Redirect required"); } diff --git a/src/prerna/web/conf/SessionCounterExceededFilter.java b/src/prerna/web/conf/SessionCounterExceededFilter.java index 0ad5ff21..2c843083 100644 --- a/src/prerna/web/conf/SessionCounterExceededFilter.java +++ b/src/prerna/web/conf/SessionCounterExceededFilter.java @@ -108,7 +108,7 @@ private static synchronized int performCheck(HttpSession session, ServletRequest // we redirect to the index.html page where we have pushed the admin page String redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + FAIL_HTML; - ((HttpServletResponse) arg1).setHeader("redirect", redirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Redirect required"); return -1; } diff --git a/src/prerna/web/conf/ShareSessionFilter.java b/src/prerna/web/conf/ShareSessionFilter.java index f5fbe6a0..a861d185 100644 --- a/src/prerna/web/conf/ShareSessionFilter.java +++ b/src/prerna/web/conf/ShareSessionFilter.java @@ -51,6 +51,7 @@ import prerna.semoss.web.services.local.UserResource; import prerna.util.Constants; import prerna.util.Utility; +import prerna.web.services.util.RedirectUtility; import prerna.web.services.util.WebUtility; public class ShareSessionFilter implements Filter { @@ -63,10 +64,6 @@ public class ShareSessionFilter implements Filter { public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { - // this will be the full path of the request - // like http://localhost:8080/Monolith_Dev/api/engine/runPixel - - String fullUrl = WebUtility.cleanHttpResponse(((HttpServletRequest) arg0).getRequestURL().toString()); String contextPath = ((HttpServletRequest) arg0).getContextPath(); // due to FE being annoying @@ -172,30 +169,26 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 // and now redirect back to the URL // if get, we can do it String method = req.getMethod(); - if (method.equalsIgnoreCase("GET")) { + // the redirect is a path on the origin the browser used, never a host from the request + String redirectPath = req.getRequestURI(); + if (method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("POST")) { // modify the prefix if necessary Map envMap = System.getenv(); if (envMap.containsKey(Constants.MONOLITH_PREFIX)) { - fullUrl = fullUrl.replace(contextPath, envMap.get(Constants.MONOLITH_PREFIX)); + redirectPath = redirectPath.replace(contextPath, envMap.get(Constants.MONOLITH_PREFIX)); } - - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); + } + if (method.equalsIgnoreCase("GET")) { String newQueryString = removeQueryParam(currentQueryString, SHARE_TOKEN_KEY); if (newQueryString != null && !newQueryString.isEmpty()) { - ((HttpServletResponse) arg1).sendRedirect(fullUrl + "?" + newQueryString); - } else { - ((HttpServletResponse) arg1).sendRedirect(fullUrl); + redirectPath = redirectPath + "?" + newQueryString; } + RedirectUtility.sendLocalRedirect((HttpServletResponse) arg1, redirectPath, + HttpServletResponse.SC_MOVED_TEMPORARILY); return; } else if (method.equalsIgnoreCase("POST")) { - // modify the prefix if necessary - Map envMap = System.getenv(); - if (envMap.containsKey(Constants.MONOLITH_PREFIX)) { - fullUrl = fullUrl.replace(contextPath, envMap.get(Constants.MONOLITH_PREFIX)); - } - - ((HttpServletResponse) arg1).setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); - ((HttpServletResponse) arg1).setHeader("Location", fullUrl); + RedirectUtility.sendLocalRedirect((HttpServletResponse) arg1, redirectPath, + HttpServletResponse.SC_TEMPORARY_REDIRECT); return; } } diff --git a/src/prerna/web/conf/StartUpSuccessFilter.java b/src/prerna/web/conf/StartUpSuccessFilter.java index ee9bc858..9187d9f5 100644 --- a/src/prerna/web/conf/StartUpSuccessFilter.java +++ b/src/prerna/web/conf/StartUpSuccessFilter.java @@ -95,7 +95,7 @@ private void filterRequest(ServletContext context, ServletRequest request, Servl // we redirect to the index.html page where we have pushed the admin page String redirectUrl = fullUrl.substring(0, fullUrl.indexOf(contextPath) + contextPath.length()) + FAIL_HTML; - ((HttpServletResponse) response).setHeader("redirect", redirectUrl); + ((HttpServletResponse) response).setHeader("redirect", WebUtility.responseHeaderValue(redirectUrl)); ((HttpServletResponse) response).sendError(302, "Redirect required"); return; } diff --git a/src/prerna/web/conf/UserExistsFilter.java b/src/prerna/web/conf/UserExistsFilter.java index 179d8075..3e9b92c7 100644 --- a/src/prerna/web/conf/UserExistsFilter.java +++ b/src/prerna/web/conf/UserExistsFilter.java @@ -50,6 +50,7 @@ import prerna.semoss.web.services.local.ResourceUtility; import prerna.usertracking.AuditErrorCode; import prerna.util.Constants; +import prerna.web.services.util.WebUtility; public class UserExistsFilter extends NoUserInSessionFilter { @@ -76,7 +77,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 String redirectUrl = ((HttpServletRequest) arg0).getHeader("referer"); redirectUrl = redirectUrl + "#!/login"; String encodedRedirectUrl = Encode.forHtml(redirectUrl); - ((HttpServletResponse) arg1).setHeader("redirect", encodedRedirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Need to redirect to " + encodedRedirectUrl); return; } else { @@ -107,7 +108,7 @@ public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2 String redirectUrl = ((HttpServletRequest) arg0).getHeader("referer"); redirectUrl = redirectUrl + "#!/login"; String encodedRedirectUrl = Encode.forHtml(redirectUrl); - ((HttpServletResponse) arg1).setHeader("redirect", encodedRedirectUrl); + ((HttpServletResponse) arg1).setHeader("redirect", WebUtility.responseHeaderValue(encodedRedirectUrl)); ((HttpServletResponse) arg1).sendError(302, "Need to redirect to " + encodedRedirectUrl); // log the user login diff --git a/src/prerna/web/services/util/RedirectUtility.java b/src/prerna/web/services/util/RedirectUtility.java new file mode 100644 index 00000000..a55dfda6 --- /dev/null +++ b/src/prerna/web/services/util/RedirectUtility.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * Copyright 2015 Defense Health Agency (DHA) + * + * If your use of this software does not include any GPLv2 components: + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ---------------------------------------------------------------------------- + * If your use of this software includes any GPLv2 components: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + *******************************************************************************/ +package prerna.web.services.util; + +import java.io.IOException; +import java.net.URI; +import java.util.Locale; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import prerna.util.Constants; +import prerna.util.SocialPropertiesUtil; +import prerna.util.Utility; + +public final class RedirectUtility { + + private static final Logger classLogger = LogManager.getLogger(RedirectUtility.class); + + private RedirectUtility() { + } + + // returns the target when a browser may be sent there after login, otherwise null (and logs the denial) + // allowed: relative paths, this host, the social.properties "redirect" origin, + // social.properties "redirect_allowed_origins" (comma separated origins), or a WHITE_LIST_DOMAINS domain + public static String allowedReturnUrl(HttpServletRequest request, String target) { + if (target == null || target.isEmpty()) { + return null; + } + if (!isAllowed(request, target)) { + classLogger.warn("Refusing redirect to a destination that is not allowed: {}", Utility.cleanLogString(target)); + return null; + } + return target; + } + + // redirect to a path on the origin the browser used, never to a host taken from the request + public static void sendLocalRedirect(HttpServletResponse response, String pathAndQuery, int status) + throws IOException { + String target = WebUtility.responseHeaderValue(pathAndQuery); + // a leading // or /\ would be a network-path reference to another host + target = "/" + target.replaceFirst("^[/\\\\]+", ""); + if (status == HttpServletResponse.SC_MOVED_TEMPORARILY) { + response.sendRedirect(target); + } else { + response.setStatus(status); + response.setHeader("Location", target); + } + } + + private static boolean isAllowed(HttpServletRequest request, String target) { + if (target.indexOf('\\') >= 0 || target.chars().anyMatch(c -> c <= 0x20 || c == 0x7f)) { + return false; + } + URI uri; + try { + uri = URI.create(target); + } catch (IllegalArgumentException e) { + return false; + } + if (!uri.isAbsolute()) { + // relative reference, but not a network-path one (//host) + return uri.getRawAuthority() == null && !target.startsWith("//"); + } + String scheme = uri.getScheme().toLowerCase(Locale.ROOT); + if (!(scheme.equals("http") || scheme.equals("https")) || uri.getHost() == null || uri.getRawUserInfo() != null) { + return false; + } + // same host, proxies commonly change the scheme and port + if (request != null && uri.getHost().equalsIgnoreCase(request.getServerName())) { + return true; + } + SocialPropertiesUtil social = SocialPropertiesUtil.getInstance(); + if (matchesOrigin(uri, social.getProperty("redirect"))) { + return true; + } + String extra = social.getProperty("redirect_allowed_origins"); + if (extra != null) { + for (String origin : extra.split(",")) { + if (matchesOrigin(uri, origin)) { + return true; + } + } + } + // an explicit domain whitelist stays a valid way to allow other hosts + String whiteList = Utility.getDIHelperProperty(Constants.WHITE_LIST_DOMAINS); + if (whiteList != null && !whiteList.trim().isEmpty()) { + try { + WebUtility.checkIfValidDomain(target); + return true; + } catch (IllegalArgumentException | IllegalStateException e) { + return false; + } + } + return false; + } + + private static boolean matchesOrigin(URI uri, String configured) { + if (configured == null || configured.isBlank()) { + return false; + } + try { + URI other = URI.create(configured.trim()); + return other.getHost() != null && origin(uri).equals(origin(other)); + } catch (IllegalArgumentException e) { + return false; + } + } + + private static String origin(URI uri) { + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + int port = uri.getPort() != -1 ? uri.getPort() : ("https".equals(scheme) ? 443 : 80); + return scheme + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } +} diff --git a/src/prerna/web/services/util/WebUtility.java b/src/prerna/web/services/util/WebUtility.java index 79b7cc9b..58cfc4c9 100644 --- a/src/prerna/web/services/util/WebUtility.java +++ b/src/prerna/web/services/util/WebUtility.java @@ -298,7 +298,7 @@ public static Response getResponse(Object vec, int status, List addHea if (addHeaders != null && !addHeaders.isEmpty()) { for (int i = 0; i < addHeaders.size(); i++) { String[] headerInfo = addHeaders.get(i); - builder.header(headerInfo[0], headerInfo[1]); + builder.header(responseHeaderValue(headerInfo[0]), responseHeaderValue(headerInfo[1])); } } if (cookies != null && cookies.length > 0) { @@ -308,7 +308,7 @@ public static Response getResponse(Object vec, int status, List addHea for (NewCookie cookie : cookies) { // add the cookie to the header // with the SameSite Strict tag - builder.header("Set-Cookie", convertCookieToHeader(cookie)); + builder.header("Set-Cookie", responseHeaderValue(convertCookieToHeader(cookie))); } } return builder.build(); @@ -445,6 +445,11 @@ public void write(OutputStream outputStream) throws IOException, WebApplicationE return null; } + // strips CR/LF/NUL from a response header value without HTML-encoding it + public static String responseHeaderValue(String value) { + return value == null ? null : value.replace("\r", "").replace("\n", "").replace("\0", ""); + } + /** * Ensure no CRLF injection into responses for malicious attacks. Replaces * newline, carriage-return, tab, and their URL-encoded forms with underscores, From 5c1134deb4f2367e61d621498a71540ed04c597c Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 11:37:33 -0500 Subject: [PATCH 3/4] fix(security): apply review feedback on redirect and upload checks - one redirect policy in IdpSSOServlet (drop the second domain check) - RedirectUtility: same origin instead of same host, also the application url; null-safe social.properties reads; strip all control characters (tab) and always set a root-relative Location - check redirect params and the referer raw instead of html-encoded - SamlVerifierServlet follows RelayState only to an allowed destination - uploads: normalize before the containment check and refuse . and .. names - update the filter and SAML tests for root-relative redirects --- .../web/services/local/UserResource.java | 13 ++++-- .../web/services/saml/IdpSSOServlet.java | 9 +--- .../services/saml/SamlVerifierServlet.java | 4 +- src/prerna/upload/FileUploader.java | 14 +++++- src/prerna/web/conf/SSOFilter.java | 3 +- .../web/services/util/RedirectUtility.java | 46 +++++++++++++------ .../saml/SamlVerifierServletTest.java | 7 ++- .../web/conf/NoUserInSessionFilterTest.java | 8 ++-- test/prerna/web/conf/SSOFilterTest.java | 4 ++ .../web/conf/ShareSessionFilterTest.java | 14 ++++-- 10 files changed, 84 insertions(+), 38 deletions(-) diff --git a/src/prerna/semoss/web/services/local/UserResource.java b/src/prerna/semoss/web/services/local/UserResource.java index 391016a7..6e8b663f 100644 --- a/src/prerna/semoss/web/services/local/UserResource.java +++ b/src/prerna/semoss/web/services/local/UserResource.java @@ -435,8 +435,8 @@ public Response userinfoGeneric(@PathParam("provider") String provider, @Context */ private HttpSession initializeOAuthLoginSession(HttpServletRequest request) { HttpSession session = request.getSession(false); - String customRedirect = RedirectUtility.allowedReturnUrl(request, - WebUtility.cleanHttpResponse(request.getParameter("redirect"))); + // checked raw: html-encoding first would corrupt valid urls, and the check refuses control characters + String customRedirect = RedirectUtility.allowedReturnUrl(request, request.getParameter("redirect")); if (customRedirect != null && !customRedirect.isEmpty()) { if (session == null) { session = request.getSession(); @@ -1352,7 +1352,8 @@ public Response loginNative(@Context HttpServletRequest request, @Context HttpSe try { String username = WebUtility.inputSQLSanitizer(request.getParameter("username")); String password = WebUtility.inputSQLSanitizer(request.getParameter("password")); - String redirect = WebUtility.cleanHttpResponse(request.getParameter("redirect")); + // validated raw in setMainPageRedirect + String redirect = request.getParameter("redirect"); // so that the default is to redirect Boolean disableRedirect = Boolean.parseBoolean(request.getParameter("disableRedirect") + ""); @@ -1589,7 +1590,8 @@ public Response loginLinOTP(@Context HttpServletRequest request, @Context HttpSe return WebUtility.getResponse(returnMap, 400); } - String redirect = WebUtility.cleanHttpResponse(request.getParameter("redirect")); + // validated raw in setMainPageRedirect + String redirect = request.getParameter("redirect"); // so that the default is to redirect Boolean disableRedirect = Boolean.parseBoolean(request.getParameter("disableRedirect") + ""); boolean autoAdd = Boolean.parseBoolean(socialData.getProperty("linotp_auto_add", "true")); @@ -1937,7 +1939,8 @@ public synchronized Response getAllLoginProperties(@Context HttpServletRequest r * @param response outbound HTTP response */ private void setMainPageRedirect(@Context HttpServletRequest request, @Context HttpServletResponse response) { - String customRedirect = WebUtility.cleanHttpResponse(request.getParameter("redirect")); + // validated raw in setMainPageRedirect(request, response, customRedirect) + String customRedirect = request.getParameter("redirect"); if (customRedirect == null || customRedirect.isEmpty()) { customRedirect = (String) request.getSession().getAttribute(CUSTOM_REDIRECT_SESSION_KEY); // also remove the attribute so additional logins dont do the redirect as well diff --git a/src/prerna/semoss/web/services/saml/IdpSSOServlet.java b/src/prerna/semoss/web/services/saml/IdpSSOServlet.java index a1288637..d6d34b32 100644 --- a/src/prerna/semoss/web/services/saml/IdpSSOServlet.java +++ b/src/prerna/semoss/web/services/saml/IdpSSOServlet.java @@ -45,7 +45,6 @@ import prerna.util.Utility; import prerna.web.conf.util.SSOUtil; import prerna.web.services.util.RedirectUtility; -import prerna.web.services.util.WebUtility; /** * Handles the IdP-initiated login entry point. @@ -99,13 +98,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) String redirect = request.getParameter("redirect"); boolean hasRedirect = (redirect != null && !(redirect = redirect.trim()).isEmpty()); if (hasRedirect) { - try { - WebUtility.checkIfValidDomain(redirect); - } catch (IllegalArgumentException | IllegalStateException e) { - response.sendError(HttpServletResponse.SC_FORBIDDEN, " Provided redirect is unauthorized"); - return; - } - // only return to this host, the configured UI or an allow-listed origin + // one policy: relative, this origin, the configured UI, redirect_allowed_origins or WHITE_LIST_DOMAINS if (RedirectUtility.allowedReturnUrl(request, redirect) == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN, " Provided redirect is unauthorized"); return; diff --git a/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java b/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java index 287b54bb..f01343fc 100644 --- a/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java +++ b/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java @@ -78,6 +78,7 @@ import prerna.util.Utility; import prerna.web.conf.AdminStartupFilter; import prerna.web.conf.util.SSOUtil; +import prerna.web.services.util.RedirectUtility; /** * Receives the SAML assertion callback from the IdP and finalizes login in this @@ -161,7 +162,8 @@ public void verifySamlOutput(HttpServletRequest request, HttpServletResponse res if ((relayUrl != null) && (relayUrl.length() != 0)) { // something special for validation to send redirect int stringPos = relayUrl.indexOf("sendRedirectForValidationNow=true"); - if (stringPos != -1) { + // RelayState is not signed, so only follow it to an allowed destination + if (stringPos != -1 && RedirectUtility.allowedReturnUrl(request, relayUrl) != null) { response.sendRedirect(relayUrl); return; } diff --git a/src/prerna/upload/FileUploader.java b/src/prerna/upload/FileUploader.java index 7974b06b..f937a958 100644 --- a/src/prerna/upload/FileUploader.java +++ b/src/prerna/upload/FileUploader.java @@ -889,11 +889,21 @@ private List> processFileItems(List fileItems, return retData; } - // the upload target must be a direct child of the upload folder + // the upload target must be a direct child of the upload folder; normalize first so the + // later write (which normalizes again) lands on exactly the path that was checked private static File containedUploadFile(String folder, String fileLocation) throws IOException { java.nio.file.Path root = Paths.get(WebUtility.normalizePath(folder)); Files.createDirectories(root); - return WebUtility.resolveWithin(root, FilenameUtils.getName(fileLocation)).toFile(); + String normalized = WebUtility.normalizePath(fileLocation); + String name = normalized == null ? null : FilenameUtils.getName(normalized); + if (!WebUtility.isSafePathSegment(name)) { + throw new IllegalArgumentException("Invalid upload file name"); + } + java.nio.file.Path target = WebUtility.resolveWithin(root, name); + if (!target.toString().equals(WebUtility.normalizePath(target.toString()))) { + throw new IllegalArgumentException("Invalid upload file name"); + } + return target.toFile(); } /** diff --git a/src/prerna/web/conf/SSOFilter.java b/src/prerna/web/conf/SSOFilter.java index 8f21d3c8..98e69b91 100644 --- a/src/prerna/web/conf/SSOFilter.java +++ b/src/prerna/web/conf/SSOFilter.java @@ -141,7 +141,8 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha // we need to store information in the session // so that we can properly come back to the referer once an admin has been added - String referer = WebUtility.cleanHttpResponse(((HttpServletRequest) request).getHeader("referer")); + // checked raw below: html-encoding first would corrupt valid urls + String referer = ((HttpServletRequest) request).getHeader("referer"); String redirectAfterLogin; if (isPortalUrl) { // Always return to the portal URL itself, not wherever the referer points diff --git a/src/prerna/web/services/util/RedirectUtility.java b/src/prerna/web/services/util/RedirectUtility.java index a55dfda6..170865fc 100644 --- a/src/prerna/web/services/util/RedirectUtility.java +++ b/src/prerna/web/services/util/RedirectUtility.java @@ -48,7 +48,7 @@ private RedirectUtility() { } // returns the target when a browser may be sent there after login, otherwise null (and logs the denial) - // allowed: relative paths, this host, the social.properties "redirect" origin, + // allowed: relative paths, this request's origin, the application url / social.properties "redirect" origin, // social.properties "redirect_allowed_origins" (comma separated origins), or a WHITE_LIST_DOMAINS domain public static String allowedReturnUrl(HttpServletRequest request, String target) { if (target == null || target.isEmpty()) { @@ -64,15 +64,13 @@ public static String allowedReturnUrl(HttpServletRequest request, String target) // redirect to a path on the origin the browser used, never to a host taken from the request public static void sendLocalRedirect(HttpServletResponse response, String pathAndQuery, int status) throws IOException { - String target = WebUtility.responseHeaderValue(pathAndQuery); + // browsers drop tabs and other control characters from urls, so strip all of them first + String target = pathAndQuery == null ? "" : pathAndQuery.replaceAll("[\\x00-\\x1f\\x7f]", ""); // a leading // or /\ would be a network-path reference to another host target = "/" + target.replaceFirst("^[/\\\\]+", ""); - if (status == HttpServletResponse.SC_MOVED_TEMPORARILY) { - response.sendRedirect(target); - } else { - response.setStatus(status); - response.setHeader("Location", target); - } + // set Location directly so the container never makes it absolute from the request host + response.setStatus(status); + response.setHeader("Location", target); } private static boolean isAllowed(HttpServletRequest request, String target) { @@ -93,15 +91,14 @@ private static boolean isAllowed(HttpServletRequest request, String target) { if (!(scheme.equals("http") || scheme.equals("https")) || uri.getHost() == null || uri.getRawUserInfo() != null) { return false; } - // same host, proxies commonly change the scheme and port - if (request != null && uri.getHost().equalsIgnoreCase(request.getServerName())) { + // same origin as this request, or the configured public application url (proxies) + if (request != null && request.getServerName() != null && origin(uri).equals(requestOrigin(request))) { return true; } - SocialPropertiesUtil social = SocialPropertiesUtil.getInstance(); - if (matchesOrigin(uri, social.getProperty("redirect"))) { + if (matchesOrigin(uri, applicationUrl()) || matchesOrigin(uri, socialProperty("redirect"))) { return true; } - String extra = social.getProperty("redirect_allowed_origins"); + String extra = socialProperty("redirect_allowed_origins"); if (extra != null) { for (String origin : extra.split(",")) { if (matchesOrigin(uri, origin)) { @@ -122,6 +119,29 @@ private static boolean isAllowed(HttpServletRequest request, String target) { return false; } + // social.properties may not be loaded (minimal installs, tests); treat that as not configured + private static String socialProperty(String key) { + try { + return SocialPropertiesUtil.getInstance().getProperty(key); + } catch (RuntimeException e) { + return null; + } + } + + private static String applicationUrl() { + try { + return Utility.getApplicationUrl(); + } catch (RuntimeException e) { + return null; + } + } + + private static String requestOrigin(HttpServletRequest request) { + String scheme = request.getScheme() == null ? "" : request.getScheme().toLowerCase(Locale.ROOT); + int port = request.getServerPort() > 0 ? request.getServerPort() : ("https".equals(scheme) ? 443 : 80); + return scheme + "://" + request.getServerName().toLowerCase(Locale.ROOT) + ":" + port; + } + private static boolean matchesOrigin(URI uri, String configured) { if (configured == null || configured.isBlank()) { return false; diff --git a/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java b/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java index 3c98eb60..6491531f 100644 --- a/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java +++ b/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java @@ -165,8 +165,13 @@ void handsARelayStateValidationBackWithoutSigningAnyoneIn() throws Exception { String relay = "https://semoss.example.com/SemossWeb/?sendRedirectForValidationNow=true"; statics.respond(assertion(attribute("uid", "u-1")), relay); HttpServletResponse resp = mock(HttpServletResponse.class); + // the relay state is only followed to an allowed destination, here this request's origin + HttpServletRequest req = request(mock(HttpSession.class)); + when(req.getScheme()).thenReturn("https"); + when(req.getServerName()).thenReturn("semoss.example.com"); + when(req.getServerPort()).thenReturn(443); - servlet(Map.of()).verifySamlOutput(request(mock(HttpSession.class)), resp); + servlet(Map.of()).verifySamlOutput(req, resp); verify(resp).sendRedirect(relay); statics.users.verifyNoInteractions(); diff --git a/test/prerna/web/conf/NoUserInSessionFilterTest.java b/test/prerna/web/conf/NoUserInSessionFilterTest.java index 6be39d15..ddd346d3 100644 --- a/test/prerna/web/conf/NoUserInSessionFilterTest.java +++ b/test/prerna/web/conf/NoUserInSessionFilterTest.java @@ -31,6 +31,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -155,7 +156,7 @@ void redirectsAPathThatOnlyStartsLikeAnApi() throws Exception { run(null, request, response, mock(FilterChain.class)); verify(response, never()).setStatus(401); - verify(response).sendRedirect(anyString()); + verify(response).setHeader(eq("Location"), anyString()); } @Test @@ -182,7 +183,8 @@ void redirectsAPathParameterThatEndsInAnOpenEndpoint() throws Exception { run(null, request, response, chain); - verify(response).sendRedirect(BASE + "/noUserFail/"); + // root-relative so the host never comes from the request + verify(response).setHeader("Location", "/Monolith/noUserFail/"); verify(chain, never()).doFilter(any(), any()); } @@ -196,7 +198,7 @@ void sendsADirectHitWithoutASessionToTheNoUserPage() throws Exception { run(null, request, response, mock(FilterChain.class)); verify(created).setAttribute(Constants.ENDPOINT_REDIRECT_KEY, BASE + "/api/engine/runPixel"); - verify(response).sendRedirect(BASE + "/noUserFail/"); + verify(response).setHeader("Location", "/Monolith/noUserFail/"); } @Test diff --git a/test/prerna/web/conf/SSOFilterTest.java b/test/prerna/web/conf/SSOFilterTest.java index d92ff1d2..3087a1e1 100644 --- a/test/prerna/web/conf/SSOFilterTest.java +++ b/test/prerna/web/conf/SSOFilterTest.java @@ -95,6 +95,10 @@ private HttpServletRequest signedOut(String url, String referer, String fetchDes when(context.getContextPath()).thenReturn("/Monolith"); when(request.getServletContext()).thenReturn(context); when(request.getRequestURL()).thenReturn(new StringBuffer(url)); + // the referer is only kept when it is on this request's origin (or another allowed one) + when(request.getScheme()).thenReturn("http"); + when(request.getServerName()).thenReturn("localhost"); + when(request.getServerPort()).thenReturn(8080); when(request.getHeader("referer")).thenReturn(referer); when(request.getHeader("Sec-Fetch-Dest")).thenReturn(fetchDest); when(request.getSession(true)).thenReturn(session); diff --git a/test/prerna/web/conf/ShareSessionFilterTest.java b/test/prerna/web/conf/ShareSessionFilterTest.java index dab22740..728fe1f6 100644 --- a/test/prerna/web/conf/ShareSessionFilterTest.java +++ b/test/prerna/web/conf/ShareSessionFilterTest.java @@ -34,6 +34,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.never; @@ -67,6 +68,8 @@ class ShareSessionFilterTest { private static final String URL = "http://localhost:8080/Monolith/api/engine/runPixel"; + // redirects are root-relative so the host never comes from the request + private static final String PATH = "/Monolith/api/engine/runPixel"; private HttpServletResponse response; private FilterChain chain; @@ -91,6 +94,7 @@ private static HttpServletRequest request(String method, String query, User user HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn(method); when(request.getRequestURL()).thenReturn(new StringBuffer(URL)); + when(request.getRequestURI()).thenReturn(PATH); when(request.getContextPath()).thenReturn("/Monolith"); when(request.getQueryString()).thenReturn(query); if (user != null) { @@ -179,7 +183,7 @@ void movesAGetOntoTheSharedSessionAndDropsTheToken() throws Exception { assertEquals("ROUTEID", cookies.get(2).getName()); assertEquals("route1", cookies.get(2).getValue()); verify(response).setStatus(302); - verify(response).sendRedirect(URL + "?insight=abc"); + verify(response).setHeader("Location", PATH + "?insight=abc"); verify(chain, never()).doFilter(any(), any()); } @@ -189,7 +193,8 @@ void redirectsAGetThatOnlyCarriedTheTokenToTheBareUrl() throws Exception { run(request, details(true, false), null); - verify(response).sendRedirect(URL); + verify(response).setStatus(302); + verify(response).setHeader("Location", PATH); } @Test @@ -199,7 +204,7 @@ void answersAPostWithATemporaryRedirect() throws Exception { run(request, details(true, false), null); verify(response).setStatus(307); - verify(response).setHeader("Location", URL); + verify(response).setHeader("Location", PATH); verify(chain, never()).doFilter(any(), any()); } @@ -212,6 +217,7 @@ void signsInWithAnAuthShareToken() throws Exception { assertTrue(passed() instanceof HttpServletRequestWrapper); verify(response, never()).addCookie(any()); verify(response, never()).sendRedirect(anyString()); + verify(response, never()).setHeader(eq("Location"), anyString()); } @Test @@ -241,6 +247,6 @@ void redirectsWithoutCookiesForATokenThatSharesNothing() throws Exception { run(request, details(false, false), null); verify(response, never()).addCookie(any()); - verify(response).sendRedirect(URL); + verify(response).setHeader("Location", PATH); } } From 7053b30119a49df04fba53a136c5c61c907b3eb1 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 12:06:19 -0500 Subject: [PATCH 4/4] fix(upload): compare upload paths as paths and keep one normalized name - containedUploadFile compares Path values, so Windows separators no longer reject every upload - the client file name is reduced to its base name and normalized before the uniqueness check; the reply uses the name actually written - SamlVerifierServlet sends the stored redirect without html-encoding it, so deep links keep their query strings --- .../web/services/saml/SamlVerifierServlet.java | 7 +++++-- src/prerna/upload/FileUploader.java | 17 ++++++++++++----- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java b/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java index f01343fc..13023a8f 100644 --- a/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java +++ b/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java @@ -79,6 +79,7 @@ import prerna.web.conf.AdminStartupFilter; import prerna.web.conf.util.SSOUtil; import prerna.web.services.util.RedirectUtility; +import prerna.web.services.util.WebUtility; /** * Receives the SAML assertion callback from the IdP and finalizes login in this @@ -247,8 +248,10 @@ public void verifySamlOutput(HttpServletRequest request, HttpServletResponse res // Complete the SSO transaction by returning the user to their original target. String encodedRedirectUrl = Encode.forHtml(originalRedirect); AdminStartupFilter.setSuccessfulRedirectUrl(encodedRedirectUrl); - response.setHeader("redirect", encodedRedirectUrl); - response.sendRedirect(encodedRedirectUrl); + // the stored value was checked when it was saved; html-encoding it here would break query strings + String redirectHeader = WebUtility.responseHeaderValue(originalRedirect); + response.setHeader("redirect", redirectHeader); + response.sendRedirect(redirectHeader); } catch (SAML2Exception | IOException | SessionException | ServletException sme) { classLogger.error("Failed to process SAML verification response.", sme); diff --git a/src/prerna/upload/FileUploader.java b/src/prerna/upload/FileUploader.java index f937a958..d8baa276 100644 --- a/src/prerna/upload/FileUploader.java +++ b/src/prerna/upload/FileUploader.java @@ -842,6 +842,12 @@ private List> processFileItems(List fileItems, // Check for viruses on upload checkForViruses(fi); + // normalize the name first so the uniqueness check, the write and the reply use the same name + String baseName = name == null ? null : FilenameUtils.getName(name); + name = baseName == null ? null : WebUtility.normalizePath(baseName); + if (!WebUtility.isSafePathSegment(name)) { + throw new IllegalArgumentException("Invalid upload file name"); + } String fileLocation = Utility.getUniqueFilePath(filePath, name); File file = containedUploadFile(filePath, fileLocation); @@ -849,7 +855,7 @@ private List> processFileItems(List fileItems, // we will do what a normal OS system does writeFile(fi, file); - String savedName = FilenameUtils.getName(fileLocation); + String savedName = file.getName(); Map fileMap = new HashMap(); fileMap.put("fileName", savedName); if (fePath.endsWith(DIR_SEPARATOR)) { @@ -872,7 +878,7 @@ private List> processFileItems(List fileItems, writeFile(fi, file); classLogger.info("Saved Pasted Data To {}", Utility.cleanLogString(file.toString())); - String savedName = FilenameUtils.getName(fileLocation); + String savedName = file.getName(); Map fileMap = new HashMap(); fileMap.put("fileName", savedName); if (fePath.endsWith(DIR_SEPARATOR)) { @@ -889,8 +895,8 @@ private List> processFileItems(List fileItems, return retData; } - // the upload target must be a direct child of the upload folder; normalize first so the - // later write (which normalizes again) lands on exactly the path that was checked + // the upload target must be a direct child of the upload folder, and the binary write + // (which normalizes the path again) must land on exactly the path that was checked private static File containedUploadFile(String folder, String fileLocation) throws IOException { java.nio.file.Path root = Paths.get(WebUtility.normalizePath(folder)); Files.createDirectories(root); @@ -900,7 +906,8 @@ private static File containedUploadFile(String folder, String fileLocation) thro throw new IllegalArgumentException("Invalid upload file name"); } java.nio.file.Path target = WebUtility.resolveWithin(root, name); - if (!target.toString().equals(WebUtility.normalizePath(target.toString()))) { + // compare as paths so Windows separators do not matter + if (!Paths.get(WebUtility.normalizePath(target.toString())).equals(target)) { throw new IllegalArgumentException("Invalid upload file name"); } return target.toFile();