1 /*
2  * Copyright (C) 2015 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.pm.permission;
18 
19 import static android.os.Process.FIRST_APPLICATION_UID;
20 
21 import android.Manifest;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.app.ActivityManager;
25 import android.app.AppOpsManager;
26 import android.app.DownloadManager;
27 import android.app.SearchManager;
28 import android.app.admin.DevicePolicyManager;
29 import android.companion.CompanionDeviceManager;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.pm.ApplicationInfo;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.pm.PackageManager.NameNotFoundException;
36 import android.content.pm.PackageManagerInternal;
37 import android.content.pm.PackageManagerInternal.PackagesProvider;
38 import android.content.pm.PackageManagerInternal.SyncAdapterPackagesProvider;
39 import android.content.pm.PermissionInfo;
40 import android.content.pm.ProviderInfo;
41 import android.content.pm.ResolveInfo;
42 import android.media.RingtoneManager;
43 import android.net.Uri;
44 import android.os.Build;
45 import android.os.Environment;
46 import android.os.Handler;
47 import android.os.Looper;
48 import android.os.Message;
49 import android.os.UserHandle;
50 import android.os.storage.StorageManager;
51 import android.permission.PermissionManager;
52 import android.print.PrintManager;
53 import android.provider.CalendarContract;
54 import android.provider.ContactsContract;
55 import android.provider.MediaStore;
56 import android.provider.Telephony.Sms.Intents;
57 import android.security.Credentials;
58 import android.speech.RecognitionService;
59 import android.telephony.TelephonyManager;
60 import android.text.TextUtils;
61 import android.util.ArrayMap;
62 import android.util.ArraySet;
63 import android.util.Log;
64 import android.util.Slog;
65 import android.util.SparseIntArray;
66 import android.util.Xml;
67 
68 import com.android.internal.annotations.GuardedBy;
69 import com.android.internal.util.ArrayUtils;
70 import com.android.internal.util.XmlUtils;
71 import com.android.server.LocalServices;
72 
73 import org.xmlpull.v1.XmlPullParser;
74 import org.xmlpull.v1.XmlPullParserException;
75 
76 import java.io.BufferedInputStream;
77 import java.io.File;
78 import java.io.FileInputStream;
79 import java.io.IOException;
80 import java.io.InputStream;
81 import java.util.ArrayList;
82 import java.util.Arrays;
83 import java.util.Collections;
84 import java.util.List;
85 import java.util.Map;
86 import java.util.Set;
87 
88 /**
89  * This class is the policy for granting runtime permissions to
90  * platform components and default handlers in the system such
91  * that the device is usable out-of-the-box. For example, the
92  * shell UID is a part of the system and the Phone app should
93  * have phone related permission by default.
94  * <p>
95  * NOTE: This class is at the wrong abstraction level. It is a part of the package manager
96  * service but knows about lots of higher level subsystems. The correct way to do this is
97  * to have an interface defined in the package manager but have the impl next to other
98  * policy stuff like PhoneWindowManager
99  */
100 public final class DefaultPermissionGrantPolicy {
101     private static final String TAG = "DefaultPermGrantPolicy"; // must be <= 23 chars
102     private static final boolean DEBUG = false;
103 
104     @PackageManager.ResolveInfoFlags
105     private static final int DEFAULT_INTENT_QUERY_FLAGS =
106             PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
107                     | PackageManager.MATCH_UNINSTALLED_PACKAGES;
108 
109     @PackageManager.PackageInfoFlags
110     private static final int DEFAULT_PACKAGE_INFO_QUERY_FLAGS =
111             PackageManager.MATCH_UNINSTALLED_PACKAGES
112                     | PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS
113                     | PackageManager.MATCH_HIDDEN_UNTIL_INSTALLED_COMPONENTS
114                     | PackageManager.GET_PERMISSIONS;
115 
116     private static final String AUDIO_MIME_TYPE = "audio/mpeg";
117 
118     private static final String TAG_EXCEPTIONS = "exceptions";
119     private static final String TAG_EXCEPTION = "exception";
120     private static final String TAG_PERMISSION = "permission";
121     private static final String ATTR_PACKAGE = "package";
122     private static final String ATTR_NAME = "name";
123     private static final String ATTR_FIXED = "fixed";
124     private static final String ATTR_WHITELISTED = "whitelisted";
125 
126     private static final Set<String> PHONE_PERMISSIONS = new ArraySet<>();
127 
128 
129     static {
130         PHONE_PERMISSIONS.add(Manifest.permission.READ_PHONE_STATE);
131         PHONE_PERMISSIONS.add(Manifest.permission.CALL_PHONE);
132         PHONE_PERMISSIONS.add(Manifest.permission.READ_CALL_LOG);
133         PHONE_PERMISSIONS.add(Manifest.permission.WRITE_CALL_LOG);
134         PHONE_PERMISSIONS.add(Manifest.permission.ADD_VOICEMAIL);
135         PHONE_PERMISSIONS.add(Manifest.permission.USE_SIP);
136         PHONE_PERMISSIONS.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
137     }
138 
139     private static final Set<String> CONTACTS_PERMISSIONS = new ArraySet<>();
140     static {
141         CONTACTS_PERMISSIONS.add(Manifest.permission.READ_CONTACTS);
142         CONTACTS_PERMISSIONS.add(Manifest.permission.WRITE_CONTACTS);
143         CONTACTS_PERMISSIONS.add(Manifest.permission.GET_ACCOUNTS);
144     }
145 
146     private static final Set<String> ALWAYS_LOCATION_PERMISSIONS = new ArraySet<>();
147     static {
148         ALWAYS_LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_FINE_LOCATION);
149         ALWAYS_LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_COARSE_LOCATION);
150         ALWAYS_LOCATION_PERMISSIONS.add(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
151     }
152 
153     private static final Set<String> ACTIVITY_RECOGNITION_PERMISSIONS = new ArraySet<>();
154     static {
155         ACTIVITY_RECOGNITION_PERMISSIONS.add(Manifest.permission.ACTIVITY_RECOGNITION);
156     }
157 
158     private static final Set<String> CALENDAR_PERMISSIONS = new ArraySet<>();
159     static {
160         CALENDAR_PERMISSIONS.add(Manifest.permission.READ_CALENDAR);
161         CALENDAR_PERMISSIONS.add(Manifest.permission.WRITE_CALENDAR);
162     }
163 
164     private static final Set<String> SMS_PERMISSIONS = new ArraySet<>();
165     static {
166         SMS_PERMISSIONS.add(Manifest.permission.SEND_SMS);
167         SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_SMS);
168         SMS_PERMISSIONS.add(Manifest.permission.READ_SMS);
169         SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_WAP_PUSH);
170         SMS_PERMISSIONS.add(Manifest.permission.RECEIVE_MMS);
171         SMS_PERMISSIONS.add(Manifest.permission.READ_CELL_BROADCASTS);
172     }
173 
174     private static final Set<String> MICROPHONE_PERMISSIONS = new ArraySet<>();
175     static {
176         MICROPHONE_PERMISSIONS.add(Manifest.permission.RECORD_AUDIO);
177     }
178 
179     private static final Set<String> CAMERA_PERMISSIONS = new ArraySet<>();
180     static {
181         CAMERA_PERMISSIONS.add(Manifest.permission.CAMERA);
182     }
183 
184     private static final Set<String> SENSORS_PERMISSIONS = new ArraySet<>();
185     static {
186         SENSORS_PERMISSIONS.add(Manifest.permission.BODY_SENSORS);
187     }
188 
189     private static final Set<String> STORAGE_PERMISSIONS = new ArraySet<>();
190     static {
191         STORAGE_PERMISSIONS.add(Manifest.permission.READ_EXTERNAL_STORAGE);
192         STORAGE_PERMISSIONS.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
193         STORAGE_PERMISSIONS.add(Manifest.permission.ACCESS_MEDIA_LOCATION);
194     }
195 
196     private static final int MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS = 1;
197 
198     private static final String ACTION_TRACK = "com.android.fitness.TRACK";
199 
200     private final Handler mHandler;
201 
202     private PackagesProvider mLocationPackagesProvider;
203     private PackagesProvider mLocationExtraPackagesProvider;
204     private PackagesProvider mVoiceInteractionPackagesProvider;
205     private PackagesProvider mSmsAppPackagesProvider;
206     private PackagesProvider mDialerAppPackagesProvider;
207     private PackagesProvider mSimCallManagerPackagesProvider;
208     private PackagesProvider mUseOpenWifiAppPackagesProvider;
209     private SyncAdapterPackagesProvider mSyncAdapterPackagesProvider;
210 
211     private ArrayMap<String, List<DefaultPermissionGrant>> mGrantExceptions;
212     private final Context mContext;
213     private final Object mLock = new Object();
214     private final PackageManagerInternal mServiceInternal;
215     private final PermissionManagerService mPermissionManager;
216 
217     @GuardedBy("mLock")
218     private SparseIntArray mDefaultPermissionsGrantedUsers = new SparseIntArray();
219 
DefaultPermissionGrantPolicy(Context context, Looper looper, @NonNull PermissionManagerService permissionManager)220     DefaultPermissionGrantPolicy(Context context, Looper looper,
221             @NonNull PermissionManagerService permissionManager) {
222         mContext = context;
223         mHandler = new Handler(looper) {
224             @Override
225             public void handleMessage(Message msg) {
226                 if (msg.what == MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS) {
227                     synchronized (mLock) {
228                         if (mGrantExceptions == null) {
229                             mGrantExceptions = readDefaultPermissionExceptionsLocked();
230                         }
231                     }
232                 }
233             }
234         };
235         mPermissionManager = permissionManager;
236         mServiceInternal = LocalServices.getService(PackageManagerInternal.class);
237     }
238 
setLocationPackagesProvider(PackagesProvider provider)239     public void setLocationPackagesProvider(PackagesProvider provider) {
240         synchronized (mLock) {
241             mLocationPackagesProvider = provider;
242         }
243     }
244 
245     /** Sets the provider for loction extra packages. */
setLocationExtraPackagesProvider(PackagesProvider provider)246     public void setLocationExtraPackagesProvider(PackagesProvider provider) {
247         synchronized (mLock) {
248             mLocationExtraPackagesProvider = provider;
249         }
250     }
251 
setVoiceInteractionPackagesProvider(PackagesProvider provider)252     public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
253         synchronized (mLock) {
254             mVoiceInteractionPackagesProvider = provider;
255         }
256     }
257 
setSmsAppPackagesProvider(PackagesProvider provider)258     public void setSmsAppPackagesProvider(PackagesProvider provider) {
259         synchronized (mLock) {
260             mSmsAppPackagesProvider = provider;
261         }
262     }
263 
setDialerAppPackagesProvider(PackagesProvider provider)264     public void setDialerAppPackagesProvider(PackagesProvider provider) {
265         synchronized (mLock) {
266             mDialerAppPackagesProvider = provider;
267         }
268     }
269 
setSimCallManagerPackagesProvider(PackagesProvider provider)270     public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
271         synchronized (mLock) {
272             mSimCallManagerPackagesProvider = provider;
273         }
274     }
275 
setUseOpenWifiAppPackagesProvider(PackagesProvider provider)276     public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
277         synchronized (mLock) {
278             mUseOpenWifiAppPackagesProvider = provider;
279         }
280     }
281 
setSyncAdapterPackagesProvider(SyncAdapterPackagesProvider provider)282     public void setSyncAdapterPackagesProvider(SyncAdapterPackagesProvider provider) {
283         synchronized (mLock) {
284             mSyncAdapterPackagesProvider = provider;
285         }
286     }
287 
wereDefaultPermissionsGrantedSinceBoot(int userId)288     public boolean wereDefaultPermissionsGrantedSinceBoot(int userId) {
289         synchronized (mLock) {
290             return mDefaultPermissionsGrantedUsers.indexOfKey(userId) >= 0;
291         }
292     }
293 
grantDefaultPermissions(int userId)294     public void grantDefaultPermissions(int userId) {
295         grantPermissionsToSysComponentsAndPrivApps(userId);
296         grantDefaultSystemHandlerPermissions(userId);
297         grantDefaultPermissionExceptions(userId);
298         synchronized (mLock) {
299             mDefaultPermissionsGrantedUsers.put(userId, userId);
300         }
301     }
302 
grantRuntimePermissionsForSystemPackage(int userId, PackageInfo pkg)303     private void grantRuntimePermissionsForSystemPackage(int userId, PackageInfo pkg) {
304         Set<String> permissions = new ArraySet<>();
305         for (String permission : pkg.requestedPermissions) {
306             final BasePermission bp = mPermissionManager.getPermission(permission);
307             if (bp == null) {
308                 continue;
309             }
310             if (bp.isRuntime()) {
311                 permissions.add(permission);
312             }
313         }
314         if (!permissions.isEmpty()) {
315             grantRuntimePermissions(pkg, permissions, true /*systemFixed*/, userId);
316         }
317     }
318 
scheduleReadDefaultPermissionExceptions()319     public void scheduleReadDefaultPermissionExceptions() {
320         mHandler.sendEmptyMessage(MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS);
321     }
322 
grantPermissionsToSysComponentsAndPrivApps(int userId)323     private void grantPermissionsToSysComponentsAndPrivApps(int userId) {
324         Log.i(TAG, "Granting permissions to platform components for user " + userId);
325         List<PackageInfo> packages = mContext.getPackageManager().getInstalledPackagesAsUser(
326                 DEFAULT_PACKAGE_INFO_QUERY_FLAGS, UserHandle.USER_SYSTEM);
327         for (PackageInfo pkg : packages) {
328             if (pkg == null) {
329                 continue;
330             }
331             if (!isSysComponentOrPersistentPlatformSignedPrivApp(pkg)
332                     || !doesPackageSupportRuntimePermissions(pkg)
333                     || ArrayUtils.isEmpty(pkg.requestedPermissions)) {
334                 continue;
335             }
336             grantRuntimePermissionsForSystemPackage(userId, pkg);
337         }
338     }
339 
340     @SafeVarargs
grantIgnoringSystemPackage(String packageName, int userId, Set<String>... permissionGroups)341     private final void grantIgnoringSystemPackage(String packageName, int userId,
342             Set<String>... permissionGroups) {
343         grantPermissionsToPackage(packageName, userId, true /* ignoreSystemPackage */,
344                 true /*whitelistRestrictedPermissions*/, permissionGroups);
345     }
346 
347     @SafeVarargs
grantSystemFixedPermissionsToSystemPackage(String packageName, int userId, Set<String>... permissionGroups)348     private final void grantSystemFixedPermissionsToSystemPackage(String packageName, int userId,
349             Set<String>... permissionGroups) {
350         grantPermissionsToSystemPackage(
351                 packageName, userId, true /* systemFixed */, permissionGroups);
352     }
353 
354     @SafeVarargs
grantPermissionsToSystemPackage( String packageName, int userId, Set<String>... permissionGroups)355     private final void grantPermissionsToSystemPackage(
356             String packageName, int userId, Set<String>... permissionGroups) {
357         grantPermissionsToSystemPackage(
358                 packageName, userId, false /* systemFixed */, permissionGroups);
359     }
360 
361     @SafeVarargs
grantPermissionsToSystemPackage(String packageName, int userId, boolean systemFixed, Set<String>... permissionGroups)362     private final void grantPermissionsToSystemPackage(String packageName, int userId,
363             boolean systemFixed, Set<String>... permissionGroups) {
364         if (!isSystemPackage(packageName)) {
365             return;
366         }
367         grantPermissionsToPackage(getSystemPackageInfo(packageName),
368                 userId, systemFixed, false /* ignoreSystemPackage */,
369                 true /*whitelistRestrictedPermissions*/, permissionGroups);
370     }
371 
372     @SafeVarargs
grantPermissionsToPackage(String packageName, int userId, boolean ignoreSystemPackage, boolean whitelistRestrictedPermissions, Set<String>... permissionGroups)373     private final void grantPermissionsToPackage(String packageName, int userId,
374             boolean ignoreSystemPackage, boolean whitelistRestrictedPermissions,
375             Set<String>... permissionGroups) {
376         grantPermissionsToPackage(getPackageInfo(packageName),
377                 userId, false /* systemFixed */, ignoreSystemPackage,
378                 whitelistRestrictedPermissions, permissionGroups);
379     }
380 
381     @SafeVarargs
grantPermissionsToPackage(PackageInfo packageInfo, int userId, boolean systemFixed, boolean ignoreSystemPackage, boolean whitelistRestrictedPermissions, Set<String>... permissionGroups)382     private final void grantPermissionsToPackage(PackageInfo packageInfo, int userId,
383             boolean systemFixed, boolean ignoreSystemPackage,
384             boolean whitelistRestrictedPermissions, Set<String>... permissionGroups) {
385         if (packageInfo == null) {
386             return;
387         }
388         if (doesPackageSupportRuntimePermissions(packageInfo)) {
389             for (Set<String> permissionGroup : permissionGroups) {
390                 grantRuntimePermissions(packageInfo, permissionGroup, systemFixed,
391                         ignoreSystemPackage, whitelistRestrictedPermissions, userId);
392             }
393         }
394     }
395 
grantDefaultSystemHandlerPermissions(int userId)396     private void grantDefaultSystemHandlerPermissions(int userId) {
397         Log.i(TAG, "Granting permissions to default platform handlers for user " + userId);
398 
399         final PackagesProvider locationPackagesProvider;
400         final PackagesProvider locationExtraPackagesProvider;
401         final PackagesProvider voiceInteractionPackagesProvider;
402         final PackagesProvider smsAppPackagesProvider;
403         final PackagesProvider dialerAppPackagesProvider;
404         final PackagesProvider simCallManagerPackagesProvider;
405         final PackagesProvider useOpenWifiAppPackagesProvider;
406         final SyncAdapterPackagesProvider syncAdapterPackagesProvider;
407 
408         synchronized (mLock) {
409             locationPackagesProvider = mLocationPackagesProvider;
410             locationExtraPackagesProvider = mLocationExtraPackagesProvider;
411             voiceInteractionPackagesProvider = mVoiceInteractionPackagesProvider;
412             smsAppPackagesProvider = mSmsAppPackagesProvider;
413             dialerAppPackagesProvider = mDialerAppPackagesProvider;
414             simCallManagerPackagesProvider = mSimCallManagerPackagesProvider;
415             useOpenWifiAppPackagesProvider = mUseOpenWifiAppPackagesProvider;
416             syncAdapterPackagesProvider = mSyncAdapterPackagesProvider;
417         }
418 
419         String[] voiceInteractPackageNames = (voiceInteractionPackagesProvider != null)
420                 ? voiceInteractionPackagesProvider.getPackages(userId) : null;
421         String[] locationPackageNames = (locationPackagesProvider != null)
422                 ? locationPackagesProvider.getPackages(userId) : null;
423         String[] locationExtraPackageNames = (locationExtraPackagesProvider != null)
424                 ? locationExtraPackagesProvider.getPackages(userId) : null;
425         String[] smsAppPackageNames = (smsAppPackagesProvider != null)
426                 ? smsAppPackagesProvider.getPackages(userId) : null;
427         String[] dialerAppPackageNames = (dialerAppPackagesProvider != null)
428                 ? dialerAppPackagesProvider.getPackages(userId) : null;
429         String[] simCallManagerPackageNames = (simCallManagerPackagesProvider != null)
430                 ? simCallManagerPackagesProvider.getPackages(userId) : null;
431         String[] useOpenWifiAppPackageNames = (useOpenWifiAppPackagesProvider != null)
432                 ? useOpenWifiAppPackagesProvider.getPackages(userId) : null;
433         String[] contactsSyncAdapterPackages = (syncAdapterPackagesProvider != null) ?
434                 syncAdapterPackagesProvider.getPackages(ContactsContract.AUTHORITY, userId) : null;
435         String[] calendarSyncAdapterPackages = (syncAdapterPackagesProvider != null) ?
436                 syncAdapterPackagesProvider.getPackages(CalendarContract.AUTHORITY, userId) : null;
437 
438         // Installer
439         grantSystemFixedPermissionsToSystemPackage(
440                 ArrayUtils.firstOrNull(getKnownPackages(
441                         PackageManagerInternal.PACKAGE_INSTALLER, userId)),
442                 userId, STORAGE_PERMISSIONS);
443 
444         // Verifier
445         final String verifier = ArrayUtils.firstOrNull(getKnownPackages(
446                 PackageManagerInternal.PACKAGE_VERIFIER, userId));
447         grantSystemFixedPermissionsToSystemPackage(verifier, userId, STORAGE_PERMISSIONS);
448         grantPermissionsToSystemPackage(verifier, userId, PHONE_PERMISSIONS, SMS_PERMISSIONS);
449 
450         // SetupWizard
451         grantPermissionsToSystemPackage(
452                 ArrayUtils.firstOrNull(getKnownPackages(
453                         PackageManagerInternal.PACKAGE_SETUP_WIZARD, userId)), userId,
454                 PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS,
455                 CAMERA_PERMISSIONS);
456 
457         // Camera
458         grantPermissionsToSystemPackage(
459                 getDefaultSystemHandlerActivityPackage(MediaStore.ACTION_IMAGE_CAPTURE, userId),
460                 userId, CAMERA_PERMISSIONS, MICROPHONE_PERMISSIONS, STORAGE_PERMISSIONS);
461 
462         // Sound recorder
463         grantPermissionsToSystemPackage(
464                 getDefaultSystemHandlerActivityPackage(
465                         MediaStore.Audio.Media.RECORD_SOUND_ACTION, userId),
466                 userId, MICROPHONE_PERMISSIONS);
467 
468         // Media provider
469         grantSystemFixedPermissionsToSystemPackage(
470                 getDefaultProviderAuthorityPackage(MediaStore.AUTHORITY, userId), userId,
471                 STORAGE_PERMISSIONS, PHONE_PERMISSIONS);
472 
473         // Downloads provider
474         grantSystemFixedPermissionsToSystemPackage(
475                 getDefaultProviderAuthorityPackage("downloads", userId), userId,
476                 STORAGE_PERMISSIONS);
477 
478         // Downloads UI
479         grantSystemFixedPermissionsToSystemPackage(
480                 getDefaultSystemHandlerActivityPackage(
481                         DownloadManager.ACTION_VIEW_DOWNLOADS, userId),
482                 userId, STORAGE_PERMISSIONS);
483 
484         // Storage provider
485         grantSystemFixedPermissionsToSystemPackage(
486                 getDefaultProviderAuthorityPackage("com.android.externalstorage.documents", userId),
487                 userId, STORAGE_PERMISSIONS);
488 
489         // CertInstaller
490         grantSystemFixedPermissionsToSystemPackage(
491                 getDefaultSystemHandlerActivityPackage(Credentials.INSTALL_ACTION, userId), userId,
492                 STORAGE_PERMISSIONS);
493 
494         // Dialer
495         if (dialerAppPackageNames == null) {
496             String dialerPackage =
497                     getDefaultSystemHandlerActivityPackage(Intent.ACTION_DIAL, userId);
498             grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
499         } else {
500             for (String dialerAppPackageName : dialerAppPackageNames) {
501                 grantDefaultPermissionsToDefaultSystemDialerApp(dialerAppPackageName, userId);
502             }
503         }
504 
505         // Sim call manager
506         if (simCallManagerPackageNames != null) {
507             for (String simCallManagerPackageName : simCallManagerPackageNames) {
508                 grantDefaultPermissionsToDefaultSystemSimCallManager(
509                         simCallManagerPackageName, userId);
510             }
511         }
512 
513         // Use Open Wifi
514         if (useOpenWifiAppPackageNames != null) {
515             for (String useOpenWifiPackageName : useOpenWifiAppPackageNames) {
516                 grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(
517                         useOpenWifiPackageName, userId);
518             }
519         }
520 
521         // SMS
522         if (smsAppPackageNames == null) {
523             String smsPackage = getDefaultSystemHandlerActivityPackageForCategory(
524                     Intent.CATEGORY_APP_MESSAGING, userId);
525             grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
526         } else {
527             for (String smsPackage : smsAppPackageNames) {
528                 grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
529             }
530         }
531 
532         // Cell Broadcast Receiver
533         grantSystemFixedPermissionsToSystemPackage(
534                 getDefaultSystemHandlerActivityPackage(Intents.SMS_CB_RECEIVED_ACTION, userId),
535                 userId, SMS_PERMISSIONS);
536 
537         // Carrier Provisioning Service
538         grantPermissionsToSystemPackage(
539                 getDefaultSystemHandlerServicePackage(Intents.SMS_CARRIER_PROVISION_ACTION, userId),
540                 userId, SMS_PERMISSIONS);
541 
542         // Calendar
543         grantPermissionsToSystemPackage(
544                 getDefaultSystemHandlerActivityPackageForCategory(
545                         Intent.CATEGORY_APP_CALENDAR, userId),
546                 userId, CALENDAR_PERMISSIONS, CONTACTS_PERMISSIONS);
547 
548         // Calendar provider
549         String calendarProvider =
550                 getDefaultProviderAuthorityPackage(CalendarContract.AUTHORITY, userId);
551         grantPermissionsToSystemPackage(calendarProvider, userId,
552                 CONTACTS_PERMISSIONS, STORAGE_PERMISSIONS);
553         grantSystemFixedPermissionsToSystemPackage(calendarProvider, userId, CALENDAR_PERMISSIONS);
554 
555         // Calendar provider sync adapters
556         grantPermissionToEachSystemPackage(
557                 getHeadlessSyncAdapterPackages(calendarSyncAdapterPackages, userId),
558                 userId, CALENDAR_PERMISSIONS);
559 
560         // Contacts
561         grantPermissionsToSystemPackage(
562                 getDefaultSystemHandlerActivityPackageForCategory(
563                         Intent.CATEGORY_APP_CONTACTS, userId),
564                 userId, CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
565 
566         // Contacts provider sync adapters
567         grantPermissionToEachSystemPackage(
568                 getHeadlessSyncAdapterPackages(contactsSyncAdapterPackages, userId),
569                 userId, CONTACTS_PERMISSIONS);
570 
571         // Contacts provider
572         String contactsProviderPackage =
573                 getDefaultProviderAuthorityPackage(ContactsContract.AUTHORITY, userId);
574         grantSystemFixedPermissionsToSystemPackage(contactsProviderPackage, userId,
575                 CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
576         grantPermissionsToSystemPackage(contactsProviderPackage, userId, STORAGE_PERMISSIONS);
577 
578         // Device provisioning
579         grantPermissionsToSystemPackage(
580                 getDefaultSystemHandlerActivityPackage(
581                         DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, userId),
582                 userId, CONTACTS_PERMISSIONS);
583 
584         // Maps
585         grantPermissionsToSystemPackage(
586                 getDefaultSystemHandlerActivityPackageForCategory(Intent.CATEGORY_APP_MAPS, userId),
587                 userId, ALWAYS_LOCATION_PERMISSIONS);
588 
589         // Gallery
590         grantPermissionsToSystemPackage(
591                 getDefaultSystemHandlerActivityPackageForCategory(
592                         Intent.CATEGORY_APP_GALLERY, userId),
593                 userId, STORAGE_PERMISSIONS);
594 
595         // Email
596         grantPermissionsToSystemPackage(
597                 getDefaultSystemHandlerActivityPackageForCategory(
598                         Intent.CATEGORY_APP_EMAIL, userId),
599                 userId, CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS);
600 
601         // Browser
602         String browserPackage = ArrayUtils.firstOrNull(getKnownPackages(
603                 PackageManagerInternal.PACKAGE_BROWSER, userId));
604         if (browserPackage == null) {
605             browserPackage = getDefaultSystemHandlerActivityPackageForCategory(
606                     Intent.CATEGORY_APP_BROWSER, userId);
607             if (!isSystemPackage(browserPackage)) {
608                 browserPackage = null;
609             }
610         }
611         grantPermissionsToPackage(browserPackage, userId, false /* ignoreSystemPackage */,
612                 true /*whitelistRestrictedPermissions*/, ALWAYS_LOCATION_PERMISSIONS);
613 
614         // Voice interaction
615         if (voiceInteractPackageNames != null) {
616             for (String voiceInteractPackageName : voiceInteractPackageNames) {
617                 grantPermissionsToSystemPackage(voiceInteractPackageName, userId,
618                         CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS, MICROPHONE_PERMISSIONS,
619                         PHONE_PERMISSIONS, SMS_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS);
620             }
621         }
622 
623         if (ActivityManager.isLowRamDeviceStatic()) {
624             // Allow voice search on low-ram devices
625             grantPermissionsToSystemPackage(
626                     getDefaultSystemHandlerActivityPackage(
627                             SearchManager.INTENT_ACTION_GLOBAL_SEARCH, userId),
628                     userId, MICROPHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS);
629         }
630 
631         // Voice recognition
632         Intent voiceRecoIntent = new Intent(RecognitionService.SERVICE_INTERFACE)
633                 .addCategory(Intent.CATEGORY_DEFAULT);
634         grantPermissionsToSystemPackage(
635                 getDefaultSystemHandlerServicePackage(voiceRecoIntent, userId), userId,
636                 MICROPHONE_PERMISSIONS);
637 
638         // Location
639         if (locationPackageNames != null) {
640             for (String packageName : locationPackageNames) {
641                 grantPermissionsToSystemPackage(packageName, userId,
642                         CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS, MICROPHONE_PERMISSIONS,
643                         PHONE_PERMISSIONS, SMS_PERMISSIONS, CAMERA_PERMISSIONS,
644                         SENSORS_PERMISSIONS, STORAGE_PERMISSIONS);
645                 grantSystemFixedPermissionsToSystemPackage(packageName, userId,
646                         ALWAYS_LOCATION_PERMISSIONS, ACTIVITY_RECOGNITION_PERMISSIONS);
647             }
648         }
649         if (locationExtraPackageNames != null) {
650             // Also grant location permission to location extra packages.
651             for (String packageName : locationExtraPackageNames) {
652                 grantPermissionsToSystemPackage(packageName, userId, ALWAYS_LOCATION_PERMISSIONS);
653             }
654         }
655 
656         // Music
657         Intent musicIntent = new Intent(Intent.ACTION_VIEW)
658                 .addCategory(Intent.CATEGORY_DEFAULT)
659                 .setDataAndType(Uri.fromFile(new File("foo.mp3")), AUDIO_MIME_TYPE);
660         grantPermissionsToSystemPackage(
661                 getDefaultSystemHandlerActivityPackage(musicIntent, userId), userId,
662                 STORAGE_PERMISSIONS);
663 
664         // Home
665         Intent homeIntent = new Intent(Intent.ACTION_MAIN)
666                 .addCategory(Intent.CATEGORY_HOME)
667                 .addCategory(Intent.CATEGORY_LAUNCHER_APP);
668         grantPermissionsToSystemPackage(
669                 getDefaultSystemHandlerActivityPackage(homeIntent, userId), userId,
670                 ALWAYS_LOCATION_PERMISSIONS);
671 
672         // Watches
673         if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0)) {
674             // Home application on watches
675 
676             String wearPackage = getDefaultSystemHandlerActivityPackageForCategory(
677                     Intent.CATEGORY_HOME_MAIN, userId);
678             grantPermissionsToSystemPackage(wearPackage, userId,
679                     CONTACTS_PERMISSIONS, MICROPHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS);
680             grantSystemFixedPermissionsToSystemPackage(wearPackage, userId, PHONE_PERMISSIONS);
681 
682             // Fitness tracking on watches
683             grantPermissionsToSystemPackage(
684                     getDefaultSystemHandlerActivityPackage(ACTION_TRACK, userId), userId,
685                     SENSORS_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS);
686         }
687 
688         // Print Spooler
689         grantSystemFixedPermissionsToSystemPackage(PrintManager.PRINT_SPOOLER_PACKAGE_NAME, userId,
690                 ALWAYS_LOCATION_PERMISSIONS);
691 
692         // EmergencyInfo
693         grantSystemFixedPermissionsToSystemPackage(
694                 getDefaultSystemHandlerActivityPackage(
695                         TelephonyManager.ACTION_EMERGENCY_ASSISTANCE, userId),
696                 userId, CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
697 
698         // NFC Tag viewer
699         Intent nfcTagIntent = new Intent(Intent.ACTION_VIEW)
700                 .setType("vnd.android.cursor.item/ndef_msg");
701         grantPermissionsToSystemPackage(
702                 getDefaultSystemHandlerActivityPackage(nfcTagIntent, userId), userId,
703                 CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
704 
705         // Storage Manager
706         grantSystemFixedPermissionsToSystemPackage(
707                 getDefaultSystemHandlerActivityPackage(
708                         StorageManager.ACTION_MANAGE_STORAGE, userId),
709                 userId, STORAGE_PERMISSIONS);
710 
711         // Companion devices
712         grantSystemFixedPermissionsToSystemPackage(
713                 CompanionDeviceManager.COMPANION_DEVICE_DISCOVERY_PACKAGE_NAME, userId,
714                 ALWAYS_LOCATION_PERMISSIONS);
715 
716         // Ringtone Picker
717         grantSystemFixedPermissionsToSystemPackage(
718                 getDefaultSystemHandlerActivityPackage(
719                         RingtoneManager.ACTION_RINGTONE_PICKER, userId),
720                 userId, STORAGE_PERMISSIONS);
721 
722         // TextClassifier Service
723         String textClassifierPackageName =
724                 mContext.getPackageManager().getSystemTextClassifierPackageName();
725         if (!TextUtils.isEmpty(textClassifierPackageName)) {
726             grantPermissionsToSystemPackage(textClassifierPackageName, userId,
727                     PHONE_PERMISSIONS, SMS_PERMISSIONS, CALENDAR_PERMISSIONS,
728                     ALWAYS_LOCATION_PERMISSIONS, CONTACTS_PERMISSIONS);
729         }
730 
731         // Atthention Service
732         String attentionServicePackageName =
733                 mContext.getPackageManager().getAttentionServicePackageName();
734         if (!TextUtils.isEmpty(attentionServicePackageName)) {
735             grantPermissionsToSystemPackage(attentionServicePackageName, userId,
736                     CAMERA_PERMISSIONS);
737         }
738 
739         // There is no real "marker" interface to identify the shared storage backup, it is
740         // hardcoded in BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE.
741         grantSystemFixedPermissionsToSystemPackage("com.android.sharedstoragebackup", userId,
742                 STORAGE_PERMISSIONS);
743 
744         // System Captions Service
745         String systemCaptionsServicePackageName =
746                 mContext.getPackageManager().getSystemCaptionsServicePackageName();
747         if (!TextUtils.isEmpty(systemCaptionsServicePackageName)) {
748             grantPermissionsToSystemPackage(systemCaptionsServicePackageName, userId,
749                     MICROPHONE_PERMISSIONS);
750         }
751     }
752 
getDefaultSystemHandlerActivityPackageForCategory(String category, int userId)753     private String getDefaultSystemHandlerActivityPackageForCategory(String category, int userId) {
754         return getDefaultSystemHandlerActivityPackage(
755                 new Intent(Intent.ACTION_MAIN).addCategory(category), userId);
756     }
757 
758     @SafeVarargs
grantPermissionToEachSystemPackage( ArrayList<String> packages, int userId, Set<String>... permissions)759     private final void grantPermissionToEachSystemPackage(
760             ArrayList<String> packages, int userId, Set<String>... permissions) {
761         if (packages == null) return;
762         final int count = packages.size();
763         for (int i = 0; i < count; i++) {
764             grantPermissionsToSystemPackage(packages.get(i), userId, permissions);
765         }
766     }
767 
getKnownPackages(int knownPkgId, int userId)768     private @NonNull String[] getKnownPackages(int knownPkgId, int userId) {
769         return mServiceInternal.getKnownPackageNames(knownPkgId, userId);
770     }
771 
grantDefaultPermissionsToDefaultSystemDialerApp( String dialerPackage, int userId)772     private void grantDefaultPermissionsToDefaultSystemDialerApp(
773             String dialerPackage, int userId) {
774         if (dialerPackage == null) {
775             return;
776         }
777         boolean isPhonePermFixed =
778                 mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0);
779         if (isPhonePermFixed) {
780             grantSystemFixedPermissionsToSystemPackage(dialerPackage, userId, PHONE_PERMISSIONS);
781         } else {
782             grantPermissionsToSystemPackage(dialerPackage, userId, PHONE_PERMISSIONS);
783         }
784         grantPermissionsToSystemPackage(dialerPackage, userId,
785                 CONTACTS_PERMISSIONS, SMS_PERMISSIONS, MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
786     }
787 
grantDefaultPermissionsToDefaultSystemSmsApp(String smsPackage, int userId)788     private void grantDefaultPermissionsToDefaultSystemSmsApp(String smsPackage, int userId) {
789         grantPermissionsToSystemPackage(smsPackage, userId,
790                 PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, SMS_PERMISSIONS,
791                 STORAGE_PERMISSIONS, MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
792     }
793 
grantDefaultPermissionsToDefaultSystemUseOpenWifiApp( String useOpenWifiPackage, int userId)794     private void grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(
795             String useOpenWifiPackage, int userId) {
796         grantPermissionsToSystemPackage(useOpenWifiPackage, userId, ALWAYS_LOCATION_PERMISSIONS);
797     }
798 
grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId)799     public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
800         Log.i(TAG, "Granting permissions to default Use Open WiFi app for user:" + userId);
801         grantIgnoringSystemPackage(packageName, userId, ALWAYS_LOCATION_PERMISSIONS);
802     }
803 
grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId)804     public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
805         if (packageName == null) {
806             return;
807         }
808         Log.i(TAG, "Granting permissions to sim call manager for user:" + userId);
809         grantPermissionsToPackage(packageName, userId, false /* ignoreSystemPackage */,
810                 true /*whitelistRestrictedPermissions*/, PHONE_PERMISSIONS, MICROPHONE_PERMISSIONS);
811     }
812 
grantDefaultPermissionsToDefaultSystemSimCallManager( String packageName, int userId)813     private void grantDefaultPermissionsToDefaultSystemSimCallManager(
814             String packageName, int userId) {
815         if (isSystemPackage(packageName)) {
816             grantDefaultPermissionsToDefaultSimCallManager(packageName, userId);
817         }
818     }
819 
grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId)820     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
821         Log.i(TAG, "Granting permissions to enabled carrier apps for user:" + userId);
822         if (packageNames == null) {
823             return;
824         }
825         for (String packageName : packageNames) {
826             grantPermissionsToSystemPackage(packageName, userId,
827                     PHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS, SMS_PERMISSIONS);
828         }
829     }
830 
grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId)831     public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
832         Log.i(TAG, "Granting permissions to enabled ImsServices for user:" + userId);
833         if (packageNames == null) {
834             return;
835         }
836         for (String packageName : packageNames) {
837             grantPermissionsToSystemPackage(packageName, userId,
838                     PHONE_PERMISSIONS, MICROPHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS,
839                     CAMERA_PERMISSIONS, CONTACTS_PERMISSIONS);
840         }
841     }
842 
grantDefaultPermissionsToEnabledTelephonyDataServices( String[] packageNames, int userId)843     public void grantDefaultPermissionsToEnabledTelephonyDataServices(
844             String[] packageNames, int userId) {
845         Log.i(TAG, "Granting permissions to enabled data services for user:" + userId);
846         if (packageNames == null) {
847             return;
848         }
849         for (String packageName : packageNames) {
850             // Grant these permissions as system-fixed, so that nobody can accidentally
851             // break cellular data.
852             grantSystemFixedPermissionsToSystemPackage(packageName, userId,
853                     PHONE_PERMISSIONS, ALWAYS_LOCATION_PERMISSIONS);
854         }
855     }
856 
revokeDefaultPermissionsFromDisabledTelephonyDataServices( String[] packageNames, int userId)857     public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
858             String[] packageNames, int userId) {
859         Log.i(TAG, "Revoking permissions from disabled data services for user:" + userId);
860         if (packageNames == null) {
861             return;
862         }
863         for (String packageName : packageNames) {
864             PackageInfo pkg = getSystemPackageInfo(packageName);
865             if (isSystemPackage(pkg) && doesPackageSupportRuntimePermissions(pkg)) {
866                 revokeRuntimePermissions(packageName, PHONE_PERMISSIONS, true, userId);
867                 revokeRuntimePermissions(packageName, ALWAYS_LOCATION_PERMISSIONS, true, userId);
868             }
869         }
870     }
871 
grantDefaultPermissionsToActiveLuiApp(String packageName, int userId)872     public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
873         Log.i(TAG, "Granting permissions to active LUI app for user:" + userId);
874         grantSystemFixedPermissionsToSystemPackage(packageName, userId, CAMERA_PERMISSIONS);
875     }
876 
revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId)877     public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
878         Log.i(TAG, "Revoke permissions from LUI apps for user:" + userId);
879         if (packageNames == null) {
880             return;
881         }
882         for (String packageName : packageNames) {
883             PackageInfo pkg = getSystemPackageInfo(packageName);
884             if (isSystemPackage(pkg) && doesPackageSupportRuntimePermissions(pkg)) {
885                 revokeRuntimePermissions(packageName, CAMERA_PERMISSIONS, true, userId);
886             }
887         }
888     }
889 
grantDefaultPermissionsToDefaultBrowser(String packageName, int userId)890     public void grantDefaultPermissionsToDefaultBrowser(String packageName, int userId) {
891         Log.i(TAG, "Granting permissions to default browser for user:" + userId);
892         grantPermissionsToSystemPackage(packageName, userId, ALWAYS_LOCATION_PERMISSIONS);
893     }
894 
getDefaultSystemHandlerActivityPackage(String intentAction, int userId)895     private String getDefaultSystemHandlerActivityPackage(String intentAction, int userId) {
896         return getDefaultSystemHandlerActivityPackage(new Intent(intentAction), userId);
897     }
898 
getDefaultSystemHandlerActivityPackage(Intent intent, int userId)899     private String getDefaultSystemHandlerActivityPackage(Intent intent, int userId) {
900         ResolveInfo handler = mContext.getPackageManager().resolveActivityAsUser(
901                 intent, DEFAULT_INTENT_QUERY_FLAGS, userId);
902         if (handler == null || handler.activityInfo == null) {
903             return null;
904         }
905         if (mServiceInternal.isResolveActivityComponent(handler.activityInfo)) {
906             return null;
907         }
908         String packageName = handler.activityInfo.packageName;
909         return isSystemPackage(packageName) ? packageName : null;
910     }
911 
getDefaultSystemHandlerServicePackage(String intentAction, int userId)912     private String getDefaultSystemHandlerServicePackage(String intentAction, int userId) {
913         return getDefaultSystemHandlerServicePackage(new Intent(intentAction), userId);
914     }
915 
getDefaultSystemHandlerServicePackage( Intent intent, int userId)916     private String getDefaultSystemHandlerServicePackage(
917             Intent intent, int userId) {
918         List<ResolveInfo> handlers = mContext.getPackageManager().queryIntentServicesAsUser(
919                 intent, DEFAULT_INTENT_QUERY_FLAGS, userId);
920         if (handlers == null) {
921             return null;
922         }
923         final int handlerCount = handlers.size();
924         for (int i = 0; i < handlerCount; i++) {
925             ResolveInfo handler = handlers.get(i);
926             String handlerPackage = handler.serviceInfo.packageName;
927             if (isSystemPackage(handlerPackage)) {
928                 return handlerPackage;
929             }
930         }
931         return null;
932     }
933 
getHeadlessSyncAdapterPackages( String[] syncAdapterPackageNames, int userId)934     private ArrayList<String> getHeadlessSyncAdapterPackages(
935             String[] syncAdapterPackageNames, int userId) {
936         ArrayList<String> syncAdapterPackages = new ArrayList<>();
937 
938         Intent homeIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
939 
940         for (String syncAdapterPackageName : syncAdapterPackageNames) {
941             homeIntent.setPackage(syncAdapterPackageName);
942 
943             ResolveInfo homeActivity = mContext.getPackageManager().resolveActivityAsUser(
944                     homeIntent, DEFAULT_INTENT_QUERY_FLAGS, userId);
945             if (homeActivity != null) {
946                 continue;
947             }
948 
949             if (isSystemPackage(syncAdapterPackageName)) {
950                 syncAdapterPackages.add(syncAdapterPackageName);
951             }
952         }
953 
954         return syncAdapterPackages;
955     }
956 
getDefaultProviderAuthorityPackage(String authority, int userId)957     private String getDefaultProviderAuthorityPackage(String authority, int userId) {
958         ProviderInfo provider = mContext.getPackageManager().resolveContentProviderAsUser(
959                 authority, DEFAULT_INTENT_QUERY_FLAGS, userId);
960         if (provider != null) {
961             return provider.packageName;
962         }
963         return null;
964     }
965 
isSystemPackage(String packageName)966     private boolean isSystemPackage(String packageName) {
967         return isSystemPackage(getPackageInfo(packageName));
968     }
969 
isSystemPackage(PackageInfo pkg)970     private boolean isSystemPackage(PackageInfo pkg) {
971         if (pkg == null) {
972             return false;
973         }
974         return pkg.applicationInfo.isSystemApp()
975                 && !isSysComponentOrPersistentPlatformSignedPrivApp(pkg);
976     }
977 
grantRuntimePermissions(PackageInfo pkg, Set<String> permissions, boolean systemFixed, int userId)978     private void grantRuntimePermissions(PackageInfo pkg, Set<String> permissions,
979             boolean systemFixed, int userId) {
980         grantRuntimePermissions(pkg, permissions, systemFixed, false,
981                 true /*whitelistRestrictedPermissions*/, userId);
982     }
983 
revokeRuntimePermissions(String packageName, Set<String> permissions, boolean systemFixed, int userId)984     private void revokeRuntimePermissions(String packageName, Set<String> permissions,
985             boolean systemFixed, int userId) {
986         PackageInfo pkg = getSystemPackageInfo(packageName);
987         if (ArrayUtils.isEmpty(pkg.requestedPermissions)) {
988             return;
989         }
990         Set<String> revokablePermissions = new ArraySet<>(Arrays.asList(pkg.requestedPermissions));
991 
992         for (String permission : permissions) {
993             // We can't revoke what wasn't requested.
994             if (!revokablePermissions.contains(permission)) {
995                 continue;
996             }
997 
998             UserHandle user = UserHandle.of(userId);
999             final int flags = mContext.getPackageManager()
1000                     .getPermissionFlags(permission, packageName, user);
1001 
1002             // We didn't get this through the default grant policy. Move along.
1003             if ((flags & PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT) == 0) {
1004                 continue;
1005             }
1006             // We aren't going to clobber device policy with a DefaultGrant.
1007             if ((flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
1008                 continue;
1009             }
1010             // Do not revoke system fixed permissions unless caller set them that way;
1011             // there is no refcount for the number of sources of this, so there
1012             // should be at most one grantor doing SYSTEM_FIXED for any given package.
1013             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0 && !systemFixed) {
1014                 continue;
1015             }
1016             mContext.getPackageManager().revokeRuntimePermission(packageName, permission, user);
1017 
1018             if (DEBUG) {
1019                 Log.i(TAG, "revoked " + (systemFixed ? "fixed " : "not fixed ")
1020                         + permission + " to " + packageName);
1021             }
1022 
1023             // Remove the GRANTED_BY_DEFAULT flag without touching the others.
1024             // Note that we do not revoke FLAG_PERMISSION_SYSTEM_FIXED. That bit remains
1025             // sticky once set.
1026             mContext.getPackageManager().updatePermissionFlags(permission, packageName,
1027                     PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, 0, user);
1028         }
1029     }
1030 
1031     /**
1032      * Check if a permission is already fixed or is set by the user.
1033      *
1034      * <p>A permission should not be set by the default policy if the user or other policies already
1035      * set the permission.
1036      *
1037      * @param flags The flags of the permission
1038      *
1039      * @return {@code true} iff the permission can be set without violating a policy of the users
1040      *         intention
1041      */
isFixedOrUserSet(int flags)1042     private boolean isFixedOrUserSet(int flags) {
1043         return (flags & (PackageManager.FLAG_PERMISSION_USER_SET
1044                 | PackageManager.FLAG_PERMISSION_USER_FIXED
1045                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
1046                 | PackageManager.FLAG_PERMISSION_SYSTEM_FIXED)) != 0;
1047     }
1048 
1049     /**
1050      * Return the background permission for a permission.
1051      *
1052      * @param permission The name of the foreground permission
1053      *
1054      * @return The name of the background permission or {@code null} if the permission has no
1055      *         background permission
1056      */
getBackgroundPermission(@onNull String permission)1057     private @Nullable String getBackgroundPermission(@NonNull String permission) {
1058         try {
1059             return mContext.getPackageManager().getPermissionInfo(permission,
1060                     0).backgroundPermission;
1061         } catch (NameNotFoundException e) {
1062             return null;
1063         }
1064     }
1065 
grantRuntimePermissions(PackageInfo pkg, Set<String> permissionsWithoutSplits, boolean systemFixed, boolean ignoreSystemPackage, boolean whitelistRestrictedPermissions, int userId)1066     private void grantRuntimePermissions(PackageInfo pkg, Set<String> permissionsWithoutSplits,
1067             boolean systemFixed, boolean ignoreSystemPackage,
1068             boolean whitelistRestrictedPermissions, int userId) {
1069         UserHandle user = UserHandle.of(userId);
1070         if (pkg == null) {
1071             return;
1072         }
1073 
1074         String[] requestedPermissions = pkg.requestedPermissions;
1075         if (ArrayUtils.isEmpty(requestedPermissions)) {
1076             return;
1077         }
1078 
1079         // Intersect the requestedPermissions for a factory image with that of its current update
1080         // in case the latter one removed a <uses-permission>
1081         String[] requestedByNonSystemPackage = getPackageInfo(pkg.packageName).requestedPermissions;
1082         int size = requestedPermissions.length;
1083         for (int i = 0; i < size; i++) {
1084             if (!ArrayUtils.contains(requestedByNonSystemPackage, requestedPermissions[i])) {
1085                 requestedPermissions[i] = null;
1086             }
1087         }
1088         requestedPermissions = ArrayUtils.filterNotNull(requestedPermissions, String[]::new);
1089 
1090         PackageManager pm;
1091         try {
1092             pm = mContext.createPackageContextAsUser(mContext.getPackageName(), 0,
1093                     user).getPackageManager();
1094         } catch (NameNotFoundException doesNotHappen) {
1095             throw new IllegalStateException(doesNotHappen);
1096         }
1097 
1098         final ArraySet<String> permissions = new ArraySet<>(permissionsWithoutSplits);
1099         ApplicationInfo applicationInfo = pkg.applicationInfo;
1100 
1101         int newFlags = PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1102         if (systemFixed) {
1103             newFlags |= PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
1104         }
1105 
1106         // Automatically attempt to grant split permissions to older APKs
1107         final List<PermissionManager.SplitPermissionInfo> splitPermissions =
1108                 mContext.getSystemService(PermissionManager.class).getSplitPermissions();
1109         final int numSplitPerms = splitPermissions.size();
1110         for (int splitPermNum = 0; splitPermNum < numSplitPerms; splitPermNum++) {
1111             final PermissionManager.SplitPermissionInfo splitPerm =
1112                     splitPermissions.get(splitPermNum);
1113 
1114             if (applicationInfo != null
1115                     && applicationInfo.targetSdkVersion < splitPerm.getTargetSdk()
1116                     && permissionsWithoutSplits.contains(splitPerm.getSplitPermission())) {
1117                 permissions.addAll(splitPerm.getNewPermissions());
1118             }
1119         }
1120 
1121         Set<String> grantablePermissions = null;
1122 
1123         // In some cases, like for the Phone or SMS app, we grant permissions regardless
1124         // of if the version on the system image declares the permission as used since
1125         // selecting the app as the default for that function the user makes a deliberate
1126         // choice to grant this app the permissions needed to function. For all other
1127         // apps, (default grants on first boot and user creation) we don't grant default
1128         // permissions if the version on the system image does not declare them.
1129         if (!ignoreSystemPackage
1130                 && applicationInfo != null
1131                 && applicationInfo.isUpdatedSystemApp()) {
1132             final PackageInfo disabledPkg = getSystemPackageInfo(
1133                     mServiceInternal.getDisabledSystemPackageName(pkg.packageName));
1134             if (disabledPkg != null) {
1135                 if (ArrayUtils.isEmpty(disabledPkg.requestedPermissions)) {
1136                     return;
1137                 }
1138                 if (!Arrays.equals(requestedPermissions, disabledPkg.requestedPermissions)) {
1139                     grantablePermissions = new ArraySet<>(Arrays.asList(requestedPermissions));
1140                     requestedPermissions = disabledPkg.requestedPermissions;
1141                 }
1142             }
1143         }
1144 
1145         final int numRequestedPermissions = requestedPermissions.length;
1146 
1147         // Sort requested permissions so that all permissions that are a foreground permission (i.e.
1148         // permissions that have a background permission) are before their background permissions.
1149         final String[] sortedRequestedPermissions = new String[numRequestedPermissions];
1150         int numForeground = 0;
1151         int numOther = 0;
1152         for (int i = 0; i < numRequestedPermissions; i++) {
1153             String permission = requestedPermissions[i];
1154             if (getBackgroundPermission(permission) != null) {
1155                 sortedRequestedPermissions[numForeground] = permission;
1156                 numForeground++;
1157             } else {
1158                 sortedRequestedPermissions[numRequestedPermissions - 1 - numOther] =
1159                         permission;
1160                 numOther++;
1161             }
1162         }
1163 
1164         for (int requestedPermissionNum = 0; requestedPermissionNum < numRequestedPermissions;
1165                 requestedPermissionNum++) {
1166             String permission = requestedPermissions[requestedPermissionNum];
1167 
1168             // If there is a disabled system app it may request a permission the updated
1169             // version ot the data partition doesn't, In this case skip the permission.
1170             if (grantablePermissions != null && !grantablePermissions.contains(permission)) {
1171                 continue;
1172             }
1173 
1174             if (permissions.contains(permission)) {
1175                 final int flags = mContext.getPackageManager().getPermissionFlags(
1176                         permission, pkg.packageName, user);
1177 
1178                 // If we are trying to grant as system fixed and already system fixed
1179                 // then the system can change the system fixed grant state.
1180                 final boolean changingGrantForSystemFixed = systemFixed
1181                         && (flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0;
1182 
1183                 // Certain flags imply that the permission's current state by the system or
1184                 // device/profile owner or the user. In these cases we do not want to clobber the
1185                 // current state.
1186                 //
1187                 // Unless the caller wants to override user choices. The override is
1188                 // to make sure we can grant the needed permission to the default
1189                 // sms and phone apps after the user chooses this in the UI.
1190                 if (!isFixedOrUserSet(flags) || ignoreSystemPackage
1191                         || changingGrantForSystemFixed) {
1192                     // Never clobber policy fixed permissions.
1193                     // We must allow the grant of a system-fixed permission because
1194                     // system-fixed is sticky, but the permission itself may be revoked.
1195                     if ((flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
1196                         continue;
1197                     }
1198 
1199                     // Preserve whitelisting flags.
1200                     newFlags |= (flags & PackageManager.FLAGS_PERMISSION_RESTRICTION_ANY_EXEMPT);
1201 
1202                     // If we are whitelisting the permission, update the exempt flag before grant.
1203                     if (whitelistRestrictedPermissions && isPermissionRestricted(permission)) {
1204                         mContext.getPackageManager().updatePermissionFlags(permission,
1205                                 pkg.packageName,
1206                                 PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT,
1207                                 PackageManager.FLAG_PERMISSION_RESTRICTION_SYSTEM_EXEMPT, user);
1208                     }
1209 
1210                     // If the system tries to change a system fixed permission from one fixed
1211                     // state to another we need to drop the fixed flag to allow the grant.
1212                     if (changingGrantForSystemFixed) {
1213                         mContext.getPackageManager().updatePermissionFlags(permission,
1214                                 pkg.packageName, flags,
1215                                 flags & ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, user);
1216                     }
1217 
1218                     if (pm.checkPermission(permission, pkg.packageName)
1219                             != PackageManager.PERMISSION_GRANTED) {
1220                         mContext.getPackageManager()
1221                                 .grantRuntimePermission(pkg.packageName, permission, user);
1222                     }
1223 
1224                     mContext.getPackageManager().updatePermissionFlags(permission, pkg.packageName,
1225                             newFlags, newFlags, user);
1226 
1227                     int uid = UserHandle.getUid(userId,
1228                             UserHandle.getAppId(pkg.applicationInfo.uid));
1229 
1230                     List<String> fgPerms = mPermissionManager.getBackgroundPermissions()
1231                             .get(permission);
1232                     if (fgPerms != null) {
1233                         int numFgPerms = fgPerms.size();
1234                         for (int fgPermNum = 0; fgPermNum < numFgPerms; fgPermNum++) {
1235                             String fgPerm = fgPerms.get(fgPermNum);
1236 
1237                             if (pm.checkPermission(fgPerm, pkg.packageName)
1238                                     == PackageManager.PERMISSION_GRANTED) {
1239                                 // Upgrade the app-op state of the fg permission to allow bg access
1240                                 // TODO: Dont' call app ops from package manager code.
1241                                 mContext.getSystemService(AppOpsManager.class).setUidMode(
1242                                         AppOpsManager.permissionToOp(fgPerm), uid,
1243                                         AppOpsManager.MODE_ALLOWED);
1244 
1245                                 break;
1246                             }
1247                         }
1248                     }
1249 
1250                     String bgPerm = getBackgroundPermission(permission);
1251                     String op = AppOpsManager.permissionToOp(permission);
1252                     if (bgPerm == null) {
1253                         if (op != null) {
1254                             // TODO: Dont' call app ops from package manager code.
1255                             mContext.getSystemService(AppOpsManager.class).setUidMode(op, uid,
1256                                     AppOpsManager.MODE_ALLOWED);
1257                         }
1258                     } else {
1259                         int mode;
1260                         if (pm.checkPermission(bgPerm, pkg.packageName)
1261                                 == PackageManager.PERMISSION_GRANTED) {
1262                             mode = AppOpsManager.MODE_ALLOWED;
1263                         } else {
1264                             mode = AppOpsManager.MODE_FOREGROUND;
1265                         }
1266 
1267                         mContext.getSystemService(AppOpsManager.class).setUidMode(op, uid, mode);
1268                     }
1269 
1270                     if (DEBUG) {
1271                         Log.i(TAG, "Granted " + (systemFixed ? "fixed " : "not fixed ")
1272                                 + permission + " to default handler " + pkg);
1273 
1274                         int appOp = AppOpsManager.permissionToOpCode(permission);
1275                         if (appOp != AppOpsManager.OP_NONE
1276                                 && AppOpsManager.opToDefaultMode(appOp)
1277                                         != AppOpsManager.MODE_ALLOWED) {
1278                             // Permission has a corresponding appop which is not allowed by default
1279                             // We must allow it as well, as it's usually checked alongside the
1280                             // permission
1281                             if (DEBUG) {
1282                                 Log.i(TAG, "Granting OP_" + AppOpsManager.opToName(appOp)
1283                                         + " to " + pkg.packageName);
1284                             }
1285                             mContext.getSystemService(AppOpsManager.class).setUidMode(
1286                                     appOp, pkg.applicationInfo.uid, AppOpsManager.MODE_ALLOWED);
1287                         }
1288                     }
1289                 }
1290 
1291                 // If a component gets a permission for being the default handler A
1292                 // and also default handler B, we grant the weaker grant form.
1293                 if ((flags & PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0
1294                         && (flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0
1295                         && !systemFixed) {
1296                     if (DEBUG) {
1297                         Log.i(TAG, "Granted not fixed " + permission + " to default handler "
1298                                 + pkg);
1299                     }
1300                     mContext.getPackageManager().updatePermissionFlags(permission, pkg.packageName,
1301                             PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, 0, user);
1302                 }
1303             }
1304         }
1305     }
1306 
getSystemPackageInfo(String pkg)1307     private PackageInfo getSystemPackageInfo(String pkg) {
1308         return getPackageInfo(pkg, PackageManager.MATCH_SYSTEM_ONLY);
1309     }
1310 
getPackageInfo(String pkg)1311     private PackageInfo getPackageInfo(String pkg) {
1312         return getPackageInfo(pkg, 0 /* extraFlags */);
1313     }
1314 
getPackageInfo(String pkg, @PackageManager.PackageInfoFlags int extraFlags)1315     private PackageInfo getPackageInfo(String pkg,
1316             @PackageManager.PackageInfoFlags int extraFlags) {
1317         if (pkg == null) {
1318             return null;
1319         }
1320         try {
1321             return mContext.getPackageManager().getPackageInfo(pkg,
1322                     DEFAULT_PACKAGE_INFO_QUERY_FLAGS | extraFlags);
1323         } catch (NameNotFoundException e) {
1324             Slog.e(TAG, "PackageNot found: " + pkg, e);
1325             return null;
1326         }
1327     }
1328 
isSysComponentOrPersistentPlatformSignedPrivApp(PackageInfo pkg)1329     private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageInfo pkg) {
1330         if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
1331             return true;
1332         }
1333         if (!pkg.applicationInfo.isPrivilegedApp()) {
1334             return false;
1335         }
1336         final PackageInfo disabledPkg = getSystemPackageInfo(
1337                 mServiceInternal.getDisabledSystemPackageName(pkg.applicationInfo.packageName));
1338         if (disabledPkg != null) {
1339             ApplicationInfo disabledPackageAppInfo = disabledPkg.applicationInfo;
1340             if (disabledPackageAppInfo != null
1341                     && (disabledPackageAppInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
1342                 return false;
1343             }
1344         } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
1345             return false;
1346         }
1347         return mServiceInternal.isPlatformSigned(pkg.packageName);
1348     }
1349 
grantDefaultPermissionExceptions(int userId)1350     private void grantDefaultPermissionExceptions(int userId) {
1351         mHandler.removeMessages(MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS);
1352 
1353         synchronized (mLock) {
1354             // mGrantExceptions is null only before the first read and then
1355             // it serves as a cache of the default grants that should be
1356             // performed for every user. If there is an entry then the app
1357             // is on the system image and supports runtime permissions.
1358             if (mGrantExceptions == null) {
1359                 mGrantExceptions = readDefaultPermissionExceptionsLocked();
1360             }
1361         }
1362 
1363         Set<String> permissions = null;
1364         final int exceptionCount = mGrantExceptions.size();
1365         for (int i = 0; i < exceptionCount; i++) {
1366             String packageName = mGrantExceptions.keyAt(i);
1367             PackageInfo pkg = getSystemPackageInfo(packageName);
1368             List<DefaultPermissionGrant> permissionGrants = mGrantExceptions.valueAt(i);
1369             final int permissionGrantCount = permissionGrants.size();
1370             for (int j = 0; j < permissionGrantCount; j++) {
1371                 DefaultPermissionGrant permissionGrant = permissionGrants.get(j);
1372                 if (!isPermissionDangerous(permissionGrant.name)) {
1373                     Log.w(TAG, "Ignoring permission " + permissionGrant.name
1374                             + " which isn't dangerous");
1375                     continue;
1376                 }
1377                 if (permissions == null) {
1378                     permissions = new ArraySet<>();
1379                 } else {
1380                     permissions.clear();
1381                 }
1382                 permissions.add(permissionGrant.name);
1383 
1384 
1385                 grantRuntimePermissions(pkg, permissions, permissionGrant.fixed,
1386                         permissionGrant.whitelisted, true /*whitelistRestrictedPermissions*/,
1387                         userId);
1388             }
1389         }
1390     }
1391 
getDefaultPermissionFiles()1392     private File[] getDefaultPermissionFiles() {
1393         ArrayList<File> ret = new ArrayList<File>();
1394         File dir = new File(Environment.getRootDirectory(), "etc/default-permissions");
1395         if (dir.isDirectory() && dir.canRead()) {
1396             Collections.addAll(ret, dir.listFiles());
1397         }
1398         dir = new File(Environment.getVendorDirectory(), "etc/default-permissions");
1399         if (dir.isDirectory() && dir.canRead()) {
1400             Collections.addAll(ret, dir.listFiles());
1401         }
1402         dir = new File(Environment.getOdmDirectory(), "etc/default-permissions");
1403         if (dir.isDirectory() && dir.canRead()) {
1404             Collections.addAll(ret, dir.listFiles());
1405         }
1406         dir = new File(Environment.getProductDirectory(), "etc/default-permissions");
1407         if (dir.isDirectory() && dir.canRead()) {
1408             Collections.addAll(ret, dir.listFiles());
1409         }
1410         dir = new File(Environment.getSystemExtDirectory(), "etc/default-permissions");
1411         if (dir.isDirectory() && dir.canRead()) {
1412             Collections.addAll(ret, dir.listFiles());
1413         }
1414         // For IoT devices, we check the oem partition for default permissions for each app.
1415         if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_EMBEDDED, 0)) {
1416             dir = new File(Environment.getOemDirectory(), "etc/default-permissions");
1417             if (dir.isDirectory() && dir.canRead()) {
1418                 Collections.addAll(ret, dir.listFiles());
1419             }
1420         }
1421         return ret.isEmpty() ? null : ret.toArray(new File[0]);
1422     }
1423 
1424     private @NonNull ArrayMap<String, List<DefaultPermissionGrant>>
readDefaultPermissionExceptionsLocked()1425             readDefaultPermissionExceptionsLocked() {
1426         File[] files = getDefaultPermissionFiles();
1427         if (files == null) {
1428             return new ArrayMap<>(0);
1429         }
1430 
1431         ArrayMap<String, List<DefaultPermissionGrant>> grantExceptions = new ArrayMap<>();
1432 
1433         // Iterate over the files in the directory and scan .xml files
1434         for (File file : files) {
1435             if (!file.getPath().endsWith(".xml")) {
1436                 Slog.i(TAG, "Non-xml file " + file
1437                         + " in " + file.getParent() + " directory, ignoring");
1438                 continue;
1439             }
1440             if (!file.canRead()) {
1441                 Slog.w(TAG, "Default permissions file " + file + " cannot be read");
1442                 continue;
1443             }
1444             try (
1445                 InputStream str = new BufferedInputStream(new FileInputStream(file))
1446             ) {
1447                 XmlPullParser parser = Xml.newPullParser();
1448                 parser.setInput(str, null);
1449                 parse(parser, grantExceptions);
1450             } catch (XmlPullParserException | IOException e) {
1451                 Slog.w(TAG, "Error reading default permissions file " + file, e);
1452             }
1453         }
1454 
1455         return grantExceptions;
1456     }
1457 
parse(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>> outGrantExceptions)1458     private void parse(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>>
1459             outGrantExceptions) throws IOException, XmlPullParserException {
1460         final int outerDepth = parser.getDepth();
1461         int type;
1462         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1463                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1464             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1465                 continue;
1466             }
1467             if (TAG_EXCEPTIONS.equals(parser.getName())) {
1468                 parseExceptions(parser, outGrantExceptions);
1469             } else {
1470                 Log.e(TAG, "Unknown tag " + parser.getName());
1471             }
1472         }
1473     }
1474 
parseExceptions(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>> outGrantExceptions)1475     private void parseExceptions(XmlPullParser parser, Map<String, List<DefaultPermissionGrant>>
1476             outGrantExceptions) throws IOException, XmlPullParserException {
1477         final int outerDepth = parser.getDepth();
1478         int type;
1479         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1480                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1481             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1482                 continue;
1483             }
1484             if (TAG_EXCEPTION.equals(parser.getName())) {
1485                 String packageName = parser.getAttributeValue(null, ATTR_PACKAGE);
1486 
1487                 List<DefaultPermissionGrant> packageExceptions =
1488                         outGrantExceptions.get(packageName);
1489                 if (packageExceptions == null) {
1490                     // The package must be on the system image
1491                     PackageInfo packageInfo = getSystemPackageInfo(packageName);
1492 
1493                     if (packageInfo == null) {
1494                         Log.w(TAG, "No such package:" + packageName);
1495                         XmlUtils.skipCurrentTag(parser);
1496                         continue;
1497                     }
1498 
1499                     if (!isSystemPackage(packageInfo)) {
1500                         Log.w(TAG, "Unknown system package:" + packageName);
1501                         XmlUtils.skipCurrentTag(parser);
1502                         continue;
1503                     }
1504 
1505                     // The package must support runtime permissions
1506                     if (!doesPackageSupportRuntimePermissions(packageInfo)) {
1507                         Log.w(TAG, "Skipping non supporting runtime permissions package:"
1508                                 + packageName);
1509                         XmlUtils.skipCurrentTag(parser);
1510                         continue;
1511                     }
1512                     packageExceptions = new ArrayList<>();
1513                     outGrantExceptions.put(packageName, packageExceptions);
1514                 }
1515 
1516                 parsePermission(parser, packageExceptions);
1517             } else {
1518                 Log.e(TAG, "Unknown tag " + parser.getName() + "under <exceptions>");
1519             }
1520         }
1521     }
1522 
parsePermission(XmlPullParser parser, List<DefaultPermissionGrant> outPackageExceptions)1523     private void parsePermission(XmlPullParser parser, List<DefaultPermissionGrant>
1524             outPackageExceptions) throws IOException, XmlPullParserException {
1525         final int outerDepth = parser.getDepth();
1526         int type;
1527         while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
1528                 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1529             if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
1530                 continue;
1531             }
1532 
1533             if (TAG_PERMISSION.contains(parser.getName())) {
1534                 String name = parser.getAttributeValue(null, ATTR_NAME);
1535                 if (name == null) {
1536                     Log.w(TAG, "Mandatory name attribute missing for permission tag");
1537                     XmlUtils.skipCurrentTag(parser);
1538                     continue;
1539                 }
1540 
1541                 final boolean fixed = XmlUtils.readBooleanAttribute(parser, ATTR_FIXED);
1542                 final boolean whitelisted = XmlUtils.readBooleanAttribute(parser, ATTR_WHITELISTED);
1543 
1544                 DefaultPermissionGrant exception = new DefaultPermissionGrant(
1545                         name, fixed, whitelisted);
1546                 outPackageExceptions.add(exception);
1547             } else {
1548                 Log.e(TAG, "Unknown tag " + parser.getName() + "under <exception>");
1549             }
1550         }
1551     }
1552 
doesPackageSupportRuntimePermissions(PackageInfo pkg)1553     private static boolean doesPackageSupportRuntimePermissions(PackageInfo pkg) {
1554         return pkg.applicationInfo != null
1555                 && pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1;
1556     }
1557 
isPermissionRestricted(String name)1558     private boolean isPermissionRestricted(String name) {
1559         try {
1560             return mContext.getPackageManager().getPermissionInfo(name, 0).isRestricted();
1561         } catch (NameNotFoundException e) {
1562             return false;
1563         }
1564     }
1565 
isPermissionDangerous(String name)1566     private boolean isPermissionDangerous(String name) {
1567         try {
1568             final PermissionInfo pi = mContext.getPackageManager().getPermissionInfo(name, 0);
1569             return (pi.getProtection() == PermissionInfo.PROTECTION_DANGEROUS);
1570         } catch (NameNotFoundException e) {
1571             // When unknown assume it's dangerous to be on the safe side
1572             return true;
1573         }
1574     }
1575 
1576     private static final class DefaultPermissionGrant {
1577         final String name;
1578         final boolean fixed;
1579         final boolean whitelisted;
1580 
DefaultPermissionGrant(String name, boolean fixed, boolean whitelisted)1581         public DefaultPermissionGrant(String name, boolean fixed,
1582                 boolean whitelisted) {
1583             this.name = name;
1584             this.fixed = fixed;
1585             this.whitelisted = whitelisted;
1586         }
1587     }
1588 }
1589