@@ -588,6 +588,9 @@ private static void decompressZip(File archive, String directory) throws IOExcep
588588 ZipEntry zipEntry ;
589589 while ((zipEntry = zis .getNextEntry ()) != null ) {
590590 File newFile = new File (directory , zipEntry .getName ());
591+ if (HasZipSlipVulnerability (newFile , directory )) {
592+ throw new IOException ("Bad tar entry: " + zipEntry .getName ());
593+ }
591594 if (zipEntry .isDirectory ()) {
592595 if (!newFile .isDirectory () && !newFile .mkdirs ()) {
593596 throw new IOException ("Failed to create directory " + newFile );
@@ -614,6 +617,9 @@ private static void decompress7z(File archive, String directory) throws IOExcept
614617 SevenZArchiveEntry entry ;
615618 while ((entry = sevenZFile .getNextEntry ()) != null ) {
616619 File newFile = new File (directory , entry .getName ());
620+ if (HasZipSlipVulnerability (newFile , directory )) {
621+ throw new IOException ("Bad tar entry: " + entry .getName ());
622+ }
617623 if (entry .isDirectory ()) {
618624 if (!newFile .isDirectory () && !newFile .mkdirs ()) {
619625 throw new IOException ("Failed to create directory " + newFile );
@@ -640,6 +646,9 @@ private static void decompressTar(File archive, String directory) throws IOExcep
640646 TarArchiveEntry entry ;
641647 while ((entry = tis .getNextEntry ()) != null ) {
642648 File newFile = new File (directory , entry .getName ());
649+ if (HasZipSlipVulnerability (newFile , directory )) {
650+ throw new IOException ("Bad tar entry: " + entry .getName ());
651+ }
643652 if (entry .isDirectory ()) {
644653 if (!newFile .isDirectory () && !newFile .mkdirs ()) {
645654 throw new IOException ("Failed to create directory " + newFile );
@@ -787,4 +796,12 @@ private static void decompressJar(File archive, String directory) throws IOExcep
787796 }
788797 }
789798 }
799+
800+ // Check for Zip Slip vulnerability: ensure extracted file remains within target directory
801+ // Use Path.normalize() and Path.startsWith()
802+ private static boolean HasZipSlipVulnerability (File file , String directory ) {
803+ java .nio .file .Path destDirPath = new File (directory ).toPath ().toAbsolutePath ().normalize ();
804+ java .nio .file .Path newFilePath = file .toPath ().toAbsolutePath ().normalize ();
805+ return !newFilePath .startsWith (destDirPath );
806+ }
790807}
0 commit comments