diff --git a/WebContent/samlLogin/index.html b/WebContent/samlLogin/index.html index 887dbc00f..c32ffc3c9 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 100cd1623..f5ef66be1 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 61a4ec76a..d3ac3f065 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 2a2838c7b..0dddbf12b 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 c8e1cf845..ee502fcab 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 afceb6837..01ebd2d64 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 566f0555f..6e8b663fe 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")); + // 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(); @@ -1350,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") + ""); @@ -1587,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")); @@ -1935,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 @@ -1958,18 +1963,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 +2001,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 3bc76c662..d6d34b320 100644 --- a/src/prerna/semoss/web/services/saml/IdpSSOServlet.java +++ b/src/prerna/semoss/web/services/saml/IdpSSOServlet.java @@ -44,7 +44,7 @@ import prerna.util.Constants; import prerna.util.Utility; import prerna.web.conf.util.SSOUtil; -import prerna.web.services.util.WebUtility; +import prerna.web.services.util.RedirectUtility; /** * Handles the IdP-initiated login entry point. @@ -98,9 +98,8 @@ 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) { + // 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 287b54bba..13023a8fa 100644 --- a/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java +++ b/src/prerna/semoss/web/services/saml/SamlVerifierServlet.java @@ -78,6 +78,8 @@ import prerna.util.Utility; 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 @@ -161,7 +163,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; } @@ -245,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 a391983ad..d8baa276a 100644 --- a/src/prerna/upload/FileUploader.java +++ b/src/prerna/upload/FileUploader.java @@ -842,14 +842,20 @@ 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 = new File(WebUtility.normalizePath(fileLocation)); + File file = containedUploadFile(filePath, fileLocation); // instead of adding unique // 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)) { @@ -868,11 +874,11 @@ 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())); - String savedName = FilenameUtils.getName(fileLocation); + String savedName = file.getName(); Map fileMap = new HashMap(); fileMap.put("fileName", savedName); if (fePath.endsWith(DIR_SEPARATOR)) { @@ -889,6 +895,24 @@ private List> processFileItems(List fileItems, return retData; } + // 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); + 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); + // 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(); + } + /** * Checks a file for viruses. * diff --git a/src/prerna/web/conf/AccountLockedFilter.java b/src/prerna/web/conf/AccountLockedFilter.java index d32f71238..d7162d204 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 65b377980..395bab439 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 fd2d0261b..f9281b0ee 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 d656a403b..98e69b914 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; /** @@ -140,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 @@ -148,8 +150,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 +202,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 +211,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 0ad5ff219..2c8430831 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 f5fbe6a0a..a861d185d 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 ee9bc8583..9187d9f53 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 179d8075b..3e9b92c7d 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 000000000..170865fc0 --- /dev/null +++ b/src/prerna/web/services/util/RedirectUtility.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * 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 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()) { + 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 { + // 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("^[/\\\\]+", ""); + // 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) { + 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 origin as this request, or the configured public application url (proxies) + if (request != null && request.getServerName() != null && origin(uri).equals(requestOrigin(request))) { + return true; + } + if (matchesOrigin(uri, applicationUrl()) || matchesOrigin(uri, socialProperty("redirect"))) { + return true; + } + String extra = socialProperty("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; + } + + // 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; + } + 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 79b7cc9b0..58cfc4c9d 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, diff --git a/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java b/test/prerna/semoss/web/services/saml/SamlVerifierServletTest.java index 3c98eb600..6491531f2 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 6be39d159..ddd346d38 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 d92ff1d22..3087a1e13 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 dab22740e..728fe1f64 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); } }