@@ -86,7 +86,12 @@ public void run() {
8686 FileHeader fileHeader = (FileHeader ) fileHeaderList .get (i );
8787
8888 File fout = new File (destDirectory , fileHeader .getFileName ());
89- ensureZipPathSafety (fout , destDirectory );
89+ String canonicalPath = fout .getCanonicalPath ();
90+ String destDirCanonicalPath = (new File (destDirectory ).getCanonicalPath ()) + File .separator ;
91+
92+ if (!canonicalPath .startsWith (destDirCanonicalPath )) {
93+ throw new SecurityException (String .format ("Found Zip Path Traversal Vulnerability with %s" , canonicalPath ));
94+ }
9095
9196 zipFile .extractFile (fileHeader , destDirectory );
9297 if (!fileHeader .isDirectory ()) {
@@ -172,8 +177,13 @@ public void onCopyProgress(long bytesRead) {
172177 };
173178
174179 File fout = new File (destDirectory , entry .getName ());
175- ensureZipPathSafety (fout , destDirectory );
180+ String canonicalPath = fout .getCanonicalPath ();
181+ String destDirCanonicalPath = (new File (destDirectory ).getCanonicalPath ()) + File .separator ;
176182
183+ if (!canonicalPath .startsWith (destDirCanonicalPath )) {
184+ throw new SecurityException (String .format ("Found Zip Path Traversal Vulnerability with %s" , canonicalPath ));
185+ }
186+
177187 if (!fout .exists ()) {
178188 //noinspection ResultOfMethodCallIgnored
179189 (new File (fout .getParent ())).mkdirs ();
@@ -260,8 +270,12 @@ public void run() {
260270 while ((entry = zipIn .getNextEntry ()) != null ) {
261271 if (entry .isDirectory ()) continue ;
262272 fout = new File (destDirectory , entry .getName ());
273+ String canonicalPath = fout .getCanonicalPath ();
274+ String destDirCanonicalPath = (new File (destDirectory ).getCanonicalPath ()) + File .separator ;
263275
264- ensureZipPathSafety (fout , destDirectory );
276+ if (!canonicalPath .startsWith (destDirCanonicalPath )) {
277+ throw new SecurityException (String .format ("Found Zip Path Traversal Vulnerability with %s" , canonicalPath ));
278+ }
265279
266280 if (!fout .exists ()) {
267281 //noinspection ResultOfMethodCallIgnored
@@ -472,12 +486,4 @@ private String getStackTrace(Exception e) {
472486 return sw .toString ();
473487 }
474488
475- private void ensureZipPathSafety (final File fout , final String destDirectory ) throws Exception {
476- String destDirCanonicalPath = (new File (destDirectory )).getCanonicalPath ();
477- String canonicalPath = fout .getCanonicalPath ();
478- if (!canonicalPath .startsWith (destDirCanonicalPath )) {
479- throw new Exception (String .format ("Found Zip Path Traversal Vulnerability with %s" , canonicalPath ));
480- }
481- }
482-
483489}
0 commit comments