1 /*
2  * Copyright (C) 2021 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.server.companion.virtual;
18 
19 import android.content.Context;
20 import android.content.pm.PackageManager;
21 import android.os.Binder;
22 import android.os.UserHandle;
23 import android.util.Slog;
24 
25 /**
26  * Utility methods for checking permissions required for VirtualDeviceManager operations.
27  */
28 class PermissionUtils {
29 
30     private static final String LOG_TAG = "VDM.PermissionUtils";
31 
32     /**
33      * Verifies whether the calling package name matches the calling app uid.
34      *
35      * @param context the context
36      * @param callingPackage the calling application package name
37      * @return {@code true} if the package name matches {@link Binder#getCallingUid()}, or
38      *   {@code false} otherwise
39      */
validateCallingPackageName(Context context, String callingPackage)40     public static boolean validateCallingPackageName(Context context, String callingPackage) {
41         final int callingUid = Binder.getCallingUid();
42         final long token = Binder.clearCallingIdentity();
43         try {
44             int packageUid = context.getPackageManager()
45                     .getPackageUidAsUser(callingPackage, UserHandle.getUserId(callingUid));
46             if (packageUid != callingUid) {
47                 Slog.e(LOG_TAG, "validatePackageName: App with package name " + callingPackage
48                         + " is UID " + packageUid + " but caller is " + callingUid);
49                 return false;
50             }
51         } catch (PackageManager.NameNotFoundException e) {
52             Slog.e(LOG_TAG, "validatePackageName: App with package name " + callingPackage
53                     + " does not exist");
54             return false;
55         } finally {
56             Binder.restoreCallingIdentity(token);
57         }
58         return true;
59     }
60 }
61