From b170fc083bb9447d7c8bb85ad9eeb69b80751b70 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 15:13:39 -0500 Subject: [PATCH 1/2] fix(paths): build room, engine and pipeline paths through checked helpers --- .../external/ExternalAuthorizationHelper.java | 4 ++- src/prerna/engine/impl/model/Room.java | 5 ++- .../impl/pipeline/EngineProxyFactory.java | 28 +++++++++++----- .../ms/onedrive/MicrosoftOneDriveHelper.java | 7 +++- src/prerna/util/InternalUtility.java | 6 ++-- src/prerna/util/UploadUtilities.java | 5 +-- src/prerna/util/Utility.java | 32 +++++++++++++++++++ 7 files changed, 69 insertions(+), 18 deletions(-) diff --git a/src/prerna/auth/external/ExternalAuthorizationHelper.java b/src/prerna/auth/external/ExternalAuthorizationHelper.java index a6a49be9ca..26a7695180 100644 --- a/src/prerna/auth/external/ExternalAuthorizationHelper.java +++ b/src/prerna/auth/external/ExternalAuthorizationHelper.java @@ -48,6 +48,7 @@ import prerna.cluster.util.ClusterUtil; import prerna.engine.api.IEngine; import prerna.engine.impl.pipeline.PlatformOperation; +import prerna.engine.impl.SmssUtilities; import prerna.engine.impl.rdbms.RDBMSNativeEngine; import prerna.security.HttpHelperUtility; import prerna.util.BeanFiller; @@ -121,7 +122,8 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep tempSmss.delete(); // also make the folder to persist... even if empty - String engineFolder = EngineUtility.getSpecificEngineBaseFolder(engineType, engineId, engineName); + String engineFolder = Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType), + SmssUtilities.getUniqueName(engineName, engineId), "engine folder"); File eFolder = new File(engineFolder); eFolder.mkdir(); diff --git a/src/prerna/engine/impl/model/Room.java b/src/prerna/engine/impl/model/Room.java index 192d26ffc7..0bbae397fd 100644 --- a/src/prerna/engine/impl/model/Room.java +++ b/src/prerna/engine/impl/model/Room.java @@ -2427,9 +2427,8 @@ public String getRoomFolderPath() { * @return the room folder path */ public static String roomFolderPath(String roomId) { - // every room folder is built here, so the id has to be a single folder name - Utility.requireSafePathSegment(roomId, "room id"); - return Utility.getBaseFolder() + File.separator + "room" + File.separator + roomId; + // every room folder is built here, so the id has to be a single folder name inside the room folder + return Utility.childPath(Utility.getBaseFolder() + File.separator + "room", roomId, "room id"); } // Core message accessors diff --git a/src/prerna/engine/impl/pipeline/EngineProxyFactory.java b/src/prerna/engine/impl/pipeline/EngineProxyFactory.java index 16c82e7a1c..7c973009d9 100644 --- a/src/prerna/engine/impl/pipeline/EngineProxyFactory.java +++ b/src/prerna/engine/impl/pipeline/EngineProxyFactory.java @@ -51,6 +51,7 @@ import prerna.engine.api.IVenvEngine; import prerna.project.api.IProject; import prerna.util.EngineUtility; +import prerna.util.Utility; /** * Factory for creating a dynamic proxy that wraps an IEngine instance to apply @@ -89,7 +90,7 @@ private static IModelEngine createGuardedModelEngine(IModelEngine engine, boolea if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -124,7 +125,7 @@ public static IDatabaseEngine createGuardedDatabaseEngine(IDatabaseEngine engine if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -157,7 +158,7 @@ public static IStorageEngine createGuardedStorageEngine(IStorageEngine engine) { if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -185,7 +186,7 @@ public static IFunctionEngine createGuardedFunctionEngine(IFunctionEngine engine if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -221,7 +222,7 @@ public static IVectorDatabaseEngine createGuardedVectorEngine(IVectorDatabaseEng if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -244,7 +245,7 @@ public static IProject createGuardedProject(IProject engine) { if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -267,7 +268,7 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) { if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFile(engine, pipelineValue); + jsonFile = pipelineFileOrNull(engine, pipelineValue); } } @@ -287,7 +288,18 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) { public static File pipelineFile(IEngine engine, String pipelineFileName) { String assetsFolder = EngineUtility.getSpecificEngineAssetsFolder(engine.getCatalogType(), engine.getEngineId(), engine.getEngineName()); - return new File((assetsFolder + "/" + pipelineFileName.trim()).replace("\\", "/")); + // the PIPELINE value is a path inside the assets folder (a leading slash was always ignored) + String relative = pipelineFileName.trim().replaceFirst("^[/\\\\]+", ""); + return new File(Utility.pathWithin(assetsFolder, relative, "pipeline file").replace("\\", "/")); + } + + // a PIPELINE value outside the assets folder is logged and the engine loads without a pipeline + private static File pipelineFileOrNull(IEngine engine, String pipelineFileName) { + try { + return pipelineFile(engine, pipelineFileName); + } catch (IllegalArgumentException e) { + return null; + } } } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index 9f5ab40e99..fe5792a202 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -1256,7 +1256,12 @@ public static long download(String url, Map headers, File file, // 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()); + File saved = HttpHelperUtility.getRequestFileDownload(url, headers, null, null, null, folder, + temp.getName()); + // only the temp file named above is moved or deleted, never a path the helper hands back + if (!temp.getCanonicalFile().equals(saved.getCanonicalFile())) { + throw new IllegalStateException("The download was not saved as " + temp.getName()); + } long size = temp.length(); checkDownloadSize(size, name); if (size > 0) { diff --git a/src/prerna/util/InternalUtility.java b/src/prerna/util/InternalUtility.java index b1f329944d..eadf1aa8e8 100644 --- a/src/prerna/util/InternalUtility.java +++ b/src/prerna/util/InternalUtility.java @@ -1239,13 +1239,13 @@ public static Properties getEngineDetails(String engineId) { // write the properties file or not // return the properties String baseFolder = Utility.getDIHelperProperty(Constants.BASE_FOLDER); - File engineDir = new File( - Utility.normalizeParam(baseFolder) + File.separator + "engines" + File.separator + engineId); + File engineDir = new File(Utility.childPath( + Utility.normalizeParam(baseFolder) + File.separator + "engines", engineId, "engine id")); if (!engineDir.exists()) { engineDir.mkdirs(); } - File owlFile = new File(engineDir.getAbsolutePath() + File.separator + engineId + ".owl"); + File owlFile = new File(Utility.childPath(engineDir.getAbsolutePath(), engineId + ".owl", "engine id")); // engine owlFileName FileUtils.writeStringToFile(owlFile, owl); prop.replace(Constants.OWL, owlFile.getAbsolutePath()); diff --git a/src/prerna/util/UploadUtilities.java b/src/prerna/util/UploadUtilities.java index 9ee3d9a165..800d3ace80 100644 --- a/src/prerna/util/UploadUtilities.java +++ b/src/prerna/util/UploadUtilities.java @@ -1540,8 +1540,9 @@ private static void writeSmssProperty(BufferedWriter bufferedWriter, String key, * @return */ private static String getEngineTempSmssLoc(IEngine.CATALOG_TYPE engineType, String engineId, String engineName) { - return EngineUtility.getLocalEngineBaseDirectory(engineType) + "/" - + SmssUtilities.getUniqueName(engineName, engineId) + ".temp"; + // the id and name come from callers and remote APIs, so the file has to stay in the engine folder + return Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType), + SmssUtilities.getUniqueName(engineName, engineId) + ".temp", "engine name"); } /** diff --git a/src/prerna/util/Utility.java b/src/prerna/util/Utility.java index 3111d0d515..c99ef4cd6b 100644 --- a/src/prerna/util/Utility.java +++ b/src/prerna/util/Utility.java @@ -1813,6 +1813,38 @@ public static String requireSafePathSegment(String value, String what) { return value; } + // one name (e.g. an id from the DB or a remote API) under a folder; logs and throws IllegalArgumentException + // unless it is a single safe name whose normalized path is a direct child of the folder + public static String childPath(String folder, String name, String what) { + requireSafePathSegment(name, what); + Path base = Path.of(folder).toAbsolutePath().normalize(); + Path child = base.resolve(name).normalize(); + if (!child.startsWith(base) || !base.equals(child.getParent())) { + classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(name)); + throw new IllegalArgumentException("Not a valid " + what); + } + // same string form callers had before (folder + separator + name), from the checked name + return folder + File.separator + child.getFileName(); + } + + // a relative path (sub folders allowed) under a folder; logs and throws IllegalArgumentException when it is + // blank, absolute, changes under NFKC or would leave the folder; returns the normalized path + public static String pathWithin(String folder, String relative, String what) { + if (relative == null || relative.isBlank() || relative.indexOf('\0') >= 0 + || !relative.equals(Normalizer.normalize(relative, Form.NFKC))) { + classLogger.warn("Refused {} that is not a plain relative path: {}", what, cleanLogString(relative)); + throw new IllegalArgumentException("Not a valid " + what); + } + Path base = Path.of(folder).toAbsolutePath().normalize(); + Path rel = Path.of(relative.replace('\\', '/')); + Path target = base.resolve(rel).normalize(); + if (rel.isAbsolute() || !target.startsWith(base) || target.equals(base)) { + classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(relative)); + throw new IllegalArgumentException("Not a valid " + what); + } + return target.toString(); + } + /** * Resolves a file inside a folder and returns the real location of the file. * The file path must be relative to the folder. Both the folder and the file From 317d31a11b54aa6c01f68ab6c22f12777ed1df88 Mon Sep 17 00:00:00 2001 From: Kunal Patel Date: Wed, 25 Nov 2026 16:31:39 -0500 Subject: [PATCH 2/2] fix(paths): compare real paths and refuse bad engine names before writing - pathWithin resolves real paths, so a symlink in the folder cannot lead outside it - both helpers refuse a blank folder and log names the file system rejects - an invalid PIPELINE value refuses the engine instead of running it without guardrails - validateEngine and the temp smss check the engine id and name on their own - one external engine that cannot be written is skipped, the sync goes on - null checks for the PIPELINE value and the OneDrive download result --- .../external/ExternalAuthorizationHelper.java | 60 ++++++++++------- .../impl/pipeline/EngineProxyFactory.java | 32 ++++++--- .../ms/onedrive/MicrosoftOneDriveHelper.java | 2 +- src/prerna/util/UploadUtilities.java | 10 ++- src/prerna/util/Utility.java | 67 +++++++++++++++++-- 5 files changed, 130 insertions(+), 41 deletions(-) diff --git a/src/prerna/auth/external/ExternalAuthorizationHelper.java b/src/prerna/auth/external/ExternalAuthorizationHelper.java index 26a7695180..decb238017 100644 --- a/src/prerna/auth/external/ExternalAuthorizationHelper.java +++ b/src/prerna/auth/external/ExternalAuthorizationHelper.java @@ -95,7 +95,6 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep String engineName = (String) newE.get("engineName"); IEngine.CATALOG_TYPE engineType = (IEngine.CATALOG_TYPE) newE.get("engineType"); String engineSubType = (String) newE.get("engineSubType"); - Map properties = null; // the id and name make up file and folder names below if (!Utility.isSafePathSegment(engineId) || !Utility.isSafePathSegment(engineName)) { @@ -104,36 +103,49 @@ public static void updateEnginePermissionsBasedOnApiCall(User user) throws Excep continue; } - // TODO: need to expand on logic for the class to initialize - String engineClass = null; - if(engineType == IEngine.CATALOG_TYPE.DATABASE) { - engineClass = RDBMSNativeEngine.class.getName(); - - properties = new HashMap<>(); - properties.put(Constants.RDBMS_TYPE, engineSubType); - properties.put(Constants.OWL, Constants.DATABASE_FOLDER+"/@ENGINE@/"+engineName+"_OWL.OWL"); + // one engine that cannot be written (e.g. a name the file system refuses) does not stop the others + try { + createExternalEngine(engineId, engineName, engineType, engineSubType); + } catch (IllegalArgumentException e) { + classLogger.warn("Skipping the external engine '{}' ('{}'): {}", Utility.cleanLogString(engineId), + Utility.cleanLogString(engineName), Utility.cleanLogString(e.getMessage())); } - - File tempSmss = UploadUtilities.createTemporaryEngineSmss(engineType, engineId, engineName, engineClass, properties); - InternalUtility.setEngineSmssPath(engineId, tempSmss.getAbsolutePath()); - File smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); - FileUtils.copyFile(tempSmss, smssFile); - InternalUtility.setEngineSmssPath(engineId, smssFile.getAbsolutePath()); - tempSmss.delete(); - - // also make the folder to persist... even if empty - String engineFolder = Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType), - SmssUtilities.getUniqueName(engineName, engineId), "engine folder"); - File eFolder = new File(engineFolder); - eFolder.mkdir(); - - ClusterUtil.pushEngine(engineId); } } catch (Exception e) { classLogger.error(Constants.STACKTRACE, e); throw e; } } + + // writes the smss and folder of an engine the external API granted, then pushes it + private static void createExternalEngine(String engineId, String engineName, IEngine.CATALOG_TYPE engineType, + String engineSubType) throws Exception { + Map properties = null; + // TODO: need to expand on logic for the class to initialize + String engineClass = null; + if(engineType == IEngine.CATALOG_TYPE.DATABASE) { + engineClass = RDBMSNativeEngine.class.getName(); + + properties = new HashMap<>(); + properties.put(Constants.RDBMS_TYPE, engineSubType); + properties.put(Constants.OWL, Constants.DATABASE_FOLDER+"/@ENGINE@/"+engineName+"_OWL.OWL"); + } + + File tempSmss = UploadUtilities.createTemporaryEngineSmss(engineType, engineId, engineName, engineClass, properties); + InternalUtility.setEngineSmssPath(engineId, tempSmss.getAbsolutePath()); + File smssFile = new File(tempSmss.getAbsolutePath().replace(".temp", ".smss")); + FileUtils.copyFile(tempSmss, smssFile); + InternalUtility.setEngineSmssPath(engineId, smssFile.getAbsolutePath()); + tempSmss.delete(); + + // also make the folder to persist... even if empty + String engineFolder = Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType), + SmssUtilities.getUniqueName(engineName, engineId), "engine folder"); + File eFolder = new File(engineFolder); + eFolder.mkdir(); + + ClusterUtil.pushEngine(engineId); + } /** * diff --git a/src/prerna/engine/impl/pipeline/EngineProxyFactory.java b/src/prerna/engine/impl/pipeline/EngineProxyFactory.java index 7c973009d9..0d664e2eb6 100644 --- a/src/prerna/engine/impl/pipeline/EngineProxyFactory.java +++ b/src/prerna/engine/impl/pipeline/EngineProxyFactory.java @@ -32,6 +32,9 @@ import java.util.ArrayList; import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + import prerna.engine.api.ICustomEmbeddingsFunctionEngine; import prerna.engine.api.IDatabaseEngine; import prerna.engine.api.IEmbeddedRDBMSServerEngine; @@ -59,6 +62,8 @@ */ public class EngineProxyFactory { + private static final Logger classLogger = LogManager.getLogger(EngineProxyFactory.class); + /** * * @param engine @@ -90,7 +95,7 @@ private static IModelEngine createGuardedModelEngine(IModelEngine engine, boolea if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -125,7 +130,7 @@ public static IDatabaseEngine createGuardedDatabaseEngine(IDatabaseEngine engine if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -158,7 +163,7 @@ public static IStorageEngine createGuardedStorageEngine(IStorageEngine engine) { if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -186,7 +191,7 @@ public static IFunctionEngine createGuardedFunctionEngine(IFunctionEngine engine if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -222,7 +227,7 @@ public static IVectorDatabaseEngine createGuardedVectorEngine(IVectorDatabaseEng if (engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -245,7 +250,7 @@ public static IProject createGuardedProject(IProject engine) { if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -268,7 +273,7 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) { if (engine != null && engine.getSmssProp().containsKey(IEngine.PIPELINE)) { String pipelineValue = engine.getSmssProp().getProperty(IEngine.PIPELINE); if (pipelineValue != null && !pipelineValue.isBlank()) { - jsonFile = pipelineFileOrNull(engine, pipelineValue); + jsonFile = checkedPipelineFile(engine, pipelineValue); } } @@ -288,17 +293,24 @@ public static IVenvEngine createGuardedVenvEngine(IVenvEngine engine) { public static File pipelineFile(IEngine engine, String pipelineFileName) { String assetsFolder = EngineUtility.getSpecificEngineAssetsFolder(engine.getCatalogType(), engine.getEngineId(), engine.getEngineName()); + if (pipelineFileName == null) { + throw new IllegalArgumentException("Not a valid pipeline file"); + } // the PIPELINE value is a path inside the assets folder (a leading slash was always ignored) String relative = pipelineFileName.trim().replaceFirst("^[/\\\\]+", ""); return new File(Utility.pathWithin(assetsFolder, relative, "pipeline file").replace("\\", "/")); } - // a PIPELINE value outside the assets folder is logged and the engine loads without a pipeline - private static File pipelineFileOrNull(IEngine engine, String pipelineFileName) { + // a PIPELINE value that is not a file in the assets folder holds guardrails that cannot be applied, so the + // engine is refused, as it is when its pipeline file cannot be read + private static File checkedPipelineFile(IEngine engine, String pipelineFileName) { try { return pipelineFile(engine, pipelineFileName); } catch (IllegalArgumentException e) { - return null; + classLogger.error("The PIPELINE value of engine {} is not a file inside its assets folder: {}", + engine.getEngineId(), Utility.cleanLogString(pipelineFileName)); + throw new IllegalStateException("The guardrail configuration for engine " + engine.getEngineId() + + " is not inside its assets folder, so it will not run without its guardrails", e); } } diff --git a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java index fe5792a202..a27d1945cc 100644 --- a/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java +++ b/src/prerna/io/connector/ms/onedrive/MicrosoftOneDriveHelper.java @@ -1259,7 +1259,7 @@ public static long download(String url, Map headers, File file, File saved = HttpHelperUtility.getRequestFileDownload(url, headers, null, null, null, folder, temp.getName()); // only the temp file named above is moved or deleted, never a path the helper hands back - if (!temp.getCanonicalFile().equals(saved.getCanonicalFile())) { + if (saved == null || !temp.getCanonicalFile().equals(saved.getCanonicalFile())) { throw new IllegalStateException("The download was not saved as " + temp.getName()); } long size = temp.length(); diff --git a/src/prerna/util/UploadUtilities.java b/src/prerna/util/UploadUtilities.java index 800d3ace80..8881118e70 100644 --- a/src/prerna/util/UploadUtilities.java +++ b/src/prerna/util/UploadUtilities.java @@ -278,6 +278,9 @@ public static void validateEngine(IEngine.CATALOG_TYPE engineType, User user, St if (engineName == null || engineName.isEmpty()) { throw new IllegalArgumentException("Need to provide a name for the database"); } + // both become the engine folder and file names, so check them before anything is written + Utility.requireSafePathSegment(engineName, "engine name"); + Utility.requireSafePathSegment(engineId, "engine id"); // need to make sure engine folder doesn't already exist String engineLocation = EngineUtility.getSpecificEngineBaseFolder(engineType, engineId, engineName); @@ -1540,7 +1543,12 @@ private static void writeSmssProperty(BufferedWriter bufferedWriter, String key, * @return */ private static String getEngineTempSmssLoc(IEngine.CATALOG_TYPE engineType, String engineId, String engineName) { - // the id and name come from callers and remote APIs, so the file has to stay in the engine folder + // the id and name come from callers and remote APIs, so the file has to stay in the engine folder; + // each is checked on its own, since the unique name normalizes away segments such as .. + Utility.requireSafePathSegment(engineId, "engine id"); + if (engineName != null) { + Utility.requireSafePathSegment(engineName, "engine name"); + } return Utility.childPath(EngineUtility.getLocalEngineBaseDirectory(engineType), SmssUtilities.getUniqueName(engineName, engineId) + ".temp", "engine name"); } diff --git a/src/prerna/util/Utility.java b/src/prerna/util/Utility.java index c99ef4cd6b..0bad6765d6 100644 --- a/src/prerna/util/Utility.java +++ b/src/prerna/util/Utility.java @@ -42,6 +42,7 @@ import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.nio.file.InvalidPathException; import java.nio.file.LinkOption; import java.nio.file.Path; import java.security.SecureRandom; @@ -1817,8 +1818,8 @@ public static String requireSafePathSegment(String value, String what) { // unless it is a single safe name whose normalized path is a direct child of the folder public static String childPath(String folder, String name, String what) { requireSafePathSegment(name, what); - Path base = Path.of(folder).toAbsolutePath().normalize(); - Path child = base.resolve(name).normalize(); + Path base = checkedBaseFolder(folder, what); + Path child = base.resolve(checkedPath(name, what)).normalize(); if (!child.startsWith(base) || !base.equals(child.getParent())) { classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(name)); throw new IllegalArgumentException("Not a valid " + what); @@ -1835,16 +1836,72 @@ public static String pathWithin(String folder, String relative, String what) { classLogger.warn("Refused {} that is not a plain relative path: {}", what, cleanLogString(relative)); throw new IllegalArgumentException("Not a valid " + what); } - Path base = Path.of(folder).toAbsolutePath().normalize(); - Path rel = Path.of(relative.replace('\\', '/')); + Path rel = checkedPath(relative.replace('\\', '/'), what); + // real path of the folder, so a link above it compares as it really is + Path base = realPathOfExisting(checkedBaseFolder(folder, what)); Path target = base.resolve(rel).normalize(); - if (rel.isAbsolute() || !target.startsWith(base) || target.equals(base)) { + if (rel.isAbsolute() || !target.startsWith(base) || target.equals(base) || leavesThroughLink(base, target)) { classLogger.warn("Refused {} that leaves its folder: {}", what, cleanLogString(relative)); throw new IllegalArgumentException("Not a valid " + what); } return target.toString(); } + // a blank folder would resolve against the working directory + private static Path checkedBaseFolder(String folder, String what) { + if (folder == null || folder.isBlank()) { + throw new IllegalArgumentException("The folder for the " + what + " must not be blank"); + } + return Path.of(folder).toAbsolutePath().normalize(); + } + + // characters the file system does not allow (e.g. : on Windows) are logged like any other refused value + private static Path checkedPath(String value, String what) { + try { + return Path.of(value); + } catch (InvalidPathException e) { + classLogger.warn("Refused {} that is not a valid path: {}", what, cleanLogString(value)); + throw new IllegalArgumentException("Not a valid " + what, e); + } + } + + // the real path of the nearest existing part, so a folder that is not created yet still compares true + private static Path realPathOfExisting(Path path) { + Path existing = path; + while (existing != null && !Files.exists(existing)) { + existing = existing.getParent(); + } + if (existing == null) { + return path; + } + try { + return existing.toRealPath().resolve(existing.relativize(path)).normalize(); + } catch (IOException e) { + throw new IllegalArgumentException("The folder cannot be resolved: " + path, e); + } + } + + // a link below the folder (or the target itself) must not lead outside it + private static boolean leavesThroughLink(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 below the folder exists yet + return false; + } + try { + return !existing.toRealPath().startsWith(base); + } catch (IOException e) { + // e.g. a link to nothing + return true; + } + } + /** * Resolves a file inside a folder and returns the real location of the file. * The file path must be relative to the folder. Both the folder and the file