|
16 | 16 |
|
17 | 17 | import java.io.*; |
18 | 18 | import java.nio.file.Files; |
| 19 | +import java.nio.file.Path; |
| 20 | +import java.nio.file.Paths; |
19 | 21 | import java.util.ArrayList; |
20 | 22 | import java.util.List; |
21 | 23 | import java.util.Stack; |
@@ -634,33 +636,41 @@ private static void decompress7z(File archive, String directory) throws IOExcept |
634 | 636 | } |
635 | 637 | } |
636 | 638 |
|
637 | | - |
| 639 | + private static boolean isPathTraversal(String dir, String fName) { |
| 640 | + try { |
| 641 | + Path path = Paths.get(dir).resolve(fName); |
| 642 | + return !path.toAbsolutePath().equals(path.toRealPath()); |
| 643 | + }catch (Exception e){ |
| 644 | + return true; |
| 645 | + } |
| 646 | + } |
638 | 647 |
|
639 | 648 | private static void decompressTar(File archive, String directory) throws IOException { |
640 | 649 | byte[] buffer = new byte[BUFFER_SIZE]; |
641 | 650 | try (TarArchiveInputStream tis = new TarArchiveInputStream(Files.newInputStream(archive.toPath()))) { |
642 | 651 | TarArchiveEntry entry; |
643 | 652 | while ((entry = tis.getNextEntry()) != null) { |
644 | | - |
645 | | - File newFile = new File(directory, entry.getName()); |
646 | | - if(!newFile.getAbsolutePath().equals(newFile.getCanonicalPath())) |
| 653 | + if(isPathTraversal(directory, entry.getName())) |
647 | 654 | { |
648 | | - log.error(DIRECTORY_ATTACK + "{}", newFile.getAbsolutePath()); |
| 655 | + log.error(DIRECTORY_ATTACK + "{}", entry.getName()); |
649 | 656 | return; |
650 | | - } |
651 | | - if (entry.isDirectory()) { |
652 | | - if (!newFile.isDirectory() && !newFile.mkdirs()) { |
653 | | - throw new IOException("Failed to create directory " + newFile); |
654 | | - } |
655 | | - } else { |
656 | | - File parent = newFile.getParentFile(); |
657 | | - if (!parent.isDirectory() && !parent.mkdirs()) { |
658 | | - throw new IOException("Failed to create directory " + parent); |
659 | | - } |
660 | | - try (OutputStream out = Files.newOutputStream(newFile.toPath())) { |
661 | | - int len; |
662 | | - while ((len = tis.read(buffer)) != -1) { |
663 | | - out.write(buffer, 0, len); |
| 657 | + }else { |
| 658 | + File newFile = new File(directory, entry.getName()); |
| 659 | + |
| 660 | + if (entry.isDirectory()) { |
| 661 | + if (!newFile.isDirectory() && !newFile.mkdirs()) { |
| 662 | + throw new IOException("Failed to create directory " + newFile); |
| 663 | + } |
| 664 | + } else { |
| 665 | + File parent = newFile.getParentFile(); |
| 666 | + if (!parent.isDirectory() && !parent.mkdirs()) { |
| 667 | + throw new IOException("Failed to create directory " + parent); |
| 668 | + } |
| 669 | + try (OutputStream out = Files.newOutputStream(newFile.toPath())) { |
| 670 | + int len; |
| 671 | + while ((len = tis.read(buffer)) != -1) { |
| 672 | + out.write(buffer, 0, len); |
| 673 | + } |
664 | 674 | } |
665 | 675 | } |
666 | 676 | } |
|
0 commit comments