Only system can set application restrictions via UserManager

Preventing apps with MANAGE_USERS from managing application
restrictions via UserManager. Application restrictions should
only be set via DevicePolicyManager.setApplicationRestrictions,
or via Settings (for restricted profiles).

Bug: 22541936
Change-Id: Ieed51ef54b4c23a73f383465e9af9b3bcf18a514
diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java
index 0b59c16..f5da103 100644
--- a/services/core/java/com/android/server/pm/UserManagerService.java
+++ b/services/core/java/com/android/server/pm/UserManagerService.java
@@ -1123,7 +1123,7 @@
      */
     private static final void checkManageUsersPermission(String message) {
         final int uid = Binder.getCallingUid();
-        if (uid != Process.SYSTEM_UID && uid != 0
+        if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID
                 && ActivityManager.checkComponentPermission(
                         android.Manifest.permission.MANAGE_USERS,
                         uid, -1, true) != PackageManager.PERMISSION_GRANTED) {
@@ -1131,6 +1131,20 @@
         }
     }
 
+    /**
+     * Enforces that only the system UID or root's UID (on any user) can make certain calls to the
+     * UserManager.
+     *
+     * @param message used as message if SecurityException is thrown
+     * @throws SecurityException if the caller is not system or root
+     */
+    private static void checkSystemOrRoot(String message) {
+        final int uid = Binder.getCallingUid();
+        if (!UserHandle.isSameApp(uid, Process.SYSTEM_UID) && uid != Process.ROOT_UID) {
+            throw new SecurityException("Only system may: " + message);
+        }
+    }
+
     private void writeBitmapLP(UserInfo info, Bitmap bitmap) {
         try {
             File dir = new File(mUsersDir, Integer.toString(info.id));
@@ -2071,7 +2085,7 @@
     public Bundle getApplicationRestrictionsForUser(String packageName, int userId) {
         if (UserHandle.getCallingUserId() != userId
                 || !UserHandle.isSameApp(Binder.getCallingUid(), getUidForPackage(packageName))) {
-            checkManageUsersPermission("get application restrictions for other users/apps");
+            checkSystemOrRoot("get application restrictions for other users/apps");
         }
         synchronized (mPackagesLock) {
             // Read the restrictions from XML
@@ -2082,7 +2096,7 @@
     @Override
     public void setApplicationRestrictions(String packageName, Bundle restrictions,
             int userId) {
-        checkManageUsersPermission("set application restrictions");
+        checkSystemOrRoot("set application restrictions");
         synchronized (mPackagesLock) {
             if (restrictions == null || restrictions.isEmpty()) {
                 cleanAppRestrictionsForPackage(packageName, userId);