|
| 1 | +package com.ichi2.libanki; |
| 2 | + |
| 3 | +import junit.framework.Assert; |
| 4 | + |
| 5 | +//import net.lachlanmckee.timberjunit.TimberTestRule; |
| 6 | + |
| 7 | +//import org.junit.Rule; |
| 8 | +import org.junit.Test; |
| 9 | + |
| 10 | +import java.io.File; |
| 11 | +import java.io.IOException; |
| 12 | +import java.net.URL; |
| 13 | +import java.util.Enumeration; |
| 14 | +import java.util.zip.ZipEntry; |
| 15 | +import java.util.zip.ZipFile; |
| 16 | + |
| 17 | +public class UtilsTest { |
| 18 | + |
| 19 | + // This depends on a Timber upgrade that should be pursued separately |
| 20 | + //@Rule |
| 21 | + //public TimberTestRule logAllAlwaysRule = TimberTestRule.logAllAlways(); |
| 22 | + |
| 23 | + @Test |
| 24 | + public void testZipWithPathTraversal() { |
| 25 | + |
| 26 | + ClassLoader classLoader = getClass().getClassLoader(); |
| 27 | + URL resource = classLoader.getResource("path-traversal.zip"); |
| 28 | + File file = new File(resource.getPath()); |
| 29 | + try { |
| 30 | + ZipFile zipFile = new ZipFile(file); |
| 31 | + Enumeration zipEntries = zipFile.entries(); |
| 32 | + while (zipEntries.hasMoreElements()) { |
| 33 | + ZipEntry ze2 = (ZipEntry) zipEntries.nextElement(); |
| 34 | + Utils.unzipFiles(zipFile, "/tmp", new String[]{ze2.getName()}, null); |
| 35 | + } |
| 36 | + Assert.fail("Expected an IOException"); |
| 37 | + } |
| 38 | + catch (IOException e) { |
| 39 | + Assert.assertEquals(e.getMessage(), "File is outside extraction target directory."); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + @Test |
| 44 | + public void testInvalidPaths() { |
| 45 | + try { |
| 46 | + File tmpDir = new File("/tmp"); |
| 47 | + Assert.assertFalse(Utils.isInside(new File(tmpDir, "../foo"), tmpDir)); |
| 48 | + Assert.assertFalse(Utils.isInside(new File(tmpDir, "/tmp/one/../../../foo"), tmpDir)); |
| 49 | + } catch (IOException ioe) { |
| 50 | + Assert.fail("Unexpected exception: " + ioe); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + public void testValidPaths() { |
| 56 | + try { |
| 57 | + File tmpDir = new File("/tmp"); |
| 58 | + Assert.assertTrue(Utils.isInside(new File(tmpDir, "test/file/path/no/parent"), tmpDir)); |
| 59 | + Assert.assertTrue(Utils.isInside(new File(tmpDir, "/tmp/absolute/path"), tmpDir)); |
| 60 | + Assert.assertTrue(Utils.isInside(new File(tmpDir, "test/file/../../"), tmpDir)); |
| 61 | + } catch (IOException ioe) { |
| 62 | + Assert.fail("Unexpected exception: " + ioe); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments