diff --git a/src/prerna/collaboration/BrainGraphHeaderSource.java b/src/prerna/collaboration/BrainGraphHeaderSource.java index 826bb2db483..a6314af9b72 100644 --- a/src/prerna/collaboration/BrainGraphHeaderSource.java +++ b/src/prerna/collaboration/BrainGraphHeaderSource.java @@ -46,6 +46,7 @@ import org.apache.logging.log4j.Logger; import prerna.auth.User; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.security.HttpHelperUtility; @@ -502,7 +503,8 @@ public Map orgChart(User user, String managerId) { @Override public byte[] photo(User user, String path) throws Exception { // User.Read covers the owner's own photo, anyone else's needs User.ReadBasic.All or more; 404 when none is set - return HttpHelperUtility.getRequestBytes(BASE + path, + return HttpHelperUtility.getRequestBytes( + ConnectorGuards.requireUnder(BASE + path, MicrosoftTokenFiller.MS_GRAPH_BASE_API), MicrosoftLoginUtils.getBearerHeader(MicrosoftLoginUtils.getValidAccessToken(user)), null, null, null); } @@ -612,7 +614,9 @@ private static Map get(User user, String url) throws Exception { } private static Map get(String token, String url) throws Exception { - return CollaborationDbUtils.parseMap(HttpHelperUtility.getRequest(url, + // a nextLink comes back in the response, and the request carries the token + return CollaborationDbUtils.parseMap(HttpHelperUtility.getRequest( + ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API), MicrosoftLoginUtils.getBearerHeader(token), null, null, null, TIMEOUT)); } diff --git a/src/prerna/collaboration/BrainGraphMessageSource.java b/src/prerna/collaboration/BrainGraphMessageSource.java index 777a60aa31e..6145b26b5a0 100644 --- a/src/prerna/collaboration/BrainGraphMessageSource.java +++ b/src/prerna/collaboration/BrainGraphMessageSource.java @@ -43,6 +43,7 @@ import org.apache.logging.log4j.Logger; import prerna.auth.User; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.sablecc2.om.execptions.SemossPixelException; @@ -100,7 +101,8 @@ public List> search(User user, List terms, boolean a try { while (url != null && out.size() < max) { Map page = CollaborationDbUtils.parseMap( - HttpHelperUtility.getRequest(url, MicrosoftLoginUtils.getBearerHeader(token), null, null, null)); + HttpHelperUtility.getRequest(ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API), + MicrosoftLoginUtils.getBearerHeader(token), null, null, null)); if (page.get("value") instanceof List values) { for (Object value : values) { out.add((Map) value); diff --git a/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java b/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java index befefb55627..2b08d5bb526 100644 --- a/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java +++ b/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java @@ -51,6 +51,7 @@ import com.google.gson.reflect.TypeToken; import prerna.engine.api.StorageTypeEnum; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftGraphAppTokenProvider; import prerna.io.connector.ms.MicrosoftGraphDriveClient; import prerna.io.connector.ms.MicrosoftLoginUtils; @@ -425,7 +426,7 @@ public void copyToLocal(String storageFilePath, String localFolderPath, String v transfers.add(() -> { try { byte[] bytes = this.driveClient.downloadBytes(item, remotePath); - Path target = localDirectory.resolve(relative); + Path target = ConnectorGuards.resolveWithin(localDirectory, relative); if (target.getParent() != null) { Files.createDirectories(target.getParent()); } @@ -511,7 +512,7 @@ public void syncStorageToLocal(String storagePath, String localPath) throws Exce String remotePath = MicrosoftGraphDriveClient.joinPath(storageFolder, relative); transfers.add(() -> { try { - Path target = localRoot.resolve(relative); + Path target = ConnectorGuards.resolveWithin(localRoot, relative); if (needsDownload(target, item)) { byte[] bytes = this.driveClient.downloadBytes(item, remotePath); if (target.getParent() != null) { @@ -675,7 +676,7 @@ private void copyVersionToLocal(String storageFilePath, String localFolderPath, versionId); Object itemName = item.get(MicrosoftGraphDriveClient.NAME); String fileName = itemName != null ? itemName.toString() : baseName(normalized); - Path target = localDirectory.resolve(fileName); + Path target = ConnectorGuards.resolveWithin(localDirectory, fileName); Files.write(target, bytes); classLogger.info("Downloaded version {} of '{}' to {}", versionId, normalized, target); } @@ -849,7 +850,9 @@ protected String buildAccessDeniedGuidance(Properties smssProp, IllegalArgumentE * @throws Exception if the request fails */ protected Map graphGet(String url) throws Exception { - String response = HttpHelperUtility.getRequest(url, + // every url sent here carries the token, nextLinks included, so none may leave Graph + String response = HttpHelperUtility.getRequest( + ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API), MicrosoftLoginUtils.getBearerHeader(this.tokenProvider.getAccessToken()), null, null, null); if (response == null || response.trim().isEmpty()) { return null; diff --git a/src/prerna/io/connector/ConnectorGuards.java b/src/prerna/io/connector/ConnectorGuards.java new file mode 100644 index 00000000000..c9d80bccb7c --- /dev/null +++ b/src/prerna/io/connector/ConnectorGuards.java @@ -0,0 +1,175 @@ +package prerna.io.connector; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.util.Locale; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Checks for urls and local paths that are built from what a connector's remote + * service sent back, or from an id a caller passed in. + */ +public final class ConnectorGuards { + + private static final Logger classLogger = LogManager.getLogger(ConnectorGuards.class); + + private ConnectorGuards() { + } + + /** + * A link that is followed with the user's bearer token, such as an + * {@code @odata.nextLink}, has to stay on the service's own host. + * + * @param link the link the service returned + * @param base the service's base url, without a trailing slash + * @return the link + * @throws IllegalArgumentException when the link is anywhere else + */ + public static String requireUnder(String link, String base) { + if (link != null) { + try { + URI parsed = new URI(link.trim()); + URI root = new URI(base); + String basePath = root.getRawPath() == null ? "" : root.getRawPath(); + String linkPath = parsed.getRawPath() == null ? "" : parsed.getRawPath(); + // scheme and host compare case-insensitively, the path must be below the base path + if (parsed.getScheme() != null && parsed.getScheme().equalsIgnoreCase(root.getScheme()) + && parsed.getHost() != null && parsed.getHost().equalsIgnoreCase(root.getHost()) + && effectivePort(parsed) == effectivePort(root) && parsed.getUserInfo() == null + && linkPath.startsWith(basePath + "/")) { + return link; + } + } catch (URISyntaxException e) { + // refused below + } + } + classLogger.warn("Refused to follow a link outside {}: {}", base, hostOf(link)); + throw new IllegalArgumentException("Refused to follow a link that does not belong to " + base); + } + + /** + * A pre-authenticated link, which is called without the token, has to be a plain + * https address. + * + * @param link the link the service returned + * @return the link, trimmed + * @throws IllegalArgumentException when it is not https or names no host + */ + public static String requirePreAuthenticated(String link) { + String trimmed = link == null ? "" : link.trim(); + try { + URI parsed = new URI(trimmed); + if ("https".equalsIgnoreCase(parsed.getScheme()) && parsed.getHost() != null + && parsed.getUserInfo() == null) { + return trimmed; + } + } catch (URISyntaxException e) { + // refused below + } + classLogger.warn("Refused a download link that is not https: {}", hostOf(trimmed)); + throw new IllegalArgumentException("Refused a download link that is not an https address"); + } + + /** + * Makes an id safe to place in one segment of a url path. Ids as the services + * issue them, such as {@code 19:abc@thread.v2} or {@code b!01ABC}, pass through + * as they are; only what could change the path or the query is encoded. + * + * @param id the id + * @return the id, with anything that could change the path encoded + * @throws IllegalArgumentException when the id is blank or a dot segment + */ + public static String segment(String id) { + String value = id == null ? "" : id.trim(); + if (value.isEmpty() || value.equals(".") || value.equals("..")) { + throw new IllegalArgumentException("Not a valid id: " + id); + } + StringBuilder out = new StringBuilder(value.length()); + for (byte b : value.getBytes(StandardCharsets.UTF_8)) { + char c = (char) (b & 0xff); + if (c < 0x80 && (Character.isLetterOrDigit(c) || "-._~!$&'()*+,;=:@".indexOf(c) >= 0)) { + out.append(c); + } else { + out.append('%').append(String.format(Locale.ROOT, "%02X", b & 0xff)); + } + } + return out.toString(); + } + + /** + * Joins a relative path, as a remote listing names it, to a local folder and + * checks that the result is still inside that folder. + * + * @param root the folder everything has to stay in + * @param relative the path below it + * @return the resolved path + * @throws IllegalArgumentException when the path would leave the folder + */ + public static Path resolveWithin(Path root, String relative) { + if (relative == null || relative.isBlank()) { + throw new IllegalArgumentException("Not a file name inside the destination: " + relative); + } + Path base = root.toAbsolutePath().normalize(); + try { + // real path of the nearest existing part, so a root that is not created yet still compares true + Path existingRoot = base; + while (existingRoot != null && !Files.exists(existingRoot)) { + existingRoot = existingRoot.getParent(); + } + if (existingRoot != null) { + base = existingRoot.toRealPath().resolve(existingRoot.relativize(base)).normalize(); + } + } catch (IOException e) { + throw new IllegalArgumentException("The destination cannot be resolved: " + root, e); + } + Path target = base.resolve(relative.replace('\\', '/')).normalize(); + if (!target.startsWith(base) || target.equals(base) || escapesThroughLink(base, target)) { + classLogger.warn("Refused a remote file name that leaves {}", base); + throw new IllegalArgumentException("Not a file name inside the destination: " + relative); + } + return target; + } + + // a symlink below the root must not carry the write outside it + private static boolean escapesThroughLink(Path base, Path target) { + Path existing = target; + while (existing != null && !Files.exists(existing, LinkOption.NOFOLLOW_LINKS)) { + existing = existing.getParent(); + } + if (existing == null) { + return true; + } + if (!existing.startsWith(base)) { + // nothing under the root exists yet + return false; + } + try { + return !existing.toRealPath().startsWith(base); + } catch (IOException e) { + return true; + } + } + + private static int effectivePort(URI uri) { + if (uri.getPort() >= 0) { + return uri.getPort(); + } + return "http".equalsIgnoreCase(uri.getScheme()) ? 80 : 443; + } + + private static String hostOf(String link) { + try { + String host = link == null ? null : new URI(link.trim()).getHost(); + return host == null ? "no host" : host; + } catch (URISyntaxException e) { + return "an unreadable address"; + } + } +} diff --git a/src/prerna/io/connector/antivirus/virustotal/VirusTotalScannerUtils.java b/src/prerna/io/connector/antivirus/virustotal/VirusTotalScannerUtils.java index 0e92aaf7313..fe2221d8a49 100644 --- a/src/prerna/io/connector/antivirus/virustotal/VirusTotalScannerUtils.java +++ b/src/prerna/io/connector/antivirus/virustotal/VirusTotalScannerUtils.java @@ -52,6 +52,7 @@ import org.apache.logging.log4j.Logger; import org.json.JSONObject; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.antivirus.IVirusScanner; import prerna.security.HttpHelperUtility; import prerna.util.Constants; @@ -212,7 +213,7 @@ private Map> analysesEndpoint(String analysisFileId, CloseableHttpClient httpClient = null; try { httpClient = HttpHelperUtility.getCustomClient(null, keyStore, keyStorePass, keyPass); - HttpGet httpGet = new HttpGet(VIRUS_TOTAL_URL + analysisFileId); + HttpGet httpGet = new HttpGet(VIRUS_TOTAL_URL + ConnectorGuards.segment(analysisFileId)); httpGet.addHeader("x-apikey", this.apiKey); httpGet.addHeader("accept", "application/json"); diff --git a/src/prerna/io/connector/google/gmail/GoogleGmailMime.java b/src/prerna/io/connector/google/gmail/GoogleGmailMime.java index f1168d8462b..02ea0139435 100644 --- a/src/prerna/io/connector/google/gmail/GoogleGmailMime.java +++ b/src/prerna/io/connector/google/gmail/GoogleGmailMime.java @@ -117,10 +117,10 @@ static String write(String from, List to, List cc, List setRecipients(message, Message.RecipientType.TO, to); setRecipients(message, Message.RecipientType.CC, cc); setRecipients(message, Message.RecipientType.BCC, bcc); - message.setSubject(subject == null ? "" : subject, "UTF-8"); + message.setSubject(subject == null ? "" : oneLine(subject), "UTF-8"); if (inReplyTo != null && !inReplyTo.isBlank()) { - message.setHeader("In-Reply-To", inReplyTo); - message.setHeader("References", references == null || references.isBlank() ? inReplyTo : references); + message.setHeader("In-Reply-To", oneLine(inReplyTo)); + message.setHeader("References", oneLine(references == null || references.isBlank() ? inReplyTo : references)); } String text = body == null ? "" : body; @@ -137,7 +137,7 @@ static String write(String from, List to, List cc, List for (File file : files) { MimeBodyPart part = new MimeBodyPart(); part.attachFile(file); - part.setFileName(OutgoingMail.attachmentName(file)); + part.setFileName(oneLine(OutgoingMail.attachmentName(file))); mixed.addBodyPart(part); } } @@ -145,10 +145,10 @@ static String write(String from, List to, List cc, List for (CarriedFile file : carried) { InternetHeaders headers = new InternetHeaders(); headers.addHeader("Content-Type", - file.contentType() == null ? "application/octet-stream" : file.contentType()); + file.contentType() == null ? "application/octet-stream" : oneLine(file.contentType())); headers.addHeader("Content-Transfer-Encoding", "base64"); MimeBodyPart part = new MimeBodyPart(headers, Base64.getMimeEncoder().encode(file.bytes())); - part.setFileName(file.name()); + part.setFileName(file.name() == null ? null : oneLine(file.name())); part.setDisposition(Part.ATTACHMENT); mixed.addBodyPart(part); } @@ -166,6 +166,11 @@ static String write(String from, List to, List cc, List * @param subject the subject being answered * @return the subject of the reply, which does not gain a second Re: */ + // a header value read from a received message may not carry a line break into the one that is written + private static String oneLine(String value) { + return value.replaceAll("[\\r\\n\\x00]+", " ").trim(); + } + static String replySubject(String subject) { String original = subject == null ? "" : subject.trim(); return original.toLowerCase(Locale.ROOT).startsWith("re:") ? original : "Re: " + original; diff --git a/src/prerna/io/connector/ms/MicrosoftGraphDriveClient.java b/src/prerna/io/connector/ms/MicrosoftGraphDriveClient.java index d387cc36397..13f4c5545d1 100644 --- a/src/prerna/io/connector/ms/MicrosoftGraphDriveClient.java +++ b/src/prerna/io/connector/ms/MicrosoftGraphDriveClient.java @@ -50,6 +50,7 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.security.HttpHelperUtility; import prerna.util.ValueUtils; @@ -185,7 +186,8 @@ public byte[] downloadVersionBytes(String itemId, String versionId) throws Excep if (version != null) { Object preAuthUrl = version.get(DOWNLOAD_URL); if (preAuthUrl != null && !preAuthUrl.toString().trim().isEmpty()) { - bytes = HttpHelperUtility.getRequestBytes(preAuthUrl.toString(), null, null, null, null); + bytes = HttpHelperUtility.getRequestBytes(ConnectorGuards.requirePreAuthenticated(preAuthUrl.toString()), + null, null, null, null); } } if (bytes == null) { @@ -206,7 +208,10 @@ private List> getPagedValues(String url) throws Exception { List> collected = new ArrayList<>(); String nextUrl = url; while (nextUrl != null) { - String response = HttpHelperUtility.getRequest(nextUrl, authHeaders(), null, null, null); + // a nextLink comes back in the response, and the request carries the token + String response = HttpHelperUtility.getRequest( + ConnectorGuards.requireUnder(nextUrl, MicrosoftTokenFiller.MS_GRAPH_BASE_API), authHeaders(), null, + null, null); Map json = parseObject(response); if (json == null) { break; @@ -320,11 +325,12 @@ public byte[] downloadBytes(Map item, String relativePath) throw Object preAuthUrl = item.get(DOWNLOAD_URL); byte[] bytes; if (preAuthUrl != null && !preAuthUrl.toString().trim().isEmpty()) { - bytes = HttpHelperUtility.getRequestBytes(preAuthUrl.toString(), null, null, null, null); + bytes = HttpHelperUtility.getRequestBytes(ConnectorGuards.requirePreAuthenticated(preAuthUrl.toString()), null, + null, null, null); } else { Object itemId = item.get(ID); String contentUrl = itemId != null - ? GRAPH_BASE + "/drives/" + this.driveId + "/items/" + itemId.toString().trim() + "/content" + ? itemIdUrl(itemId.toString()) + "/content" : itemUrl(relativePath) + "/content"; bytes = HttpHelperUtility.getRequestBytes(contentUrl, authHeaders(), null, null, null); } @@ -393,7 +399,7 @@ private String sessionUpload(File localFile, String relativePath, String conflic if (sessionJson == null || sessionJson.get(UPLOAD_URL) == null) { throw new IllegalStateException("Graph did not return an upload session for path: " + relativePath); } - String uploadUrl = sessionJson.get(UPLOAD_URL).toString(); + String uploadUrl = ConnectorGuards.requirePreAuthenticated(sessionJson.get(UPLOAD_URL).toString()); // the upload session url is pre-authenticated, so no bearer header is sent long totalSize = localFile.length(); @@ -584,7 +590,7 @@ private String itemIdUrl(String itemId) { if (ValueUtils.isBlank(itemId)) { throw new IllegalArgumentException("An item id is required."); } - return GRAPH_BASE + "/drives/" + this.driveId + "/items/" + itemId.trim(); + return GRAPH_BASE + "/drives/" + ConnectorGuards.segment(this.driveId) + "/items/" + ConnectorGuards.segment(itemId); } private Map authHeaders() { diff --git a/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java b/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java index 51d35351a6c..098e3be1c87 100644 --- a/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java +++ b/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java @@ -41,6 +41,7 @@ import prerna.auth.AccessToken; import prerna.auth.AuthProvider; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.IAccessTokenFiller; import prerna.security.HttpHelperUtility; import prerna.util.SocialPropertiesUtil; @@ -128,7 +129,7 @@ public GraphApiResponse findUser(AccessToken accessToken, String groupId, String filter += " and userType eq 'Member'"; path = "/v1.0/users"; } else { - path = "/v1.0/groups/" + groupId + "/members/microsoft.graph.user"; + path = "/v1.0/groups/" + ConnectorGuards.segment(groupId) + "/members/microsoft.graph.user"; } List queryParams = new ArrayList<>(); queryParams.add("$filter=" + URLEncoder.encode(filter, StandardCharsets.UTF_8.toString())); @@ -232,11 +233,13 @@ private String buildUri(String groupId, String searchTerm, String nextLink) thro java.nio.charset.StandardCharsets.UTF_8.toString())); uri = MicrosoftTokenFiller.MS_GRAPH_BASE_API + "/v1.0/users?" + String.join("&", queryParams); } else { - uri = MicrosoftTokenFiller.MS_GRAPH_BASE_API + "/v1.0/groups/" + groupId + uri = MicrosoftTokenFiller.MS_GRAPH_BASE_API + "/v1.0/groups/" + + ConnectorGuards.segment(groupId) + "/members/microsoft.graph.user?" + String.join("&", queryParams); } } else { - uri = nextLink; + // a nextLink may come from a caller, and the request carries the token + uri = ConnectorGuards.requireUnder(nextLink, MicrosoftTokenFiller.MS_GRAPH_BASE_API); } return uri; } diff --git a/src/prerna/io/connector/ms/calendar/MicrosoftCalendarHelper.java b/src/prerna/io/connector/ms/calendar/MicrosoftCalendarHelper.java index f2883908006..6db83b6b83d 100644 --- a/src/prerna/io/connector/ms/calendar/MicrosoftCalendarHelper.java +++ b/src/prerna/io/connector/ms/calendar/MicrosoftCalendarHelper.java @@ -54,6 +54,7 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ConnectorPage; import prerna.io.connector.ConnectorTimes; import prerna.io.connector.calendar.AbstractRespondToEventReactor; @@ -754,7 +755,9 @@ private static CalendarEvent toEvent(String response, String eventId) { } private static String get(String url, String accessToken, boolean textBody) { - return HttpHelperUtility.getRequest(url, headers(accessToken, textBody), null, null, null); + // a nextLink comes back in the response, and the request carries the token + return HttpHelperUtility.getRequest(ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API), + headers(accessToken, textBody), null, null, null); } /** diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 3be2ff8e03d..9f5ab40e997 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -62,6 +62,7 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftTokenFiller; import prerna.security.HttpHelperUtility; @@ -702,7 +703,8 @@ public static Map downloadFile(String accessToken, String driveI if (item.get(DOWNLOAD_URL) == null && !ValueUtils.isBlank(resolvedDriveId) && !ValueUtils.isBlank(resolvedItemId)) { Map remote = readItem(accessToken, - GRAPH_BASE + "/drives/" + resolvedDriveId + ITEMS + resolvedItemId); + GRAPH_BASE + "/drives/" + ConnectorGuards.segment(resolvedDriveId) + ITEMS + + ConnectorGuards.segment(resolvedItemId)); if (remote != null) { item = remote; } @@ -1216,7 +1218,8 @@ private static long downloadBytes(String accessToken, Map item, size = download(preAuthUrl.toString(), null, file, name); } if (size == 0 && !ValueUtils.isBlank(driveId) && !ValueUtils.isBlank(itemId)) { - String contentUrl = GRAPH_BASE + "/drives/" + driveId + ITEMS + itemId + "/content"; + String contentUrl = GRAPH_BASE + "/drives/" + ConnectorGuards.segment(driveId) + ITEMS + + ConnectorGuards.segment(itemId) + "/content"; size = download(contentUrl, headers(accessToken), file, name); } if (size == 0) { @@ -1250,6 +1253,9 @@ public static long download(String url, Map headers, File file, // named up front, so a download that breaks part way is deleted too File temp = new File(folder, ".download-" + UUID.randomUUID()); try { + // with the token the link has to be Graph's own; without it, a plain https link + url = headers == null ? ConnectorGuards.requirePreAuthenticated(url) + : ConnectorGuards.requireUnder(url, MicrosoftTokenFiller.MS_GRAPH_BASE_API); temp = HttpHelperUtility.getRequestFileDownload(url, headers, null, null, null, folder, temp.getName()); long size = temp.length(); checkDownloadSize(size, name); @@ -1284,7 +1290,10 @@ public static void checkDownloadSize(Object size, String name) { * Teams attachment's that its sender chose, may carry "../" and would otherwise * write outside the destination. */ - static String baseName(String name) { + public static String baseName(String name) { + if (name == null) { + throw new IllegalArgumentException("Not a file name: null"); + } String base = name.replace('\\', '/'); base = base.substring(base.lastIndexOf('/') + 1).trim(); if (base.isEmpty() || base.equals(".") || base.equals("..")) { @@ -1372,6 +1381,7 @@ public static String sendToUploadSession(String uploadUrl, File file, String fil final String CONTENT_RANGE = "Content-Range"; // the upload session url is pre-authenticated, so the bearer header is omitted + uploadUrl = ConnectorGuards.requirePreAuthenticated(uploadUrl); long totalSize = file.length(); long offset = 0; String lastResponse = null; @@ -1567,7 +1577,10 @@ private static List> getPagedValues(String accessToken, Stri List> collected = new ArrayList<>(); String nextUrl = url; while (nextUrl != null) { - String response = HttpHelperUtility.getRequest(nextUrl, headers(accessToken), null, null, null); + // a nextLink comes back in the response, and the request carries the token + String response = HttpHelperUtility.getRequest( + ConnectorGuards.requireUnder(nextUrl, MicrosoftTokenFiller.MS_GRAPH_BASE_API), headers(accessToken), + null, null, null); Map json = readMap(response); if (json == null) { break; @@ -1594,7 +1607,7 @@ private static String drivePath(String driveId) { if (ValueUtils.isBlank(driveId)) { return GRAPH_BASE + "/me/drive"; } - return GRAPH_BASE + "/drives/" + driveId.trim(); + return GRAPH_BASE + "/drives/" + ConnectorGuards.segment(driveId); } /** @@ -1616,7 +1629,7 @@ private static String itemUrl(String driveId, String itemId, String path) { String base = drivePath(driveId); String relativePath = encodeRelativePath(path); if (!ValueUtils.isBlank(itemId)) { - String itemBase = base + ITEMS + itemId.trim(); + String itemBase = base + ITEMS + ConnectorGuards.segment(itemId); return relativePath.isEmpty() ? itemBase : itemBase + ":/" + relativePath + ":"; } return relativePath.isEmpty() ? base + "/root" : base + "/root:/" + relativePath + ":"; diff --git a/src/prerna/io/connector/ms/outlook/MicrosoftOutlookMailHelper.java b/src/prerna/io/connector/ms/outlook/MicrosoftOutlookMailHelper.java index 246d96dd43a..9ff341b85f6 100644 --- a/src/prerna/io/connector/ms/outlook/MicrosoftOutlookMailHelper.java +++ b/src/prerna/io/connector/ms/outlook/MicrosoftOutlookMailHelper.java @@ -59,6 +59,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ConnectorPage; import prerna.query.parsers.MailSearchParser; import prerna.security.HttpHelperUtility; @@ -398,7 +399,7 @@ private static void uploadAttachment(String accessToken, String attachmentsUrl, int end = Math.min(offset + UPLOAD_CHUNK_BYTES, bytes.length); Map chunkHeaders = new HashMap<>(); chunkHeaders.put("Content-Range", "bytes " + offset + "-" + (end - 1) + "/" + bytes.length); - HttpHelperUtility.putRequestBytesBody(uploadUrl.toString(), chunkHeaders, + HttpHelperUtility.putRequestBytesBody(ConnectorGuards.requirePreAuthenticated(uploadUrl.toString()), chunkHeaders, Arrays.copyOfRange(bytes, offset, end), ContentType.APPLICATION_OCTET_STREAM, null, null, null); } } @@ -978,7 +979,9 @@ public ConnectorPage> listMessagePage(String accessToken, St } messages.add(message); } - next = page != null && page.get("@odata.nextLink") instanceof String link ? link : null; + next = page != null && page.get("@odata.nextLink") instanceof String link + ? ConnectorGuards.requireUnder(link, this.graphBaseUrl) + : null; pages++; } while (searching && next != null && pages < MAX_SEARCH_PAGES && messages.size() < query.top); @@ -1317,7 +1320,9 @@ private void appendFolderLevel(String accessToken, String mailbox, String parent appendFolderLevel(accessToken, mailbox, id, path, depth + 1, tree); } } - url = page != null && page.get("@odata.nextLink") instanceof String next ? next : null; + url = page != null && page.get("@odata.nextLink") instanceof String next + ? ConnectorGuards.requireUnder(next, this.graphBaseUrl) + : null; } } diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java index 03e1e0723a3..58d5a6e6baf 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java @@ -55,6 +55,7 @@ import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; +import prerna.io.connector.ConnectorGuards; import prerna.io.connector.ms.MicrosoftLoginUtils; import prerna.io.connector.ms.MicrosoftMessageDisplay; import prerna.io.connector.ms.MicrosoftTokenFiller; @@ -252,7 +253,8 @@ public static List> listChats(String accessToken, String use int olderRun = 0; walk: while (nextUrl != null) { Map json = readMap( - HttpHelperUtility.getRequest(nextUrl, headers(accessToken), null, null, null)); + HttpHelperUtility.getRequest(ConnectorGuards.requireUnder(nextUrl, MicrosoftTokenFiller.MS_GRAPH_BASE_API), + headers(accessToken), null, null, null)); if (json == null) { break; } @@ -689,7 +691,7 @@ public static Map getChatMessage(String accessToken, String chat requireValue(chatId, "Chat ID is required to read a Microsoft Teams chat message."); requireValue(messageId, "Message ID is required to read a Microsoft Teams chat message."); - String url = chatPath(chatId) + MESSAGES + messageId.trim(); + String url = chatPath(chatId) + MESSAGES + ConnectorGuards.segment(messageId); return readMessage(accessToken, url, maxBodyChars, false); } catch (Exception e) { classLogger.error("Failed to read message '{}' of Microsoft Teams chat '{}'.", messageId, chatId, e); @@ -751,8 +753,8 @@ public static void deleteChatMessage(String accessToken, String chatId, String m // Graph documents this one only under a named user rather than under /me, // so the signed in user's id is read rather than assumed to be aliasable - String url = GRAPH_BASE + "/users/" + signedInUserId(accessToken) + CHATS + chatId.trim() + MESSAGES - + messageId.trim() + SOFT_DELETE; + String url = GRAPH_BASE + "/users/" + ConnectorGuards.segment(signedInUserId(accessToken)) + CHATS + + ConnectorGuards.segment(chatId) + MESSAGES + ConnectorGuards.segment(messageId) + SOFT_DELETE; // answers 204 with no body HttpHelperUtility.postRequestStringBody(url, headers(accessToken), "", ContentType.APPLICATION_JSON, null, null, null); @@ -863,7 +865,7 @@ public static Map sendChannelMessage(String accessToken, String Map request = buildMessage(accessToken, subject, content, html, mentions, attachmentUrls, attachmentNames); String url = ValueUtils.isBlank(replyToId) ? channelPath(teamId, channelId) + "/messages" - : channelPath(teamId, channelId) + MESSAGES + replyToId.trim() + "/replies"; + : channelPath(teamId, channelId) + MESSAGES + ConnectorGuards.segment(replyToId) + "/replies"; return postMessage(accessToken, url, request, maxBodyChars); } catch (Exception e) { classLogger.error("Failed to send a message to channel '{}' in Microsoft Team '{}'.", channelId, teamId, e); @@ -943,7 +945,7 @@ public static Map downloadAttachment(String accessToken, String requireValue(destination, "A destination path is required to download a Microsoft Teams attachment."); String messageUrl = ValueUtils.isBlank(chatId) ? messagePath(teamId, channelId, messageId, replyId) - : chatPath(chatId) + MESSAGES + messageId.trim(); + : chatPath(chatId) + MESSAGES + ConnectorGuards.segment(messageId); Map message = readMap( HttpHelperUtility.getRequest(messageUrl, headers(accessToken), null, null, null)); if (message == null) { @@ -1006,7 +1008,7 @@ private static Map downloadHostedContent(String accessToken, Str "The message holds no attachment of that name or id. Read the message to see what it has on it."); } - String url = messageUrl + HOSTED_CONTENTS + "/" + hostedContentId.trim() + "/$value"; + String url = messageUrl + HOSTED_CONTENTS + "/" + ConnectorGuards.segment(hostedContentId) + "/$value"; // hosted content is unnamed, so it is written under the name the caller // asked for and under the id it has otherwise @@ -1283,7 +1285,8 @@ private static Map conversationMember(String userId) { * The file a download is written to in a directory. */ private static File target(String destination, String fileName) { - File file = new File(Paths.get(destination, fileName).toString()); + // only the base name is honored, so a name carrying separators cannot leave the destination + File file = new File(Paths.get(destination, MicrosoftOneDriveHelper.baseName(fileName)).toString()); File parent = file.getParentFile(); if (parent != null && !parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Unable to create destination directory at: " + parent.getAbsolutePath()); @@ -1295,14 +1298,14 @@ private static File target(String destination, String fileName) { * The part of a Graph url that says which chat this is. */ private static String chatPath(String chatId) { - return GRAPH_BASE + CHATS + chatId.trim(); + return GRAPH_BASE + CHATS + ConnectorGuards.segment(chatId); } /** * The part of a Graph url that says which channel this is. */ private static String channelPath(String teamId, String channelId) { - return GRAPH_BASE + "/teams/" + teamId.trim() + "/channels/" + channelId.trim(); + return GRAPH_BASE + "/teams/" + ConnectorGuards.segment(teamId) + "/channels/" + ConnectorGuards.segment(channelId); } /** @@ -1311,8 +1314,8 @@ private static String channelPath(String teamId, String channelId) { private static String messagePath(String teamId, String channelId, String messageId, String replyId) { requireValue(teamId, "Team ID is required to address a Microsoft Teams channel message."); requireValue(channelId, "Channel ID is required to address a Microsoft Teams channel message."); - String message = channelPath(teamId, channelId) + MESSAGES + messageId.trim(); - return ValueUtils.isBlank(replyId) ? message : message + REPLIES + replyId.trim(); + String message = channelPath(teamId, channelId) + MESSAGES + ConnectorGuards.segment(messageId); + return ValueUtils.isBlank(replyId) ? message : message + REPLIES + ConnectorGuards.segment(replyId); } /** @@ -1336,9 +1339,11 @@ private static List> getPagedValues(String accessToken, Stri List> collected = new ArrayList<>(); String nextUrl = url; while (nextUrl != null) { + // a nextLink comes back in the response, and the request carries the token + String guarded = ConnectorGuards.requireUnder(nextUrl, MicrosoftTokenFiller.MS_GRAPH_BASE_API); Map json = readMap(timeout == null - ? HttpHelperUtility.getRequest(nextUrl, headers(accessToken), null, null, null) - : HttpHelperUtility.getRequest(nextUrl, headers(accessToken), null, null, null, timeout)); + ? HttpHelperUtility.getRequest(guarded, headers(accessToken), null, null, null) + : HttpHelperUtility.getRequest(guarded, headers(accessToken), null, null, null, timeout)); if (json == null) { break; }