This is an automated email from the ASF dual-hosted git repository.

Croway pushed a commit to branch camel-4.22.x
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 67d11ddfe611067de77238cb05a7f576fbb56d9d
Author: croway <[email protected]>
AuthorDate: Mon Nov 23 18:56:31 2026 +0100

    CAMEL-27453: camel-file - starting directory check: normalize paths without 
special prefixes
    
    The jailStartingDirectory check of the producer, and the starting directory
    check of the remote file consumers, compacted the path with
    FileUtil.compactPath, which gives a special meaning to a leading http:,
    https:, file: or classpath: prefix and to a drive such as C:. A server
    gives no such meaning to them, so it could resolve the path differently
    than the check did.
    
    Compact the path for the check with a new
    GenericFileHelper.compactPathForContainment, which treats every segment
    alike, and let isWithinDirectory refuse a path with a .. segment left
    anywhere in it, not only at its start.
---
 .../camel/component/file/GenericFileHelper.java    | 79 ++++++++++++++++++--
 .../camel/component/file/GenericFileProducer.java  |  7 +-
 .../component/file/GenericFileHelperTest.java      | 78 ++++++++++++++++++++
 .../component/file/remote/RemoteFileConsumer.java  | 20 ++---
 ...emoteFileConsumerStartingDirectoryJailTest.java | 29 ++++++++
 ...emoteFileProducerStartingDirectoryJailTest.java | 85 ++++++++++++++++++++++
 ...roducerJailStartingDirectoryResolvedNameIT.java | 60 +++++++++++++++
 .../apache/camel/component/smb/SmbConsumer.java    |  5 +-
 8 files changed, 337 insertions(+), 26 deletions(-)

diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileHelper.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileHelper.java
index 8f3e6a170435..aee17489dc58 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileHelper.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileHelper.java
@@ -23,6 +23,8 @@ import java.nio.file.LinkOption;
 import java.nio.file.NoSuchFileException;
 import java.nio.file.Path;
 import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayDeque;
+import java.util.Deque;
 import java.util.function.Supplier;
 
 import org.apache.camel.Exchange;
@@ -31,6 +33,9 @@ import org.apache.camel.util.FileUtil;
 
 public final class GenericFileHelper {
 
+    // the separators that split a path into segments when compacting it for a 
containment check
+    private static final String SEPARATORS = "[/\\\\]";
+
     private GenericFileHelper() {
     }
 
@@ -179,9 +184,10 @@ public final class GenericFileHelper {
      * Determines whether a compacted target path is contained within a 
compacted directory path, using a path-segment
      * boundary comparison. Unlike a bare string prefix test, a sibling 
directory whose name merely extends the
      * directory name (for example {@code /work} versus {@code /workspace}) is 
not considered contained. A trailing
-     * separator on the directory is tolerated, and an empty directory imposes 
no boundary.
+     * separator on the directory is tolerated, and an empty directory imposes 
no boundary other than that the target
+     * must not go above it.
      *
-     * @param  compactTarget the compacted target path (see {@link 
FileUtil#compactPath(String)})
+     * @param  compactTarget the compacted target path (see {@link 
#compactPathForContainment(String, char)})
      * @param  compactDir    the compacted directory the target must stay 
within
      * @return               {@code true} if the target is the directory 
itself or a path inside it
      * @see                  #isWithinDirectory(String, String, char)
@@ -195,15 +201,15 @@ public final class GenericFileHelper {
      * separator. Remote file paths always use {@code /} regardless of the 
platform Camel runs on, so remote callers
      * must pass {@code '/'} rather than relying on {@link File#separatorChar}.
      *
-     * @param  compactTarget the compacted target path (see {@link 
FileUtil#compactPath(String, char)})
+     * @param  compactTarget the compacted target path (see {@link 
#compactPathForContainment(String, char)})
      * @param  compactDir    the compacted directory the target must stay 
within
      * @param  separator     the path separator both paths are expressed with
      * @return               {@code true} if the target is the directory 
itself or a path inside it
      */
     public static boolean isWithinDirectory(String compactTarget, String 
compactDir, char separator) {
-        // a target that still resolves upwards after compaction escapes any 
root, even when no boundary is
-        // configured, so it is never contained
-        if (compactTarget.equals("..") || compactTarget.startsWith(".." + 
separator)) {
+        // a .. segment left after compaction goes above the start of the 
path, so the target escapes any root, even
+        // when no boundary is configured, and is never contained
+        if (hasParentSegment(compactTarget)) {
             return false;
         }
         if (compactDir.isEmpty()) {
@@ -219,6 +225,67 @@ public final class GenericFileHelper {
         return compactTarget.equals(dir) || compactTarget.startsWith(dir + 
separator);
     }
 
+    /**
+     * Determines whether a path on a remote server stays within a directory 
on that server, such as a path built from a
+     * name in the listing of the server. Both paths are compacted with
+     * {@link #compactPathForContainment(String, char)}, the way the server 
resolves them.
+     *
+     * @param  target    the path, not compacted
+     * @param  directory the directory the path must stay within, not 
compacted, or empty or {@code null} when no
+     *                   directory is configured
+     * @return           {@code true} if the path is the directory itself or a 
path inside it
+     */
+    public static boolean isWithinRemoteDirectory(String target, String 
directory) {
+        if (target == null) {
+            return false;
+        }
+        return isWithinDirectory(
+                compactPathForContainment(target, '/'), 
compactPathForContainment(directory != null ? directory : "", '/'),
+                '/');
+    }
+
+    /**
+     * Compacts a path for {@link #isWithinDirectory(String, String, char)} 
the way a file system or a server resolves
+     * it: segment by segment, dropping empty and {@code .} segments, and 
dropping a {@code ..} segment together with
+     * the segment before it. Both {@code /} and {@code \} separate segments. 
Unlike
+     * {@link FileUtil#compactPath(String)} no part of the path has a special 
meaning: a scheme such as {@code http:} or
+     * {@code file:}, or a drive such as {@code C:}, is a segment like any 
other, as it is to a server. A {@code ..}
+     * segment that goes above the start of the path is kept, so that the path 
is not contained in any directory.
+     *
+     * @param  path      the path
+     * @param  separator the separator to join the segments of the compacted 
path with
+     * @return           the compacted path, which starts with the separator 
if the path starts with {@code /} or
+     *                   {@code \}, or {@code null} if the path is {@code null}
+     */
+    public static String compactPathForContainment(String path, char 
separator) {
+        if (path == null) {
+            return null;
+        }
+        boolean absolute = !path.isEmpty() && (path.charAt(0) == '/' || 
path.charAt(0) == '\\');
+        Deque<String> segments = new ArrayDeque<>();
+        for (String segment : path.split(SEPARATORS)) {
+            if (segment.isEmpty() || ".".equals(segment)) {
+                continue;
+            }
+            if ("..".equals(segment) && !segments.isEmpty() && 
!"..".equals(segments.peekLast())) {
+                segments.removeLast();
+            } else {
+                segments.addLast(segment);
+            }
+        }
+        String compacted = String.join(String.valueOf(separator), segments);
+        return absolute ? separator + compacted : compacted;
+    }
+
+    private static boolean hasParentSegment(String path) {
+        for (String segment : path.split(SEPARATORS)) {
+            if ("..".equals(segment)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
     public static String asExclusiveReadLockKey(GenericFile file, String key) {
         // use the copy from absolute path as that was the original path of the
         // file when the lock was acquired
diff --git 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileProducer.java
 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileProducer.java
index 30bac75a664f..f4c0d6bbe726 100644
--- 
a/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileProducer.java
+++ 
b/components/camel-file/src/main/java/org/apache/camel/component/file/GenericFileProducer.java
@@ -437,9 +437,10 @@ public class GenericFileProducer<T> extends 
DefaultAsyncProducer {
 
     private static void jailedCheck(String answer, String baseDir) {
         // check for file must be within starting directory (need to compact
-        // first as the name can be using relative paths via ../ etc)
-        String compatchAnswer = FileUtil.compactPath(answer);
-        String compatchBaseDir = FileUtil.compactPath(baseDir);
+        // first as the name can be using relative paths via ../ etc), the way
+        // the file system or the remote server resolves the path
+        String compatchAnswer = 
GenericFileHelper.compactPathForContainment(answer, File.separatorChar);
+        String compatchBaseDir = 
GenericFileHelper.compactPathForContainment(baseDir, File.separatorChar);
         if (!GenericFileHelper.isWithinDirectory(compatchAnswer, 
compatchBaseDir)) {
             throw new IllegalArgumentException(
                     "Cannot write file with name: " + compatchAnswer
diff --git 
a/components/camel-file/src/test/java/org/apache/camel/component/file/GenericFileHelperTest.java
 
b/components/camel-file/src/test/java/org/apache/camel/component/file/GenericFileHelperTest.java
index 6946088f319f..6fbc88030a79 100644
--- 
a/components/camel-file/src/test/java/org/apache/camel/component/file/GenericFileHelperTest.java
+++ 
b/components/camel-file/src/test/java/org/apache/camel/component/file/GenericFileHelperTest.java
@@ -26,7 +26,9 @@ import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -128,6 +130,82 @@ public class GenericFileHelperTest {
         assertFalse(GenericFileHelper.isWithinDirectory("../secret.txt", "", 
'/'));
     }
 
+    @Test
+    public void isWithinDirectoryRejectsAParentSegmentAnywhere() {
+        assertFalse(GenericFileHelper.isWithinDirectory("file:/../secret.txt", 
"", '/'));
+        assertFalse(GenericFileHelper.isWithinDirectory("poll/../secret.txt", 
"poll", '/'));
+        
assertFalse(GenericFileHelper.isWithinDirectory("poll\\..\\secret.txt", "poll", 
'/'));
+        // a name that only contains two dots is not a parent segment
+        assertTrue(GenericFileHelper.isWithinDirectory("poll/a..b", "poll", 
'/'));
+        assertTrue(GenericFileHelper.isWithinDirectory("poll/...txt", "poll", 
'/'));
+        assertTrue(GenericFileHelper.isWithinDirectory("poll/..txt", "poll", 
'/'));
+    }
+
+    @Test
+    public void compactPathForContainmentGivesNoMeaningToPrefixes() {
+        // a scheme or a drive is a segment like any other, as it is to a 
server
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("http:/../../other/secret.txt", 
'/'));
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("https:/../../other/secret.txt", 
'/'));
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("file:/../../other/secret.txt", 
'/'));
+        // file:.. is a name, not a .. segment, as it is to a server
+        assertEquals("secret.txt", 
GenericFileHelper.compactPathForContainment("file:../../secret.txt", '/'));
+        assertEquals("../secret.txt", 
GenericFileHelper.compactPathForContainment("file:../../../secret.txt", '/'));
+        assertEquals("../other/secret.txt",
+                
GenericFileHelper.compactPathForContainment("classpath:/../../other/secret.txt",
 '/'));
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("a:/../../other/secret.txt", '/'));
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("C:/../../other/secret.txt", '/'));
+        assertEquals("../other/secret.txt", 
GenericFileHelper.compactPathForContainment("HTTP:/../../other/secret.txt", 
'/'));
+        // both separators separate segments
+        assertEquals("../other/secret.txt",
+                
GenericFileHelper.compactPathForContainment("http:\\..\\..\\other\\secret.txt", 
'/'));
+        assertEquals("..\\other\\secret.txt",
+                
GenericFileHelper.compactPathForContainment("sub/../../other/secret.txt", 
'\\'));
+
+        // a .. that stays inside, and . and empty segments
+        assertEquals("poll/secret.txt", 
GenericFileHelper.compactPathForContainment("poll/sub/../secret.txt", '/'));
+        assertEquals("poll/secret.txt", 
GenericFileHelper.compactPathForContainment("poll/./sub//../secret.txt", '/'));
+        assertEquals("http:/secret.txt", 
GenericFileHelper.compactPathForContainment("http:/sub/../secret.txt", '/'));
+        // a leading separator is kept, and a .. above it too
+        assertEquals("/poll/secret.txt", 
GenericFileHelper.compactPathForContainment("/poll/secret.txt", '/'));
+        assertEquals("/../secret.txt", 
GenericFileHelper.compactPathForContainment("/../secret.txt", '/'));
+        assertEquals("", GenericFileHelper.compactPathForContainment("", '/'));
+        assertEquals("", GenericFileHelper.compactPathForContainment("sub/..", 
'/'));
+        assertNull(GenericFileHelper.compactPathForContainment(null, '/'));
+    }
+
+    @Test
+    public void prefixedPathsEscapingTheDirectoryAreNotContained() {
+        String[] escaping = {
+                "http:/../../other/secret.txt", 
"https:/../../other/secret.txt", "file:/../../other/secret.txt",
+                "file:../../../other/secret.txt", 
"classpath:/../../other/secret.txt", "a:/../../other/secret.txt",
+                "C:/../../other/secret.txt", "HTTP:/../../other/secret.txt", 
"http:\\..\\..\\other\\secret.txt",
+                "sub/../../other/secret.txt", "../secret.txt" };
+        for (String name : escaping) {
+            // no directory configured
+            assertFalse(GenericFileHelper.isWithinRemoteDirectory(name, ""), 
name);
+            assertFalse(GenericFileHelper.isWithinRemoteDirectory(name, null), 
name);
+            assertFalse(GenericFileHelper.isWithinDirectory(
+                    GenericFileHelper.compactPathForContainment(name, '/'), 
"", '/'), name);
+            // a directory configured
+            assertFalse(GenericFileHelper.isWithinRemoteDirectory("poll/" + 
name, "poll"), name);
+        }
+    }
+
+    @Test
+    public void namesThatStayInsideAreContained() {
+        String[] inside = {
+                "secret.txt", "a:b.txt", "report 10:30.txt", "file:x.txt", 
"http:x.txt", "a..b", "...txt", "sub/../x",
+                "sub/file.txt", "http:/secret.txt", "C:/data/x.txt", 
"sub\\file.txt", "sub/a\\b.txt" };
+        for (String name : inside) {
+            assertTrue(GenericFileHelper.isWithinRemoteDirectory(name, ""), 
name);
+            assertTrue(GenericFileHelper.isWithinRemoteDirectory("poll/" + 
name, "poll"), name);
+            assertTrue(GenericFileHelper.isWithinRemoteDirectory("/poll/" + 
name, "/poll/"), name);
+        }
+        // a sibling whose name merely extends the directory name is not 
contained
+        
assertFalse(GenericFileHelper.isWithinRemoteDirectory("pollute/file.txt", 
"poll"));
+        assertFalse(GenericFileHelper.isWithinRemoteDirectory(null, "poll"));
+    }
+
     @Test
     public void pathWithoutLinksIsBelowTheDirectoryWithoutResolving(@TempDir 
Path tmp) throws IOException {
         Path inbox = Files.createDirectories(tmp.resolve("inbox"));
diff --git 
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java
 
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java
index ad780f979043..52f458515e31 100644
--- 
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java
+++ 
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileConsumer.java
@@ -28,7 +28,6 @@ import org.apache.camel.component.file.GenericFileHelper;
 import org.apache.camel.component.file.GenericFileOperationFailedException;
 import org.apache.camel.component.file.GenericFileProcessStrategy;
 import org.apache.camel.support.SynchronizationAdapter;
-import org.apache.camel.util.FileUtil;
 import org.apache.camel.util.ObjectHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -40,11 +39,6 @@ public abstract class RemoteFileConsumer<T> extends 
GenericFileConsumer<T> {
 
     private static final Logger LOG = 
LoggerFactory.getLogger(RemoteFileConsumer.class);
 
-    /**
-     * Remote paths always use {@code /}, regardless of the platform Camel 
runs on.
-     */
-    private static final char REMOTE_PATH_SEPARATOR = '/';
-
     protected transient boolean loggedIn;
     protected transient boolean loggedInWarning;
     protected transient boolean autoCreatedDone;
@@ -69,18 +63,14 @@ public abstract class RemoteFileConsumer<T> extends 
GenericFileConsumer<T> {
 
     /**
      * The file name comes from the directory listing returned by the remote 
server and is not guaranteed to be a single
-     * path segment, so the path resolved from it is compacted and checked to 
still be inside the directory being polled
-     * before the file is accepted for retrieval, deletion or renaming.
+     * path segment, so the path resolved from it is compacted the way the 
server resolves it, and checked to still be
+     * inside the directory being polled before the file is accepted for 
retrieval, deletion or renaming (see
+     * {@link GenericFileHelper#isWithinRemoteDirectory(String, String)}).
      */
     @Override
     protected boolean isWithinStartingDirectory(String absoluteFilePath) {
-        if (absoluteFilePath == null) {
-            return false;
-        }
-        String directory = getEndpoint().getConfiguration().getDirectory();
-        String compactDir = directory != null ? 
FileUtil.compactPath(directory, REMOTE_PATH_SEPARATOR) : "";
-        return GenericFileHelper.isWithinDirectory(
-                FileUtil.compactPath(absoluteFilePath, REMOTE_PATH_SEPARATOR), 
compactDir, REMOTE_PATH_SEPARATOR);
+        return GenericFileHelper.isWithinRemoteDirectory(
+                absoluteFilePath, 
getEndpoint().getConfiguration().getDirectory());
     }
 
     @Override
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileConsumerStartingDirectoryJailTest.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileConsumerStartingDirectoryJailTest.java
index c46ac16334f7..ccd24beb4083 100644
--- 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileConsumerStartingDirectoryJailTest.java
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileConsumerStartingDirectoryJailTest.java
@@ -96,6 +96,35 @@ class RemoteFileConsumerStartingDirectoryJailTest extends 
CamelTestSupport {
         assertFalse(consumer.isWithinStartingDirectory("../secret.txt"));
     }
 
+    @Test
+    void shouldRejectPrefixedUpwardsPathsWhenPollingTheSessionRoot() throws 
Exception {
+        for (String uri : new String[] { "ftp://hostname";, "ftps://hostname", 
"sftp://hostname"; }) {
+            RemoteFileConsumer<?> consumer = consumer(uri);
+
+            // a scheme or a drive at the start of the name is a directory 
name to the server, like any other
+            
assertFalse(consumer.isWithinStartingDirectory("http:/../../other/secret.txt"), 
uri);
+            
assertFalse(consumer.isWithinStartingDirectory("https:/../../other/secret.txt"),
 uri);
+            
assertFalse(consumer.isWithinStartingDirectory("file:/../../other/secret.txt"), 
uri);
+            
assertFalse(consumer.isWithinStartingDirectory("classpath:/../../other/secret.txt"),
 uri);
+            
assertFalse(consumer.isWithinStartingDirectory("a:/../../other/secret.txt"), 
uri);
+            
assertFalse(consumer.isWithinStartingDirectory("http:\\..\\..\\other\\secret.txt"),
 uri);
+
+            // names that stay inside
+            assertTrue(consumer.isWithinStartingDirectory("http:/secret.txt"), 
uri);
+            assertTrue(consumer.isWithinStartingDirectory("report 10:30.txt"), 
uri);
+            
assertTrue(consumer.isWithinStartingDirectory("sub/../secret.txt"), uri);
+        }
+    }
+
+    @Test
+    void shouldRejectPrefixedPathsEscapingTheStartingDirectory() throws 
Exception {
+        RemoteFileConsumer<?> consumer = consumer("ftp://hostname/poll";);
+
+        
assertFalse(consumer.isWithinStartingDirectory("poll/http:/../../secret.txt"));
+        
assertFalse(consumer.isWithinStartingDirectory("poll/a:/../../secret.txt"));
+        
assertTrue(consumer.isWithinStartingDirectory("poll/http:/secret.txt"));
+    }
+
     @Test
     void shouldNotResolveListedFilesThatAreNotSymbolicLinks() {
         StubSftpOperations server = new 
StubSftpOperations().file("/home/camel/poll/hello.txt");
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerStartingDirectoryJailTest.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerStartingDirectoryJailTest.java
new file mode 100644
index 000000000000..fb4fb3f75e3b
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerStartingDirectoryJailTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.file.GenericFileProducer;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The name of the file to upload is resolved by the server, which gives no 
special meaning to a scheme or a drive at
+ * the start of it. Verifies that a name that the server resolves outside the 
starting directory is refused with
+ * jailStartingDirectory (the default), whether a directory is configured or 
not.
+ */
+class RemoteFileProducerStartingDirectoryJailTest extends CamelTestSupport {
+
+    private String createFileName(String uri, String name) throws Exception {
+        RemoteFileEndpoint<?> endpoint = context.getEndpoint(uri, 
RemoteFileEndpoint.class);
+        GenericFileProducer<?> producer = (GenericFileProducer<?>) 
endpoint.createProducer();
+        Exchange exchange = new DefaultExchange(context);
+        exchange.getIn().setHeader(Exchange.FILE_NAME, name);
+        return producer.createFileName(exchange);
+    }
+
+    private void assertRefused(String uri, String name) {
+        IllegalArgumentException e
+                = assertThrows(IllegalArgumentException.class, () -> 
createFileName(uri, name), uri + " " + name);
+        assertTrue(e.getMessage().contains("as the filename is jailed to the 
starting directory"), e.getMessage());
+    }
+
+    @Test
+    void shouldRefuseNamesEscapingTheSessionRoot() {
+        for (String uri : new String[] { "ftp://hostname";, "ftps://hostname", 
"sftp://hostname"; }) {
+            assertRefused(uri, "../planted.txt");
+            assertRefused(uri, "sub/../../planted.txt");
+            assertRefused(uri, "http:/../../other/planted.txt");
+            assertRefused(uri, "https:/../../other/planted.txt");
+            assertRefused(uri, "file:/../../other/planted.txt");
+            assertRefused(uri, "classpath:/../../other/planted.txt");
+            assertRefused(uri, "a:/../../other/planted.txt");
+            assertRefused(uri, "http:\\..\\..\\other\\planted.txt");
+        }
+    }
+
+    @Test
+    void shouldRefuseNamesEscapingTheStartingDirectory() {
+        assertRefused("ftp://hostname/upload";, "http:/../../planted.txt");
+        assertRefused("ftp://hostname/upload";, "a:/../../planted.txt");
+    }
+
+    @Test
+    void shouldAcceptNamesStayingInside() throws Exception {
+        assertEquals("hello.txt", createFileName("ftp://hostname";, 
"hello.txt"));
+        assertEquals("http:/hello.txt", createFileName("ftp://hostname";, 
"http:/hello.txt"));
+        assertEquals("report 10:30.txt", createFileName("ftp://hostname";, 
"report 10:30.txt"));
+        assertEquals("sub/../hello.txt", createFileName("sftp://hostname";, 
"sub/../hello.txt"));
+        assertEquals("upload/sub/hello.txt", 
createFileName("ftp://hostname/upload";, "sub/hello.txt"));
+        assertEquals("upload/a\\b.txt", 
createFileName("ftp://hostname/upload";, "a\\b.txt"));
+    }
+
+    @Test
+    void shouldAcceptAnyNameWithoutJail() throws Exception {
+        assertEquals("http:/../../other/planted.txt",
+                createFileName("ftp://hostname?jailStartingDirectory=false";, 
"http:/../../other/planted.txt"));
+    }
+}
diff --git 
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerJailStartingDirectoryResolvedNameIT.java
 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerJailStartingDirectoryResolvedNameIT.java
new file mode 100644
index 000000000000..525d15b4763d
--- /dev/null
+++ 
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpProducerJailStartingDirectoryResolvedNameIT.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.integration;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.Exchange;
+import org.junit.jupiter.api.Test;
+
+import static org.apache.camel.test.junit6.TestSupport.assertIsInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The FTP client compacts the directory of a stepwise upload before it 
changes into each of its segments, and gives no
+ * special meaning to a scheme or a drive at the start of it. Verifies that a 
name that the upload would resolve outside
+ * the starting directory is refused.
+ */
+public class FtpProducerJailStartingDirectoryResolvedNameIT extends 
FtpServerTestSupport {
+
+    private String ftpUrl(String directory) {
+        return "ftp://admin@localhost:{{ftp.server.port}}/"; + directory + 
"?password=admin";
+    }
+
+    private void assertRefused(String directory, String name) {
+        CamelExecutionException e = assertThrows(CamelExecutionException.class,
+                () -> template.sendBodyAndHeader(ftpUrl(directory), "Hello 
World", Exchange.FILE_NAME, name));
+        IllegalArgumentException iae = 
assertIsInstanceOf(IllegalArgumentException.class, e.getCause());
+        assertTrue(iae.getMessage().contains("as the filename is jailed to the 
starting directory"), iae.getMessage());
+    }
+
+    @Test
+    public void testPrefixedNameEscapingTheSessionRootIsRefused() {
+        assertRefused("", "http:/../../planted.txt");
+        assertRefused("", "a:/../../planted.txt");
+
+        assertFalse(service.ftpFile("planted.txt").toFile().exists());
+    }
+
+    @Test
+    public void testNameInsideTheStartingDirectoryIsWritten() {
+        template.sendBodyAndHeader(ftpUrl("upload/jail"), "Hello World", 
Exchange.FILE_NAME, "sub/../hello.txt");
+
+        assertTrue(service.ftpFile("upload/jail/hello.txt").toFile().exists());
+    }
+}
diff --git 
a/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbConsumer.java
 
b/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbConsumer.java
index c529b5502783..813d5279a453 100644
--- 
a/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbConsumer.java
+++ 
b/components/camel-smb/src/main/java/org/apache/camel/component/smb/SmbConsumer.java
@@ -87,9 +87,10 @@ public class SmbConsumer extends 
GenericFileConsumer<FileIdBothDirectoryInformat
         if (absoluteFilePath == null) {
             return false;
         }
+        // SMB takes \ as the path separator, and a / is sent as one, so both 
separate segments
         return GenericFileHelper.isWithinDirectory(
-                FileUtil.compactPath(absoluteFilePath, REMOTE_PATH_SEPARATOR),
-                FileUtil.compactPath(endpointPath, REMOTE_PATH_SEPARATOR), 
REMOTE_PATH_SEPARATOR);
+                GenericFileHelper.compactPathForContainment(absoluteFilePath, 
REMOTE_PATH_SEPARATOR),
+                GenericFileHelper.compactPathForContainment(endpointPath, 
REMOTE_PATH_SEPARATOR), REMOTE_PATH_SEPARATOR);
     }
 
     @Override

Reply via email to