Skip to content

Commit ba9b6bc

Browse files
sgramponeBeta Bot
authored andcommitted
Cherry pick branch 'genexuslabs:fix/gxcompress-abitrary-file-access' into beta
1 parent 31fec23 commit ba9b6bc

File tree

1 file changed

+29
-19
lines changed

1 file changed

+29
-19
lines changed

gxcompress/src/main/java/com/genexus/compression/GXCompressor.java

Lines changed: 29 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616

1717
import java.io.*;
1818
import java.nio.file.Files;
19+
import java.nio.file.Path;
20+
import java.nio.file.Paths;
1921
import java.util.ArrayList;
2022
import java.util.List;
2123
import java.util.Stack;
@@ -634,33 +636,41 @@ private static void decompress7z(File archive, String directory) throws IOExcept
634636
}
635637
}
636638

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+
}
638647

639648
private static void decompressTar(File archive, String directory) throws IOException {
640649
byte[] buffer = new byte[BUFFER_SIZE];
641650
try (TarArchiveInputStream tis = new TarArchiveInputStream(Files.newInputStream(archive.toPath()))) {
642651
TarArchiveEntry entry;
643652
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()))
647654
{
648-
log.error(DIRECTORY_ATTACK + "{}", newFile.getAbsolutePath());
655+
log.error(DIRECTORY_ATTACK + "{}", entry.getName());
649656
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+
}
664674
}
665675
}
666676
}

0 commit comments

Comments
 (0)