6
6
import java .util .zip .ZipException ;
7
7
import java .util .zip .ZipFile ;
8
8
import java .util .zip .ZipInputStream ;
9
+ import java .nio .file .Path ;
10
+ import java .nio .file .Paths ;
9
11
10
12
public class ZipUtils {
11
13
@@ -29,7 +31,7 @@ public static void unZipIt(String zipFilePath, String outputFolder) {
29
31
ZipEntry ze = zis .getNextEntry ();
30
32
while (ze != null ) {
31
33
String fileName = ze .getName ();
32
- File newFile = new File ( outputFolder + File . separator + fileName );
34
+ File newFile = protectZipSlip ( fileName , outputFolder );
33
35
//大部分网络上的源码,这里没有判断子目录
34
36
if (ze .isDirectory ()) {
35
37
if (!newFile .mkdirs ()) {
@@ -60,7 +62,7 @@ public static void unzip(File source, String out) throws IOException {
60
62
61
63
while (entry != null ) {
62
64
63
- File file = new File ( out , entry .getName ());
65
+ File file = protectZipSlip ( entry .getName (), out );
64
66
65
67
if (entry .isDirectory ()) {
66
68
if (!file .mkdirs ()) {
@@ -130,4 +132,17 @@ public static void upZipFile(File zipFile, String folderPath) throws ZipExceptio
130
132
131
133
}
132
134
}
135
+ public static File protectZipSlip (String fileName , String destDir ) throws IOException {
136
+ Path destPath = Paths .get (destDir );
137
+ Path resolvedDest = destPath .resolve (fileName );
138
+ Path normalizedPath = resolvedDest .normalize ();
139
+
140
+ // checking whether zipEntry filename has changed the destination
141
+ if (!normalizedPath .startsWith (destDir )) {
142
+ throw new IOException ("Malicious zip entry found: " + fileName );
143
+ }
144
+
145
+ File newFile = normalizedPath .toFile ();
146
+ return newFile ;
147
+ }
133
148
}
0 commit comments