1 /*
2  * Copyright (C) 2022 The Android Open Source Project
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 
17 package com.android.internal.os;
18 
19 import android.annotation.NonNull;
20 import android.compat.annotation.ChangeId;
21 import android.compat.annotation.EnabledSince;
22 import android.os.Build;
23 
24 import dalvik.system.ZipPathValidator;
25 
26 import java.io.File;
27 import java.util.zip.ZipException;
28 
29 /**
30  * A child implementation of the {@link dalvik.system.ZipPathValidator.Callback} that removes the
31  * risk of zip path traversal vulnerabilities.
32  *
33  * @hide
34  */
35 public class SafeZipPathValidatorCallback implements ZipPathValidator.Callback {
36     /**
37      * This change targets zip path traversal vulnerabilities by throwing
38      * {@link java.util.zip.ZipException} if zip path entries contain ".." or start with "/".
39      * <p>
40      * The exception will be thrown in {@link java.util.zip.ZipInputStream#getNextEntry} or
41      * {@link java.util.zip.ZipFile#ZipFile(String)}.
42      * <p>
43      * This validation is enabled for apps with targetSDK >= U.
44      */
45     @ChangeId
46     @EnabledSince(targetSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
47     public static final long VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL = 242716250L;
48 
49     @Override
onZipEntryAccess(@onNull String path)50     public void onZipEntryAccess(@NonNull String path) throws ZipException {
51         if (path.startsWith("/")) {
52             throw new ZipException("Invalid zip entry path: " + path);
53         }
54         if (path.contains("..")) {
55             // If the string does contain "..", break it down into its actual name elements to
56             // ensure it actually contains ".." as a name, not just a name like "foo..bar" or even
57             // "foo..", which should be fine.
58             File file = new File(path);
59             while (file != null) {
60                 if (file.getName().equals("..")) {
61                     throw new ZipException("Invalid zip entry path: " + path);
62                 }
63                 file = file.getParentFile();
64             }
65         }
66     }
67 }
68