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

jbonofre pushed a commit to branch karaf-4.4.x
in repository https://gitbox.apache.org/repos/asf/karaf.git


The following commit(s) were added to refs/heads/karaf-4.4.x by this push:
     new 360478528f [4.4.x] Reject shell metacharacters in instance names and 
locations (#3066)
360478528f is described below

commit 360478528ffa8429c1d2905917f530fcd5d6bb49
Author: JB Onofré <[email protected]>
AuthorDate: Wed Nov 11 05:29:57 2026 +0000

    [4.4.x] Reject shell metacharacters in instance names and locations (#3066)
    
    * Reject shell metacharacters in instance names and locations
    
    #2878 rejects shell metacharacters in javaOpts, but the instance name and
    location still reach /bin/sh when a child instance is started:
    
    - ProcessImpl substitutes the working directory as plain text into the jpm
      start script, unquoted in `cd ${dir}`, so a location such as
      `/tmp/x$(id)` or `/tmp/x;id` runs a command.
    - doStart() puts the location inside double quotes in the launch command
      line (-Dkaraf.base="..." and others), where the shell still expands
      $(...) and backticks.
    - The name is the default location, and it is substituted unquoted into
      the child instance bin/start and bin/stop scripts (bin/karaf gets the
      location).
    
    Pass the jpm working directory as a single-quoted shell literal, so the
    jpm start script never interprets it, whoever the caller is. In
    InstanceServiceImpl, restrict instance names to a plain identifier syntax
    on create, clone and rename, and reject locations that contain quotes,
    line breaks, $`&|<> or (outside Windows) \ on create and clone, and again
    in doStart() for instances registered before this change. Also
    double-quote the values substituted into the child instance unix scripts.
    
    * Check the raw instance location before canonicalizing it
    
    On Windows, File.getCanonicalPath() throws an IOException for paths
    containing characters such as " or |, so validateLocation() failed with
    a RuntimeException instead of rejecting the location with an
    IllegalArgumentException. Check the raw path first, and only
    canonicalize it once it is known to be safe.
---
 .../core/internal/InstanceServiceImpl.java         | 36 +++++++++++++
 .../org/apache/karaf/instance/resources/bin/karaf  |  4 +-
 .../org/apache/karaf/instance/resources/bin/start  |  4 +-
 .../org/apache/karaf/instance/resources/bin/stop   |  4 +-
 .../core/internal/InstanceServiceImplTest.java     | 61 ++++++++++++++++++++++
 .../java/org/apache/karaf/jpm/ProcessTest.java     | 30 +++++++++++
 .../org/apache/karaf/jpm/impl/ProcessImpl.java     |  7 ++-
 .../org/apache/karaf/jpm/impl/unix/start.sh        |  5 +-
 8 files changed, 142 insertions(+), 9 deletions(-)

diff --git 
a/instance/src/main/java/org/apache/karaf/instance/core/internal/InstanceServiceImpl.java
 
b/instance/src/main/java/org/apache/karaf/instance/core/internal/InstanceServiceImpl.java
index 5c375f62ba..e231d7b213 100644
--- 
a/instance/src/main/java/org/apache/karaf/instance/core/internal/InstanceServiceImpl.java
+++ 
b/instance/src/main/java/org/apache/karaf/instance/core/internal/InstanceServiceImpl.java
@@ -93,6 +93,16 @@ public class InstanceServiceImpl implements InstanceService {
     // never contain shell metacharacters; only characters that can legally 
appear in JVM option syntax are allowed.
     private static final Pattern SAFE_JAVA_OPTS = Pattern.compile("[A-Za-z0-9_ 
\\t\\-+.,:=/@*]*");
 
+    // Instance names are substituted into the child instance scripts and are, 
by default, the last segment of the
+    // instance location, so they are restricted to a plain identifier syntax.
+    private static final Pattern SAFE_INSTANCE_NAME = 
Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_.\\-]*");
+
+    // The instance location ends up inside double quotes in the shell command 
line (see doStart) and in the child
+    // instance scripts, where /bin/sh still interprets $, ` and \ and cmd.exe 
interprets & | < >, so these
+    // characters (as well as quotes and line breaks) must never appear in it.
+    private static final Pattern UNSAFE_LOCATION_CHARS =
+            Pattern.compile(ScriptUtils.isWindows() ? "[\"$`&|<>\\r\\n]" : 
"[\"$`\\\\&|<>\\r\\n]");
+
     private LinkedHashMap<String, InstanceImpl> proxies = new 
LinkedHashMap<>();
 
     private File storageLocation;
@@ -293,6 +303,7 @@ public class InstanceServiceImpl implements InstanceService 
{
 
     public synchronized Instance createInstance(final String name, final 
InstanceSettings settings, final boolean printOutput) throws Exception {
         return execute(state -> {
+            validateName(name);
             if (state.instances.get(name) != null) {
                 throw new IllegalArgumentException("Instance '" + name + "' 
already exists");
             }
@@ -309,6 +320,7 @@ public class InstanceServiceImpl implements InstanceService 
{
             if (!karafBase.isAbsolute()) {
                 karafBase = new File(storageLocation, loc);
             }
+            validateLocation(karafBase);
             int sshPort = settings.getSshPort();
             if (sshPort <= 0) {
                 sshPort = ++state.defaultSshPortStart;
@@ -496,6 +508,26 @@ public class InstanceServiceImpl implements 
InstanceService {
         }
     }
 
+    private static void validateName(String name) {
+        if (name == null || !SAFE_INSTANCE_NAME.matcher(name).matches()) {
+            throw new IllegalArgumentException("Invalid instance name '" + 
name + "': only letters, digits and _-. "
+                    + "are allowed, and the name must not start with . or -");
+        }
+    }
+
+    private static void validateLocation(File location) throws IOException {
+        // check the raw path first: on Windows, getCanonicalPath() fails on 
some of these characters
+        checkLocation(location.getPath());
+        checkLocation(location.getCanonicalPath());
+    }
+
+    private static void checkLocation(String path) {
+        if (UNSAFE_LOCATION_CHARS.matcher(path).find()) {
+            throw new IllegalArgumentException("Invalid instance location '" + 
path + "': quotes, line breaks "
+                    + "and $`&|<> are not allowed" + (ScriptUtils.isWindows() 
? "" : ", nor \\"));
+        }
+    }
+
     private void doStart(InstanceState instance, String name, String javaOpts) 
throws IOException {
         String opts = javaOpts;
         if (opts == null || opts.length() == 0) {
@@ -511,6 +543,7 @@ public class InstanceServiceImpl implements InstanceService 
{
         String karafOpts = System.getProperty("karaf.opts", karafOptsEnv != 
null ? karafOptsEnv : "");
 
         String location = instance.loc;
+        validateLocation(new File(location));
 
         File libDir = new File(System.getProperty("karaf.home"), "lib");
         File bootLibDir = new File(libDir, "boot");
@@ -725,6 +758,7 @@ public class InstanceServiceImpl implements InstanceService 
{
 
     public void renameInstance(final String oldName, final String newName, 
final boolean printOutput) throws Exception {
         execute(state -> {
+            validateName(newName);
             if (state.instances.get(newName) != null) {
                 throw new IllegalArgumentException("Instance " + newName + " 
already exists");
             }
@@ -786,6 +820,7 @@ public class InstanceServiceImpl implements InstanceService 
{
         final int instanceRmiRegistryPort = getInstanceRmiRegistryPort(name);
         final int instanceRmiServerPort = getInstanceRmiServerPort(name);
         return execute(state -> {
+            validateName(cloneName);
             if (state.instances.get(cloneName) != null) {
                 throw new IllegalArgumentException("Instance " + cloneName + " 
already exists");
             }
@@ -800,6 +835,7 @@ public class InstanceServiceImpl implements InstanceService 
{
             if (!cloneLocation.isAbsolute()) {
                 cloneLocation = new File(storageLocation, cloneLocationPath);
             }
+            validateLocation(cloneLocation);
             // copy instance directory
             String locationPath = instance.loc;
             File location = new File(locationPath);
diff --git 
a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/karaf 
b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/karaf
index 8027492440..622044d823 100644
--- a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/karaf
+++ b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/karaf
@@ -18,8 +18,8 @@
 #
 
################################################################################
 
-KARAF_HOME=${SUBST-KARAF-HOME}
-KARAF_BASE=${SUBST-KARAF-BASE}
+KARAF_HOME="${SUBST-KARAF-HOME}"
+KARAF_BASE="${SUBST-KARAF-BASE}"
 
 export KARAF_BASE
 exec "${KARAF_HOME}/bin/karaf" "$*"
diff --git 
a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/start 
b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/start
index 80d11a58f9..02cbe1fd10 100644
--- a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/start
+++ b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/start
@@ -18,8 +18,8 @@
 #
 
################################################################################
 
-KARAF_HOME=${SUBST-KARAF-HOME}
-KARAF_NAME=${SUBST-KARAF-NAME}
+KARAF_HOME="${SUBST-KARAF-HOME}"
+KARAF_NAME="${SUBST-KARAF-NAME}"
 
 exec "${KARAF_HOME}/bin/instance" start "${KARAF_NAME}" "$@"
 
diff --git 
a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/stop 
b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/stop
index 3e8966362a..dd6488fa48 100644
--- a/instance/src/main/resources/org/apache/karaf/instance/resources/bin/stop
+++ b/instance/src/main/resources/org/apache/karaf/instance/resources/bin/stop
@@ -18,8 +18,8 @@
 #
 
################################################################################
 
-KARAF_HOME=${SUBST-KARAF-HOME}
-KARAF_NAME=${SUBST-KARAF-NAME}
+KARAF_HOME="${SUBST-KARAF-HOME}"
+KARAF_NAME="${SUBST-KARAF-NAME}"
 
 exec "${KARAF_HOME}/bin/instance" stop "${KARAF_NAME}" "$@"
 
diff --git 
a/instance/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
 
b/instance/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
index 5cf547a8ba..cf3dce81d9 100644
--- 
a/instance/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
+++ 
b/instance/src/test/java/org/apache/karaf/instance/core/internal/InstanceServiceImplTest.java
@@ -38,6 +38,8 @@ import org.junit.rules.TestName;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
 import static org.junit.Assert.assertTrue;
 
 public class InstanceServiceImplTest {
@@ -175,6 +177,65 @@ public class InstanceServiceImplTest {
         assertEquals("9999", props.get("sshPort"));
     }
 
+    @Test
+    public void testCreateInstanceRejectsUnsafeName() throws Exception {
+        InstanceServiceImpl service = new InstanceServiceImpl();
+        service.setStorageLocation(tempFolder.newFolder("instances"));
+
+        for (String unsafe : new String[] { "x$(id)", "x`id`", "x;id", "x id", 
"..", "-x" }) {
+            InstanceSettings settings = new InstanceSettings(8122, 1122, 
44444, null, null, null, null);
+            assertThrows(IllegalArgumentException.class, () -> 
service.createInstance(unsafe, settings, false));
+            assertNull(service.getInstance(unsafe));
+        }
+    }
+
+    @Test
+    public void testCreateInstanceRejectsUnsafeLocation() throws Exception {
+        InstanceServiceImpl service = new InstanceServiceImpl();
+        service.setStorageLocation(tempFolder.newFolder("instances"));
+
+        for (String unsafe : new String[] { "x$(id)", "x`id`", "x\"y", "x&id", 
"x|id" }) {
+            InstanceSettings settings = new InstanceSettings(8122, 1122, 
44444, unsafe, null, null, null);
+            assertThrows(IllegalArgumentException.class, () -> 
service.createInstance(getName(), settings, false));
+        }
+        assertNull(service.getInstance(getName()));
+    }
+
+    @Test
+    public void testCloneAndRenameInstanceRejectUnsafeNameAndLocation() throws 
Exception {
+        InstanceServiceImpl service = new InstanceServiceImpl();
+        service.setStorageLocation(tempFolder.newFolder("instances"));
+
+        InstanceSettings settings = new InstanceSettings(8122, 1122, 44444, 
getName(), null, null, null);
+        service.createInstance(getName(), settings, false);
+
+        assertThrows(IllegalArgumentException.class, () -> 
service.renameInstance(getName(), "x$(id)", false));
+        assertThrows(IllegalArgumentException.class, () -> 
service.cloneInstance(getName(), "x$(id)",
+                new InstanceSettings(8123, 1123, 44445, null, null, null, 
null), false));
+        assertThrows(IllegalArgumentException.class, () -> 
service.cloneInstance(getName(), getName() + "b",
+                new InstanceSettings(8123, 1123, 44445, "x$(id)", null, null, 
null), false));
+        assertNotNull(service.getInstance(getName()));
+        assertNull(service.getInstance(getName() + "b"));
+    }
+
+    @Test
+    public void testStartInstanceRejectsUnsafeStoredLocation() throws 
Exception {
+        InstanceServiceImpl service = new InstanceServiceImpl();
+        File storageLocation = tempFolder.newFolder("instances");
+        service.setStorageLocation(storageLocation);
+
+        InstanceSettings settings = new InstanceSettings(8122, 1122, 44444, 
getName(), null, null, null);
+        service.createInstance(getName(), settings, false);
+
+        // simulate an instance registered (e.g. by an older version) with a 
location that is unsafe in a shell
+        File storageFile = new File(storageLocation, 
InstanceServiceImpl.STORAGE_FILE);
+        Properties storage = loadStorage(storageFile);
+        storage.setProperty("item.0.loc", new File(storageLocation, 
"x$(id)").getPath());
+        saveStorage(storage, storageFile, 
"testStartInstanceRejectsUnsafeStoredLocation");
+
+        assertThrows(IllegalArgumentException.class, () -> 
service.startInstance(getName(), null));
+    }
+
     private String getName() {
         return name.getMethodName();
     }
diff --git a/instance/src/test/java/org/apache/karaf/jpm/ProcessTest.java 
b/instance/src/test/java/org/apache/karaf/jpm/ProcessTest.java
index 80da7adbe0..584a2688e0 100644
--- a/instance/src/test/java/org/apache/karaf/jpm/ProcessTest.java
+++ b/instance/src/test/java/org/apache/karaf/jpm/ProcessTest.java
@@ -17,6 +17,7 @@
 package org.apache.karaf.jpm;
 
 import java.io.File;
+import java.nio.file.Files;
 
 import junit.framework.TestCase;
 
@@ -59,6 +60,35 @@ public class ProcessTest extends TestCase {
         assertFalse(p.isRunning());
     }
 
+    public void testDirectoryIsNotInterpretedByShell() throws Exception {
+        if (ScriptUtils.isWindows()) {
+            return;
+        }
+        // any command injected through the directory name runs in the current 
working directory
+        File marker = new File("jpm-injection-marker").getAbsoluteFile();
+        marker.delete();
+        File base = Files.createTempDirectory("jpm").toFile();
+        String[] names = {
+            "$(touch jpm-injection-marker) `touch jpm-injection-marker`; touch 
jpm-injection-marker",
+            "it's"
+        };
+        try {
+            for (String name : names) {
+                File dir = new File(base, name);
+                assertTrue(dir.mkdirs());
+                new 
ProcessBuilderFactoryImpl().newBuilder().directory(dir).command("touch 
created").start();
+                assertFalse("The directory name should not have been 
interpreted by the shell", marker.exists());
+                File created = new File(dir, "created");
+                for (int i = 0; i < 50 && !created.exists(); i++) {
+                    Thread.sleep(100);
+                }
+                assertTrue("The command should have run in " + dir, 
created.exists());
+            }
+        } finally {
+            marker.delete();
+        }
+    }
+
     /*
      * When the process creation fails, no error is reported by the script
      * 
diff --git a/util/src/main/java/org/apache/karaf/jpm/impl/ProcessImpl.java 
b/util/src/main/java/org/apache/karaf/jpm/impl/ProcessImpl.java
index 41658ed602..0d36180fa8 100644
--- a/util/src/main/java/org/apache/karaf/jpm/impl/ProcessImpl.java
+++ b/util/src/main/java/org/apache/karaf/jpm/impl/ProcessImpl.java
@@ -149,10 +149,15 @@ public class ProcessImpl implements Process {
             //props.put("${out.file}", output.getCanonicalPath());
             //props.put("${err.file}", error.getCanonicalPath());
             props.put("${pid.file}", pidFile.getCanonicalPath());
-            props.put("${dir}", dir != null ? dir.getCanonicalPath() : "");
+            String dirPath = dir != null ? dir.getCanonicalPath() : "";
             if (ScriptUtils.isWindows()) {
                 command = command.replaceAll("\"", "\"\"");
+            } else {
+                // the start script is generated by plain text substitution, 
so pass the directory as a
+                // single-quoted shell literal to prevent the shell from 
interpreting characters in the path
+                dirPath = "'" + dirPath.replace("'", "'\\''") + "'";
             }
+            props.put("${dir}", dirPath);
             props.put("${command}", command);
             int ret = ScriptUtils.execute("start", props);
             if (ret != 0) {
diff --git a/util/src/main/resources/org/apache/karaf/jpm/impl/unix/start.sh 
b/util/src/main/resources/org/apache/karaf/jpm/impl/unix/start.sh
index d925e48435..0839fb9c0b 100644
--- a/util/src/main/resources/org/apache/karaf/jpm/impl/unix/start.sh
+++ b/util/src/main/resources/org/apache/karaf/jpm/impl/unix/start.sh
@@ -22,8 +22,9 @@
 #exec 2>${err.file}
 exec 1>/dev/null
 exec 2>/dev/null
-if [ "x${dir}" != "x" ]; then
-    cd ${dir}
+JPM_DIR=${dir}
+if [ "x$JPM_DIR" != "x" ]; then
+    cd "$JPM_DIR"
 fi
 nohup ${command} &
 echo $! > "${pid.file}"

Reply via email to