1e67f5
commit 78cf73473dda5ceee3eecda5169621f36b93c3db
1e67f5
Author: Jiri Vanek <jvanek@redhat.com>
1e67f5
Date:   Tue Jun 18 15:37:47 2019 +0200
1e67f5
1e67f5
    Fixed bug when relative path (..) could leak up (even out of cache)
1e67f5
1e67f5
--- a/netx/net/sourceforge/jnlp/cache/CacheUtil.java
1e67f5
+++ a/netx/net/sourceforge/jnlp/cache/CacheUtil.java
1e67f5
@@ -696,46 +696,68 @@
1e67f5
             path.append(location.getPort());
1e67f5
             path.append(File.separatorChar);
1e67f5
         }
1e67f5
-        path.append(location.getPath().replace('/', File.separatorChar));
1e67f5
-        if (location.getQuery() != null && !location.getQuery().trim().isEmpty()) {
1e67f5
-            path.append(".").append(location.getQuery());
1e67f5
-        }
1e67f5
-
1e67f5
-        File candidate = new File(FileUtils.sanitizePath(path.toString()));
1e67f5
-        if (candidate.getName().length() > 255) {
1e67f5
-            /**
1e67f5
-             * When filename is longer then 255 chars, then then various
1e67f5
-             * filesytems have issues to save it. By saving the file by its
1e67f5
-             * summ, we are trying to prevent collision of two files differs in
1e67f5
-             * suffixes (general suffix of name, not only 'filetype suffix')
1e67f5
-             * only. It is also preventing bug when truncate (files with 1000
1e67f5
-             * chars hash in query) cuts to much.
1e67f5
-             */
1e67f5
+        String locationPath = location.getPath().replace('/', File.separatorChar);
1e67f5
+        if (locationPath.contains("..")){
1e67f5
             try {
1e67f5
-                MessageDigest md = MessageDigest.getInstance("SHA-256");
1e67f5
-                byte[] sum = md.digest(candidate.getName().getBytes(StandardCharsets.UTF_8));
1e67f5
-                //convert the byte to hex format method 2
1e67f5
-                StringBuilder hexString = new StringBuilder();
1e67f5
-                for (int i = 0; i < sum.length; i++) {
1e67f5
-                    hexString.append(Integer.toHexString(0xFF & sum[i]));
1e67f5
-                }
1e67f5
-                String extension = "";
1e67f5
-                int i = candidate.getName().lastIndexOf('.');
1e67f5
-                if (i > 0) {
1e67f5
-                    extension = candidate.getName().substring(i);//contains dot
1e67f5
-                }
1e67f5
-                if (extension.length() < 10 && extension.length() > 1) {
1e67f5
-                    hexString.append(extension);
1e67f5
-                }
1e67f5
-                candidate = new File(candidate.getParentFile(), hexString.toString());
1e67f5
+                /**
1e67f5
+                 * if path contains .. then it can harm lcoal system
1e67f5
+                 * So without mercy, hash it
1e67f5
+                 */
1e67f5
+                String hexed = hex(new File(locationPath).getName(), locationPath);
1e67f5
+                return new File(path.toString(), hexed.toString());
1e67f5
             } catch (NoSuchAlgorithmException ex) {
1e67f5
-                // should not occure, cite from javadoc:
1e67f5
-                // every java iomplementation should support
1e67f5
+                // should not occur, cite from javadoc:
1e67f5
+                // every java implementation should support
1e67f5
                 // MD5 SHA-1 SHA-256
1e67f5
                 throw new RuntimeException(ex);
1e67f5
             }
1e67f5
-        }
1e67f5
-        return candidate;
1e67f5
+        } else {
1e67f5
+            path.append(locationPath);
1e67f5
+            if (location.getQuery() != null && !location.getQuery().trim().isEmpty()) {
1e67f5
+                path.append(".").append(location.getQuery());
1e67f5
+            }
1e67f5
+
1e67f5
+            File candidate = new File(FileUtils.sanitizePath(path.toString()));
1e67f5
+            try {
1e67f5
+                if (candidate.getName().length() > 255) {
1e67f5
+                    /**
1e67f5
+                     * When filename is longer then 255 chars, then then various
1e67f5
+                     * filesystems have issues to save it. By saving the file by its
1e67f5
+                     * sum, we are trying to prevent collision of two files differs in
1e67f5
+                     * suffixes (general suffix of name, not only 'filetype suffix')
1e67f5
+                     * only. It is also preventing bug when truncate (files with 1000
1e67f5
+                     * chars hash in query) cuts to much.
1e67f5
+                     */
1e67f5
+                    String hexed = hex(candidate.getName(), candidate.getName());
1e67f5
+                    candidate = new File(candidate.getParentFile(), hexed.toString());
1e67f5
+                }
1e67f5
+            } catch (NoSuchAlgorithmException ex) {
1e67f5
+                // should not occur, cite from javadoc:
1e67f5
+                // every java implementation should support
1e67f5
+                // MD5 SHA-1 SHA-256
1e67f5
+                throw new RuntimeException(ex);
1e67f5
+            }
1e67f5
+            return candidate;
1e67f5
+        }
1e67f5
+    }
1e67f5
+
1e67f5
+    private static String hex(String origName, String candidate) throws NoSuchAlgorithmException {
1e67f5
+        MessageDigest md = MessageDigest.getInstance("SHA-256");
1e67f5
+        byte[] sum = md.digest(candidate.getBytes(StandardCharsets.UTF_8));
1e67f5
+        //convert the byte to hex format method 2
1e67f5
+        StringBuilder hexString = new StringBuilder();
1e67f5
+        for (int i = 0; i < sum.length; i++) {
1e67f5
+            hexString.append(Integer.toHexString(0xFF & sum[i]));
1e67f5
+        }
1e67f5
+        String extension = "";
1e67f5
+        int i = origName.lastIndexOf('.');
1e67f5
+        if (i > 0) {
1e67f5
+            extension = origName.substring(i);//contains dot
1e67f5
+        }
1e67f5
+        if (extension.length() < 10 && extension.length() > 1) {
1e67f5
+            hexString.append(extension);
1e67f5
+        }
1e67f5
+        return hexString.toString();
1e67f5
     }
1e67f5
 
1e67f5
     /**
1e67f5
diff --git a/netx/net/sourceforge/jnlp/util/FileUtils.java b/netx/net/sourceforge/jnlp/util/FileUtils.java
1e67f5
index 89216375..a5356e08 100644
1e67f5
--- a/netx/net/sourceforge/jnlp/util/FileUtils.java
1e67f5
+++ b/netx/net/sourceforge/jnlp/util/FileUtils.java
1e67f5
@@ -183,6 +183,13 @@
1e67f5
      */
1e67f5
     public static void createParentDir(File f, String eMsg) throws IOException {
1e67f5
         File parent = f.getParentFile();
1e67f5
+        // warning, linux and windows behave differently. Below snippet will pass on win(security hole), fail on linux
1e67f5
+        // warning  mkdir is canonicaling, but exists/isDirectory is not. So  where mkdirs return true, and really creates dir, isDirectory can still return false
1e67f5
+        // can be seen on this example
1e67f5
+        // mkdirs /a/b/../c
1e67f5
+        // where b do not exists will lead creation of /a/c
1e67f5
+        // but exists on /a/b/../c is false on linux  even afterwards
1e67f5
+        // without hexing of .. paths,
1e67f5
         if (!parent.isDirectory() && !parent.mkdirs()) {
1e67f5
             throw new IOException(R("RCantCreateDir",
1e67f5
                     eMsg == null ? parent : eMsg));
1e67f5
diff --git a/tests/netx/unit/net/sourceforge/jnlp/cache/CacheUtilTest.java b/tests/netx/unit/net/sourceforge/jnlp/cache/CacheUtilTest.java
1e67f5
index 6422246b..0d2d9811 100644
1e67f5
--- a/tests/netx/unit/net/sourceforge/jnlp/cache/CacheUtilTest.java
1e67f5
+++ b/tests/netx/unit/net/sourceforge/jnlp/cache/CacheUtilTest.java
1e67f5
@@ -88,6 +88,53 @@ public class CacheUtilTest {
1e67f5
         final File expected = new File("/tmp/https/example.com/5050/applet/e4f3cf11f86f5aa33f424bc3efe3df7a9d20837a6f1a5bbbc60c1f57f3780a4");
1e67f5
         Assert.assertEquals(expected, CacheUtil.urlToPath(u, "/tmp"));
1e67f5
     }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasic() throws Exception {
1e67f5
+        final URL u = new URL("https://example.com/applet/../my.jar");
1e67f5
+        final File expected = new File("/tmp/https/example.com/abca4723622ed60db3dea12cbe2402622a74f7a49b73e23b55988e4eee5ded.jar");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasicLong() throws Exception {
1e67f5
+        final URL u = new URL("https://example.com/applet/../my.jar.q_SlNFU1NJT05JRD02OUY1ODVCNkJBOTM1NThCQjdBMTA5RkQyNDZEQjEwRi5wcm9kX3RwdG9tY2F0MjE1X2p2bTsgRW50cnVzdFRydWVQYXNzUmVkaXJlY3RVcmw9Imh0dHBzOi8vZWZzLnVzcHRvLmdvdi9FRlNXZWJVSVJlZ2lzdGVyZWQvRUZTV2ViUmVnaXN0ZXJlZCI7IFRDUFJPRFBQQUlSc2Vzc2lvbj02MjIxMjk0MTguMjA0ODAuMDAwMA\"");
1e67f5
+        final File expected = new File("/tmp/https/example.com/ec97413e3f6eee8215ecc8375478cc1ae5f44f18241b9375361d5dfcd7b0ec");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasic2() throws Exception {
1e67f5
+        final URL u = new URL("https://example.com/../my.jar");
1e67f5
+        final File expected = new File("/tmp/https/example.com/eb1a56bed34523dbe7ad84d893ebc31a8bbbba9ce3f370e42741b6a5f067c140.jar");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasicEvil() throws Exception {
1e67f5
+        final URL u = new URL("https://example.com/../../my.jar");
1e67f5
+        final File expected = new File("/tmp/https/example.com/db464f11d68af73e37eefaef674517b6be23f0e4a5738aaee774ecf5b58f1bfc.jar");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasicEvil2() throws Exception {
1e67f5
+        final URL u = new URL("https://example.com:99/../../../my.jar");
1e67f5
+        final File expected = new File("/tmp/https/example.com/99/95401524c345e0d554d4d77330e86c98a77b9bb58a0f93094204df446b356.jar");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
+    @Test
1e67f5
+    public void tesPathUpNoGoBasicEvilest() throws Exception {
1e67f5
+        final URL u = new URL("https://example2.com/something/../../../../../../../../../../../my.jar");
1e67f5
+        final File expected = new File("/tmp/https/example2.com/a8df64388f5b84d5f635e4d6dea5f4d2f692ae5381f8ec6736825ff8d6ff2c0.jar");
1e67f5
+        File r = CacheUtil.urlToPath(u, "/tmp/");
1e67f5
+        Assert.assertEquals(expected, r);
1e67f5
+    }
1e67f5
     
1e67f5
     
1e67f5
     @Test
1e67f5
diff --git a/tests/netx/unit/net/sourceforge/jnlp/runtime/JNLPClassLoaderTest.java b/tests/netx/unit/net/sourceforge/jnlp/runtime/JNLPClassLoaderTest.java
1e67f5
index 100d9150..7580d23b 100644
1e67f5
--- a/tests/netx/unit/net/sourceforge/jnlp/runtime/JNLPClassLoaderTest.java
1e67f5
+++ b/tests/netx/unit/net/sourceforge/jnlp/runtime/JNLPClassLoaderTest.java
1e67f5
@@ -43,6 +43,8 @@
1e67f5
 import java.io.File;
1e67f5
 import java.io.FileOutputStream;
1e67f5
 import java.io.InputStream;
1e67f5
+import java.net.URL;
1e67f5
+import java.nio.charset.Charset;
1e67f5
 import java.nio.file.Files;
1e67f5
 import java.util.Arrays;
1e67f5
 import java.util.List;
1e67f5
@@ -55,6 +57,12 @@
1e67f5
 import net.sourceforge.jnlp.browsertesting.browsers.firefox.FirefoxProfilesOperator;
1e67f5
 import net.sourceforge.jnlp.cache.UpdatePolicy;
1e67f5
 import net.sourceforge.jnlp.config.DeploymentConfiguration;
1e67f5
+import net.sourceforge.jnlp.config.PathsAndFiles;
1e67f5
+import net.sourceforge.jnlp.JNLPFile;
1e67f5
+import net.sourceforge.jnlp.ServerAccess;
1e67f5
+import net.sourceforge.jnlp.ServerLauncher;
1e67f5
+import net.sourceforge.jnlp.util.StreamUtils;
1e67f5
+import net.sourceforge.jnlp.cache.CacheUtil;
1e67f5
 import net.sourceforge.jnlp.mock.DummyJNLPFileWithJar;
1e67f5
 import net.sourceforge.jnlp.security.appletextendedsecurity.AppletSecurityLevel;
1e67f5
 import net.sourceforge.jnlp.security.appletextendedsecurity.AppletStartupSecuritySettings;
1e67f5
@@ -65,6 +73,7 @@
1e67f5
 import org.junit.BeforeClass;
1e67f5
 
1e67f5
 import org.junit.Test;
1e67f5
+import org.junit.Ignore;
1e67f5
 
1e67f5
 public class JNLPClassLoaderTest extends NoStdOutErrTest {
1e67f5
 
1e67f5
@@ -138,7 +147,8 @@
1e67f5
         File tempDirectory = FileTestUtils.createTempDirectory();
1e67f5
         File jarLocation = new File(tempDirectory, "test.jar");
1e67f5
 
1e67f5
-        /* Test with main-class in manifest */ {
1e67f5
+        /* Test with main-class in manifest */
1e67f5
+        {
1e67f5
             Manifest manifest = new Manifest();
1e67f5
             manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, "DummyClass");
1e67f5
             FileTestUtils.createJarWithContents(jarLocation, manifest);
1e67f5
@@ -156,8 +166,10 @@
1e67f5
     }
1e67f5
 
1e67f5
     @Test
1e67f5
+    @Ignore
1e67f5
     public void getMainClassNameTestEmpty() throws Exception {
1e67f5
-        /* Test with-out any main-class specified */ {
1e67f5
+        /* Test with-out any main-class specified */
1e67f5
+        {
1e67f5
             File tempDirectory = FileTestUtils.createTempDirectory();
1e67f5
             File jarLocation = new File(tempDirectory, "test.jar");
1e67f5
             FileTestUtils.createJarWithContents(jarLocation /* No contents */);
1e67f5
@@ -363,4 +375,57 @@
1e67f5
         }
1e67f5
 
1e67f5
     }
1e67f5
+
1e67f5
+    @Test
1e67f5
+    public void testRelativePathInUrl() throws Exception {
1e67f5
+        CacheUtil.clearCache();
1e67f5
+        int port = ServerAccess.findFreePort();
1e67f5
+        File dir = FileTestUtils.createTempDirectory();
1e67f5
+        dir.deleteOnExit();
1e67f5
+        dir = new File(dir,"base");
1e67f5
+        dir.mkdir();
1e67f5
+        File jar = new File(dir,"j1.jar");
1e67f5
+        File jnlp = new File(dir+"/a/b/up.jnlp");
1e67f5
+        jnlp.getParentFile().mkdirs();
1e67f5
+        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("net/sourceforge/jnlp/runtime/up.jnlp");
1e67f5
+        String jnlpString = StreamUtils.readStreamAsString(is, true, "utf-8");
1e67f5
+        is.close();
1e67f5
+        jnlpString = jnlpString.replaceAll("8080", ""+port);
1e67f5
+        is = ClassLoader.getSystemClassLoader().getResourceAsStream("net/sourceforge/jnlp/runtime/j1.jar");
1e67f5
+        StreamUtils.copyStream(is, new FileOutputStream(jar));
1e67f5
+        Files.write(jnlp.toPath(),jnlpString.getBytes("utf-8"));
1e67f5
+        ServerLauncher as = ServerAccess.getIndependentInstance(jnlp.getParent(), port);
1e67f5
+        boolean verifyBackup = JNLPRuntime.isVerifying();
1e67f5
+        boolean trustBackup= JNLPRuntime.isTrustAll();
1e67f5
+        boolean securityBAckup= JNLPRuntime.isSecurityEnabled();
1e67f5
+        boolean verbose= JNLPRuntime.isDebug();
1e67f5
+        JNLPRuntime.setVerify(false);
1e67f5
+        JNLPRuntime.setTrustAll(true);
1e67f5
+        JNLPRuntime.setSecurityEnabled(false);
1e67f5
+        JNLPRuntime.setDebug(true);
1e67f5
+        try {
1e67f5
+            final JNLPFile jnlpFile1 = new JNLPFile(new URL("http://localhost:" + port + "/up.jnlp"));
1e67f5
+            final JNLPClassLoader classLoader1 = new JNLPClassLoader(jnlpFile1, UpdatePolicy.ALWAYS) {
1e67f5
+                @Override
1e67f5
+                protected void activateJars(List<JARDesc> jars) {
1e67f5
+                    super.activateJars(jars);
1e67f5
+                }
1e67f5
+
1e67f5
+            };
1e67f5
+            InputStream is1 = classLoader1.getResourceAsStream("Hello1.class");
1e67f5
+            is1.close();
1e67f5
+            is1 = classLoader1.getResourceAsStream("META-INF/MANIFEST.MF");
1e67f5
+            is1.close();
1e67f5
+            Assert.assertTrue(new File(PathsAndFiles.CACHE_DIR.getFullPath()+"/0/http/localhost/"+port+"/up.jnlp").exists());
1e67f5
+            Assert.assertTrue(new File(PathsAndFiles.CACHE_DIR.getFullPath()+"/1/http/localhost/"+port+"/f812acb32c857fd916c842e2bf4fb32b9c3837ef63922b167a7e163305058b7.jar").exists());
1e67f5
+        } finally {
1e67f5
+            JNLPRuntime.setVerify(verifyBackup);
1e67f5
+            JNLPRuntime.setTrustAll(trustBackup);
1e67f5
+            JNLPRuntime.setSecurityEnabled(securityBAckup);
1e67f5
+            JNLPRuntime.setDebug(verbose);
1e67f5
+            as.stop();
1e67f5
+        }
1e67f5
+
1e67f5
+    }
1e67f5
+
1e67f5
 }
1e67f5
diff --git a/tests/netx/unit/net/sourceforge/jnlp/runtime/up.jnlp b/tests/netx/unit/net/sourceforge/jnlp/runtime/up.jnlp
1e67f5
new file mode 100644
1e67f5
index 00000000..b22fdfb7
1e67f5
--- /dev/null
1e67f5
+++ b/tests/netx/unit/net/sourceforge/jnlp/runtime/up.jnlp
1e67f5
@@ -0,0 +1,15 @@
1e67f5
+
1e67f5
+<jnlp spec="6.0+" codebase=".">
1e67f5
+
1e67f5
+<information><title>1965</title><vendor>Nemzeti Ado- es Vamhivatal</vendor><offline-allowed/></information>
1e67f5
+
1e67f5
+
1e67f5
+<resources>
1e67f5
+  <j2se href="http://java.sun.com/products/autodl/j2se" version="1.8+" />
1e67f5
+
1e67f5
+  <jar href="http://localhost:8080/../../../base/j1.jar" version="2.0"/>
1e67f5
+</resources>
1e67f5
+
1e67f5
+<application-desc main-class="Hello1" />
1e67f5
+
1e67f5
+</jnlp>