CVE-2020-15250: Incorrect Permission Assignment for Critical Resource (CWE-732)
value: In JUnit4 from version 4.7 and before 4.13.1, the test rule TemporaryFolder contains a local information disclosure vulnerability. On Unix like systems, the system's temporary directory is shared between all users on that system. Because of this, when files and directories are written into this directory they are, by default, readable by other users on that same system. This vulnerability does not allow other users to overwrite the contents of these directories or files. This is purely an information disclosure vulnerability. This vulnerability impacts you if the JUnit tests write sensitive information, like API keys or passwords, into the temporary folder, and the JUnit tests execute in an environment where the OS has other untrusted users. Because certain JDK file system APIs were only added in JDK 1.7, this this fix is dependent upon the version of the JDK you are using. For Java 1.7 and higher users: this vulnerability is fixed in 4.13.1. For Java 1.6 and lower users: no patch is available, you must use the workaround below. If you are unable to patch, or are stuck running on Java 1.6, specifying the `java.io.tmpdir` system environment variable to a directory that is exclusively owned by the executing user will fix this vulnerability. For more information, including an example of vulnerable code, see the referenced GitHub Security Advisory.
CWE description: The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.
CVSS v3 base score: 5.5
Published: 2020-10-12T18:15Z
Repository: https://github.com/junit-team/junit4
Language: Java
Files changed: src/main/java/org/junit/rules/TemporaryFolder.java, src/test/java/org/junit/rules/TempFolderRuleTest.java
Commit date: 2020-10-11 16:56:21 +0200
Commit message: Merge pull request from GHSA-269g-pwp5-87pp

When running on Java 7 or later, temporary directories are now created
Using Java’s NIO API which restricts permissions to owner-only by
default.
Diff: diff --git a/src/main/java/org/junit/rules/TemporaryFolder.java b/src/main/java/org/junit/rules/TemporaryFolder.java
index 1a6a7706..a726c66e 100644
--- a/src/main/java/org/junit/rules/TemporaryFolder.java
+++ b/src/main/java/org/junit/rules/TemporaryFolder.java
@@ -2,10 +2,13 @@ package org.junit.rules;
 
 import static org.junit.Assert.fail;
 
 import java.io.File;
 import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 
 import org.junit.Rule;
 
 /**
  * The TemporaryFolder Rule allows creation of files and folders that should
@@ -227,11 +230,49 @@ public class TemporaryFolder extends ExternalResource {
      */
     public File newFolder() throws IOException {
         return createTemporaryFolderIn(getRoot());
     }
 
-    private File createTemporaryFolderIn(File parentFolder) throws IOException {
+    private static File createTemporaryFolderIn(File parentFolder) throws IOException {
+        try {
+            return createTemporaryFolderWithNioApi(parentFolder);
+        } catch (ClassNotFoundException ignore) {
+            // Fallback for Java 5 and 6
+            return createTemporaryFolderWithFileApi(parentFolder);
+        } catch (InvocationTargetException e) {
+            Throwable cause = e.getCause();
+            if (cause instanceof IOException) {
+                throw (IOException) cause;
+            }
+            if (cause instanceof RuntimeException) {
+                throw (RuntimeException) cause;
+            }
+            IOException exception = new IOException("Failed to create temporary folder in " + parentFolder);
+            exception.initCause(cause);
+            throw exception;
+        } catch (Exception e) {
+            throw new RuntimeException("Failed to create temporary folder in " + parentFolder, e);
+        }
+    }
+
+    private static File createTemporaryFolderWithNioApi(File parentFolder) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
+        Class<?> filesClass = Class.forName("java.nio.file.Files");
+        Object fileAttributeArray = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
+        Class<?> pathClass = Class.forName("java.nio.file.Path");
+        Object tempDir;
+        if (parentFolder != null) {
+            Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", pathClass, String.class, fileAttributeArray.getClass());
+            Object parentPath = File.class.getDeclaredMethod("toPath").invoke(parentFolder);
+            tempDir = createTempDirectoryMethod.invoke(null, parentPath, TMP_PREFIX, fileAttributeArray);
+        } else {
+            Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", String.class, fileAttributeArray.getClass());
+            tempDir = createTempDirectoryMethod.invoke(null, TMP_PREFIX, fileAttributeArray);
+        }
+        return (File) pathClass.getDeclaredMethod("toFile").invoke(tempDir);
+    }
+
+    private static File createTemporaryFolderWithFileApi(File parentFolder) throws IOException {
         File createdFolder = null;
         for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
             // Use createTempFile to get a suitable folder name.
             String suffix = ".tmp";
             File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
diff --git a/src/test/java/org/junit/rules/TempFolderRuleTest.java b/src/test/java/org/junit/rules/TempFolderRuleTest.java
index 0a82a602..b120e71e 100644
--- a/src/test/java/org/junit/rules/TempFolderRuleTest.java
+++ b/src/test/java/org/junit/rules/TempFolderRuleTest.java
@@ -1,25 +1,32 @@
 package org.junit.rules;
 
 import static org.hamcrest.CoreMatchers.hasItem;
 import static org.hamcrest.MatcherAssert.assertThat;
 import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
 import static org.junit.experimental.results.PrintableResult.testResult;
 import static org.junit.experimental.results.ResultMatchers.failureCountIs;
 import static org.junit.experimental.results.ResultMatchers.isSuccessful;
 
 import java.io.File;
 import java.io.IOException;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.Arrays;
+import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
 
 import org.junit.After;
+import org.junit.AssumptionViolatedException;
 import org.junit.Rule;
 import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
 
 public class TempFolderRuleTest {
     private static File[] createdFiles = new File[20];
 
     public static class HasTempFolder {
@@ -180,10 +187,38 @@ public class TempFolderRuleTest {
         folder.create();
         folder.delete();
         assertFalse(folder.getRoot().exists());
     }
 
+    @Test
+    public void tempFolderIsOnlyAccessibleByOwner() throws IOException {
+        TemporaryFolder folder = new TemporaryFolder();
+        folder.create();
+
+        Set<String> expectedPermissions = new TreeSet<String>(Arrays.asList("OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE"));
+        Set<String> actualPermissions = getPosixFilePermissions(folder.getRoot());
+        assertEquals(expectedPermissions, actualPermissions);
+    }
+
+    private Set<String> getPosixFilePermissions(File root) {
+        try {
+            Class<?> pathClass = Class.forName("java.nio.file.Path");
+            Object linkOptionArray = Array.newInstance(Class.forName("java.nio.file.LinkOption"), 0);
+            Class<?> filesClass = Class.forName("java.nio.file.Files");
+            Object path = File.class.getDeclaredMethod("toPath").invoke(root);
+            Method posixFilePermissionsMethod = filesClass.getDeclaredMethod("getPosixFilePermissions", pathClass, linkOptionArray.getClass());
+            Set<?> permissions = (Set<?>) posixFilePermissionsMethod.invoke(null, path, linkOptionArray);
+            SortedSet<String> convertedPermissions = new TreeSet<String>();
+            for (Object item : permissions) {
+                convertedPermissions.add(item.toString());
+            }
+            return convertedPermissions;
+        } catch (Exception e) {
+            throw new AssumptionViolatedException("Test requires at least Java 1.7", e);
+        }
+    }
+
     public static class NameClashes {
         @Rule
         public TemporaryFolder folder = new TemporaryFolder();
 
         @Test

Vulnerable code:     private File createTemporaryFolderIn(File parentFolder) throws IOException {
import org.junit.rules.TemporaryFolder;
Fixed code: import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
    private static File createTemporaryFolderIn(File parentFolder) throws IOException {
        try {
            return createTemporaryFolderWithNioApi(parentFolder);
        } catch (ClassNotFoundException ignore) {
            // Fallback for Java 5 and 6
            return createTemporaryFolderWithFileApi(parentFolder);
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            if (cause instanceof IOException) {
                throw (IOException) cause;
            }
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            }
            IOException exception = new IOException("Failed to create temporary folder in " + parentFolder);
            exception.initCause(cause);
            throw exception;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create temporary folder in " + parentFolder, e);
        }
    }

    private static File createTemporaryFolderWithNioApi(File parentFolder) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> filesClass = Class.forName("java.nio.file.Files");
        Object fileAttributeArray = Array.newInstance(Class.forName("java.nio.file.attribute.FileAttribute"), 0);
        Class<?> pathClass = Class.forName("java.nio.file.Path");
        Object tempDir;
        if (parentFolder != null) {
            Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", pathClass, String.class, fileAttributeArray.getClass());
            Object parentPath = File.class.getDeclaredMethod("toPath").invoke(parentFolder);
            tempDir = createTempDirectoryMethod.invoke(null, parentPath, TMP_PREFIX, fileAttributeArray);
        } else {
            Method createTempDirectoryMethod = filesClass.getDeclaredMethod("createTempDirectory", String.class, fileAttributeArray.getClass());
            tempDir = createTempDirectoryMethod.invoke(null, TMP_PREFIX, fileAttributeArray);
        }
        return (File) pathClass.getDeclaredMethod("toFile").invoke(tempDir);
    }

    private static File createTemporaryFolderWithFileApi(File parentFolder) throws IOException {
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.junit.AssumptionViolatedException;
    @Test
    public void tempFolderIsOnlyAccessibleByOwner() throws IOException {
        TemporaryFolder folder = new TemporaryFolder();
        folder.create();

        Set<String> expectedPermissions = new TreeSet<String>(Arrays.asList("OWNER_READ", "OWNER_WRITE", "OWNER_EXECUTE"));
        Set<String> actualPermissions = getPosixFilePermissions(folder.getRoot());
        assertEquals(expectedPermissions, actualPermissions);
    }

    private Set<String> getPosixFilePermissions(File root) {
        try {
            Class<?> pathClass = Class.forName("java.nio.file.Path");
            Object linkOptionArray = Array.newInstance(Class.forName("java.nio.file.LinkOption"), 0);
            Class<?> filesClass = Class.forName("java.nio.file.Files");
            Object path = File.class.getDeclaredMethod("toPath").invoke(root);
            Method posixFilePermissionsMethod = filesClass.getDeclaredMethod("getPosixFilePermissions", pathClass, linkOptionArray.getClass());
            Set<?> permissions = (Set<?>) posixFilePermissionsMethod.invoke(null, path, linkOptionArray);
            SortedSet<String> convertedPermissions = new TreeSet<String>();
            for (Object item : permissions) {
                convertedPermissions.add(item.toString());
            }
            return convertedPermissions;
        } catch (Exception e) {
            throw new AssumptionViolatedException("Test requires at least Java 1.7", e);
        }
    }