From 5994082a3fe883a4d0194b704b729d12360644de Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 15:20:38 -0500 Subject: [PATCH 1/6] fix(connectors): keep Graph links and ids from steering requests off the service host Add ConnectorGuards: a nextLink that is sent with the user's token must stay on graph.microsoft.com, a pre-authenticated download or upload link must be https, and ids placed in url paths are encoded only where they could change the path. Applied at the Graph request choke points (storage engine graphGet, drive client, OneDrive, Teams, Calendar, Outlook, Brain Graph sources, user search) and the VirusTotal analysis id. --- .../collaboration/BrainGraphHeaderSource.java | 8 +- .../BrainGraphMessageSource.java | 4 +- .../AbstractMicrosoftGraphStorageEngine.java | 5 +- src/prerna/io/connector/ConnectorGuards.java | 124 ++++++++++++++++++ .../virustotal/VirusTotalScannerUtils.java | 3 +- .../ms/MicrosoftGraphDriveClient.java | 18 ++- .../ms/MicrosoftGraphUserSearchClient.java | 4 +- .../ms/calendar/MicrosoftCalendarHelper.java | 5 +- .../ms/onedrive/MicrosoftOneDriveHelper.java | 20 ++- .../outlook/MicrosoftOutlookMailHelper.java | 11 +- .../ms/teams/MicrosoftTeamsMessageHelper.java | 30 +++-- 11 files changed, 198 insertions(+), 34 deletions(-) create mode 100644 src/prerna/io/connector/ConnectorGuards.java 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..b0fc37e6b18 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; @@ -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..60e51a551f9 --- /dev/null +++ b/src/prerna/io/connector/ConnectorGuards.java @@ -0,0 +1,124 @@ +package prerna.io.connector; + +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +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 && link.startsWith(base + "/")) { + try { + URI parsed = new URI(link); + if (parsed.getHost() != null && parsed.getHost().equalsIgnoreCase(new URI(base).getHost()) + && parsed.getUserInfo() == null) { + 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) { + Path base = root.toAbsolutePath().normalize(); + Path target = base.resolve(relative.replace('\\', '/')).normalize(); + if (!target.startsWith(base) || target.equals(base)) { + classLogger.warn("Refused a remote file name that leaves {}", base); + throw new IllegalArgumentException("Not a file name inside the destination: " + relative); + } + return target; + } + + 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/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..466fd87e741 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; @@ -236,7 +237,8 @@ private String buildUri(String groupId, String searchTerm, String nextLink) thro + "/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..1212c88b072 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); @@ -1372,6 +1378,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 +1574,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 +1604,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 +1626,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..c8c883b26f1 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 @@ -1295,14 +1297,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 +1313,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 +1338,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; } From e3a39f9f8ba611ab22a50069d2f17329ba24d8ee Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 15:20:44 -0500 Subject: [PATCH 2/6] fix(connectors): keep remote file names inside the download folder Resolve names that Graph listings return against the real destination folder and refuse anything that leaves it (storage engine downloads, sync down, version download), and reduce the Teams helper's target name to a base name as the OneDrive helper already does. --- .../impl/storage/AbstractMicrosoftGraphStorageEngine.java | 6 +++--- .../io/connector/ms/onedrive/MicrosoftOneDriveHelper.java | 2 +- .../io/connector/ms/teams/MicrosoftTeamsMessageHelper.java | 3 ++- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java b/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java index b0fc37e6b18..2b08d5bb526 100644 --- a/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java +++ b/src/prerna/engine/impl/storage/AbstractMicrosoftGraphStorageEngine.java @@ -426,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()); } @@ -512,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) { @@ -676,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); } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 1212c88b072..49ed89dd939 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -1290,7 +1290,7 @@ 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) { String base = name.replace('\\', '/'); base = base.substring(base.lastIndexOf('/') + 1).trim(); if (base.isEmpty() || base.equals(".") || base.equals("..")) { diff --git a/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java b/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java index c8c883b26f1..58d5a6e6baf 100644 --- a/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java +++ b/src/prerna/io/connector/ms/teams/MicrosoftTeamsMessageHelper.java @@ -1285,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()); From d0e5ca74bc6ccc0d293c4d34c22534ae10d8384b Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 15:20:44 -0500 Subject: [PATCH 3/6] fix(gmail): keep line breaks out of MIME header values Collapse CR, LF and NUL in the subject, In-Reply-To, References and carried attachment content type before they are written as headers of the outgoing draft. --- .../io/connector/google/gmail/GoogleGmailMime.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/prerna/io/connector/google/gmail/GoogleGmailMime.java b/src/prerna/io/connector/google/gmail/GoogleGmailMime.java index f1168d8462b..98a04f0addd 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; @@ -145,7 +145,7 @@ 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()); @@ -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; From 215e8cfc67c0e45aa20f1dc08b87af634f3d13aa Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 16:14:12 -0500 Subject: [PATCH 4/6] fix(gmail): strip line breaks from attachment file names in MIME headers --- src/prerna/io/connector/google/gmail/GoogleGmailMime.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/prerna/io/connector/google/gmail/GoogleGmailMime.java b/src/prerna/io/connector/google/gmail/GoogleGmailMime.java index 98a04f0addd..02ea0139435 100644 --- a/src/prerna/io/connector/google/gmail/GoogleGmailMime.java +++ b/src/prerna/io/connector/google/gmail/GoogleGmailMime.java @@ -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); } } @@ -148,7 +148,7 @@ static String write(String from, List to, List cc, List 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); } From 469269a1424ede696efe6f27a5ba434d101ff48f Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 16:14:12 -0500 Subject: [PATCH 5/6] fix(connectors): refuse symlink escapes and null names, compare link host and scheme case-insensitively --- src/prerna/io/connector/ConnectorGuards.java | 61 +++++++++++++++++-- .../ms/onedrive/MicrosoftOneDriveHelper.java | 3 + 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/src/prerna/io/connector/ConnectorGuards.java b/src/prerna/io/connector/ConnectorGuards.java index 60e51a551f9..c9d80bccb7c 100644 --- a/src/prerna/io/connector/ConnectorGuards.java +++ b/src/prerna/io/connector/ConnectorGuards.java @@ -1,8 +1,11 @@ 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; @@ -30,11 +33,17 @@ private ConnectorGuards() { * @throws IllegalArgumentException when the link is anywhere else */ public static String requireUnder(String link, String base) { - if (link != null && link.startsWith(base + "/")) { + if (link != null) { try { - URI parsed = new URI(link); - if (parsed.getHost() != null && parsed.getHost().equalsIgnoreCase(new URI(base).getHost()) - && parsed.getUserInfo() == null) { + 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) { @@ -104,15 +113,57 @@ public static String segment(String id) { * @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)) { + 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(); diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 49ed89dd939..9f5ab40e997 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -1291,6 +1291,9 @@ public static void checkDownloadSize(Object size, String name) { * write outside the destination. */ 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("..")) { From 4e1a4c5c53e3e19b763c75c184ca2cb3b28b3ad7 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Tue, 24 Nov 2026 16:14:12 -0500 Subject: [PATCH 6/6] fix(connectors): encode the group id in Graph user search paths --- .../io/connector/ms/MicrosoftGraphUserSearchClient.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java b/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java index 466fd87e741..098e3be1c87 100644 --- a/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java +++ b/src/prerna/io/connector/ms/MicrosoftGraphUserSearchClient.java @@ -129,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())); @@ -233,7 +233,8 @@ 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 {