1 /*
2  * Copyright (C) 2020 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 package com.android.car;
17 
18 import android.annotation.NonNull;
19 import android.app.ActivityManager;
20 import android.os.Binder;
21 
22 import java.util.Arrays;
23 
24 /**
25  * Helper for permissions checks.
26  */
27 public final class PermissionHelper {
28 
29     /**
30      * Checks if caller has the {@code android.Manifest.permission.DUMP} permission.
31      *
32      * @throws SecurityException if it doesn't.
33      */
checkHasDumpPermissionGranted(@onNull String message)34     public static void checkHasDumpPermissionGranted(@NonNull String message) {
35         checkHasAtLeastOnePermissionGranted(message, android.Manifest.permission.DUMP);
36     }
37 
38     /**
39      * Checks if caller has at least one of the give permissions.
40      *
41      * @throws SecurityException if it doesn't.
42      */
checkHasAtLeastOnePermissionGranted(@onNull String message, @NonNull String...permissions)43     public static void checkHasAtLeastOnePermissionGranted(@NonNull String message,
44             @NonNull String...permissions) {
45         int callingUid = Binder.getCallingUid();
46         if (!hasAtLeastOnePermissionGranted(callingUid, permissions)) {
47             if (permissions.length == 1) {
48                 throw new SecurityException("You need " + permissions[0] + " to: " + message);
49             }
50             throw new SecurityException("You need one of " + Arrays.toString(permissions)
51                     + " to: " + message);
52         }
53     }
54 
55     /**
56      * Returns whether the given {@code uids} has at least one of the give permissions.
57      */
hasAtLeastOnePermissionGranted(int uid, @NonNull String... permissions)58     public static boolean hasAtLeastOnePermissionGranted(int uid, @NonNull String... permissions) {
59         for (String permission : permissions) {
60             if (ActivityManager.checkComponentPermission(permission, uid, /* owningUid = */-1,
61                     /* exported = */ true)
62                     == android.content.pm.PackageManager.PERMISSION_GRANTED) {
63                 return true;
64             }
65         }
66         return false;
67     }
68 
PermissionHelper()69     private PermissionHelper() {
70         throw new UnsupportedOperationException("provides only static methods");
71     }
72 }
73