Skip to content
8 changes: 6 additions & 2 deletions src/prerna/collaboration/BrainGraphHeaderSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -502,7 +503,8 @@ public Map<String, String> 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);
}

Expand Down Expand Up @@ -612,7 +614,9 @@ private static Map<String, Object> get(User user, String url) throws Exception {
}

private static Map<String, Object> 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));
}

Expand Down
4 changes: 3 additions & 1 deletion src/prerna/collaboration/BrainGraphMessageSource.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -100,7 +101,8 @@ public List<Map<String, Object>> search(User user, List<String> terms, boolean a
try {
while (url != null && out.size() < max) {
Map<String, Object> 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<String, Object>) value);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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());
}
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -849,7 +850,9 @@ protected String buildAccessDeniedGuidance(Properties smssProp, IllegalArgumentE
* @throws Exception if the request fails
*/
protected Map<String, Object> 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;
Expand Down
175 changes: 175 additions & 0 deletions src/prerna/io/connector/ConnectorGuards.java
Original file line number Diff line number Diff line change
@@ -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";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -212,7 +213,7 @@ private Map<String, Collection<String>> 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");

Expand Down
17 changes: 11 additions & 6 deletions src/prerna/io/connector/google/gmail/GoogleGmailMime.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,10 @@ static String write(String from, List<String> to, List<String> cc, List<String>
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;
Expand All @@ -137,18 +137,18 @@ static String write(String from, List<String> to, List<String> cc, List<String>
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);
}
}
if (carried != null) {
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);
}
Expand All @@ -166,6 +166,11 @@ static String write(String from, List<String> to, List<String> cc, List<String>
* @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;
Expand Down
18 changes: 12 additions & 6 deletions src/prerna/io/connector/ms/MicrosoftGraphDriveClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand All @@ -206,7 +208,10 @@ private List<Map<String, Object>> getPagedValues(String url) throws Exception {
List<Map<String, Object>> 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<String, Object> json = parseObject(response);
if (json == null) {
break;
Expand Down Expand Up @@ -320,11 +325,12 @@ public byte[] downloadBytes(Map<String, Object> 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);
}
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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<String, String> authHeaders() {
Expand Down
Loading
Loading