blob: da66a1466a5f91d14849d2e7b4cd8c33fdf68bfd [file] [log] [blame]
Ray Milkey351d4562018-07-25 12:31:48 -07001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onlab.util;
18
19import java.io.File;
20import java.io.IOException;
21import java.util.zip.ZipEntry;
22
23/**
24 * Utilities for validation of Zip files.
25 */
Ray Milkey74c98a32018-07-26 10:05:49 -070026public final class FilePathValidator {
Ray Milkey351d4562018-07-25 12:31:48 -070027
28 /**
29 * Do not allow construction.
30 */
Ray Milkey74c98a32018-07-26 10:05:49 -070031 private FilePathValidator() {
32 }
Ray Milkey351d4562018-07-25 12:31:48 -070033
Ray Milkey74c98a32018-07-26 10:05:49 -070034 /**
35 * Validates a File. Checks that the file being created does not
36 * lie outside the target directory.
37 *
38 * @param destinationFile file to check
39 * @param destinationDir target directory
40 * @return true if the Entry resolves to a file inside the target directory; false otherwise
41 */
42 public static boolean validateFile(File destinationFile, File destinationDir) {
43 try {
44 String canonicalDestinationDirPath = destinationDir.getCanonicalPath();
45 String canonicalDestinationFile = destinationFile.getCanonicalPath();
46 return canonicalDestinationFile.startsWith(canonicalDestinationDirPath + File.separator);
47 } catch (IOException ioe) {
48 return false;
49 }
Ray Milkey351d4562018-07-25 12:31:48 -070050 }
51
52 /**
53 * Validates a zip entry. Checks that the file being created does not
54 * lie outside the target directory.
55 *
56 * See https://snyk.io/research/zip-slip-vulnerability for more information.
57 *
58 * @param entry ZipEntry to check
59 * @param destinationDir target directory
60 * @return true if the Entry resolves to a file inside the target directory; false otherwise
61 */
62 public static boolean validateZipEntry(ZipEntry entry, File destinationDir) {
63 try {
64 String canonicalDestinationDirPath = destinationDir.getCanonicalPath();
65 File destinationFile = new File(destinationDir, entry.getName());
66 String canonicalDestinationFile = destinationFile.getCanonicalPath();
67 return canonicalDestinationFile.startsWith(canonicalDestinationDirPath + File.separator);
68 } catch (IOException ioe) {
69 return false;
70 }
71 }
72
73}