Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions WebContent/samlLogin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
<title>SAML Login</title>
<script>
function redirectSAML() {
var xhttp = new XMLHttpRequest(),
origin = window.location.href;
endpoint = origin.substring(0, origin.lastIndexOf('/samlLogin')) + '/IdpSSOServlet',
window.location.replace(endpoint);
xhttp.open('GET', endpoint, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// sibling endpoint only, never built from the href (query or fragment text)
if (window.location.pathname.endsWith('/samlLogin')) {
window.location.replace('./IdpSSOServlet');
} else {
var trailingSlashes = window.location.pathname.match(/\/+$/);
var levels = trailingSlashes ? trailingSlashes[0].length : 1;
window.location.replace('../'.repeat(levels) + 'IdpSSOServlet');
}
}
</script>
</head>
Expand Down
14 changes: 8 additions & 6 deletions WebContent/samlSPLogin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
<title>SAML Login</title>
<script>
function redirectSAML() {
var xhttp = new XMLHttpRequest(),
origin = window.location.href;
endpoint = origin.substring(0, origin.lastIndexOf('/samlSPLogin')) + '/SPSSOServlet',
window.location.replace(endpoint);
xhttp.open('GET', endpoint, true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// sibling endpoint only, never built from the href (query or fragment text)
if (window.location.pathname.endsWith('/samlSPLogin')) {
window.location.replace('./SPSSOServlet');
} else {
var trailingSlashes = window.location.pathname.match(/\/+$/);
var levels = trailingSlashes ? trailingSlashes[0].length : 1;
window.location.replace('../'.repeat(levels) + 'SPSSOServlet');
}
}
</script>
</head>
Expand Down
15 changes: 14 additions & 1 deletion WebContent/setAdmin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -281,7 +294,7 @@
return;
}

window.location.replace(getBasePrefix());
returnToBase();
return;
}

Expand Down
4 changes: 3 additions & 1 deletion src/prerna/semoss/web/services/local/NameServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, e.getMessage());
Expand Down
4 changes: 2 additions & 2 deletions src/prerna/semoss/web/services/local/ProjectResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "error sending image file");
Expand Down Expand Up @@ -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<String, String> errorMap = new HashMap<>();
errorMap.put(Constants.ERROR_MESSAGE, "Error sending image file");
Expand Down
6 changes: 3 additions & 3 deletions src/prerna/semoss/web/services/local/SessionResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -270,15 +270,15 @@ 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 {
classLogger.info("Session ended. Redirect to login page");

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);
}

Expand Down
27 changes: 17 additions & 10 deletions src/prerna/semoss/web/services/local/UserResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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"));
Expand All @@ -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);
}
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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") + "");

Expand Down Expand Up @@ -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"));
Expand Down Expand Up @@ -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
Expand All @@ -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"));
Expand All @@ -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));
}

//////////////////////////////////////////////////////////////////////
Expand Down
7 changes: 3 additions & 4 deletions src/prerna/semoss/web/services/saml/IdpSSOServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
}
Expand Down
11 changes: 8 additions & 3 deletions src/prerna/semoss/web/services/saml/SamlVerifierServlet.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down
32 changes: 28 additions & 4 deletions src/prerna/upload/FileUploader.java
Original file line number Diff line number Diff line change
Expand Up @@ -842,14 +842,20 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> 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<String, String> fileMap = new HashMap<String, String>();
fileMap.put("fileName", savedName);
if (fePath.endsWith(DIR_SEPARATOR)) {
Expand All @@ -868,11 +874,11 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> 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<String, String> fileMap = new HashMap<String, String>();
fileMap.put("fileName", savedName);
if (fePath.endsWith(DIR_SEPARATOR)) {
Expand All @@ -889,6 +895,24 @@ private List<Map<String, String>> processFileItems(List<DiskFileItem> 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.
*
Expand Down
2 changes: 1 addition & 1 deletion src/prerna/web/conf/AccountLockedFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/prerna/web/conf/MemoryCheckFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
9 changes: 5 additions & 4 deletions src/prerna/web/conf/NoUserInSessionFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading