• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2010 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.devicepolicy;
18 
19 import static android.Manifest.permission.BIND_DEVICE_ADMIN;
20 import static android.Manifest.permission.MANAGE_CA_CERTIFICATES;
21 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
22 import static android.app.admin.DeviceAdminReceiver.EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE;
23 import static android.app.admin.DevicePolicyManager.ACTION_PROVISION_MANAGED_USER;
24 import static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY;
25 import static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED;
26 import static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE;
27 import static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED;
28 import static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER;
29 import static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED;
30 import static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED;
31 import static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS;
32 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER;
33 import static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT;
34 import static android.app.admin.DevicePolicyManager.CODE_OK;
35 import static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
36 import static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER;
37 import static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER;
38 import static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING;
39 import static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED;
40 import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
41 import static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL;
42 import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
43 import static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP;
44 import static android.app.admin.DevicePolicyManager.DELEGATION_INSTALL_EXISTING_PACKAGE;
45 import static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES;
46 import static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS;
47 import static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT;
48 import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
49 import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
50 import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
51 import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
52 import static android.app.admin.DevicePolicyManager.LEAVE_ALL_SYSTEM_APPS_ENABLED;
53 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_HOME;
54 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS;
55 import static android.app.admin.DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
56 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
57 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
58 import static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
59 import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
60 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
61 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
62 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
63 
64 import static android.provider.Telephony.Carriers.DPC_URI;
65 import static android.provider.Telephony.Carriers.ENFORCE_KEY;
66 import static android.provider.Telephony.Carriers.ENFORCE_MANAGED_URI;
67 
68 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent
69         .PROVISIONING_ENTRY_POINT_ADB;
70 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker
71         .STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
72 
73 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER;
74 import static com.android.server.devicepolicy.TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER;
75 
76 
77 import static com.android.server.pm.PackageManagerService.PLATFORM_PACKAGE_NAME;
78 
79 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
80 import static org.xmlpull.v1.XmlPullParser.END_TAG;
81 import static org.xmlpull.v1.XmlPullParser.TEXT;
82 
83 import android.Manifest.permission;
84 import android.accessibilityservice.AccessibilityServiceInfo;
85 import android.accounts.Account;
86 import android.accounts.AccountManager;
87 import android.annotation.NonNull;
88 import android.annotation.Nullable;
89 import android.annotation.UserIdInt;
90 import android.app.Activity;
91 import android.app.ActivityManager;
92 import android.app.ActivityManagerInternal;
93 import android.app.ActivityThread;
94 import android.app.AlarmManager;
95 import android.app.AppGlobals;
96 import android.app.IActivityManager;
97 import android.app.IApplicationThread;
98 import android.app.IServiceConnection;
99 import android.app.Notification;
100 import android.app.NotificationManager;
101 import android.app.PendingIntent;
102 import android.app.StatusBarManager;
103 import android.app.admin.DeviceAdminInfo;
104 import android.app.admin.DeviceAdminReceiver;
105 import android.app.admin.DevicePolicyCache;
106 import android.app.admin.DevicePolicyManager;
107 import android.app.admin.DevicePolicyManagerInternal;
108 import android.app.admin.NetworkEvent;
109 import android.app.admin.PasswordMetrics;
110 import android.app.admin.SecurityLog;
111 import android.app.admin.SecurityLog.SecurityEvent;
112 import android.app.admin.SystemUpdateInfo;
113 import android.app.admin.SystemUpdatePolicy;
114 import android.app.backup.IBackupManager;
115 import android.app.backup.ISelectBackupTransportCallback;
116 import android.app.trust.TrustManager;
117 import android.app.usage.UsageStatsManagerInternal;
118 import android.content.BroadcastReceiver;
119 import android.content.ComponentName;
120 import android.content.ContentValues;
121 import android.content.Context;
122 import android.content.Intent;
123 import android.content.IntentFilter;
124 import android.content.pm.ActivityInfo;
125 import android.content.pm.ApplicationInfo;
126 import android.content.pm.IPackageDataObserver;
127 import android.content.pm.IPackageManager;
128 import android.content.pm.PackageInfo;
129 import android.content.pm.PackageManager;
130 import android.content.pm.PackageManager.NameNotFoundException;
131 import android.content.pm.PackageManagerInternal;
132 import android.content.pm.ParceledListSlice;
133 import android.content.pm.PermissionInfo;
134 import android.content.pm.ResolveInfo;
135 import android.content.pm.ServiceInfo;
136 import android.content.pm.StringParceledListSlice;
137 import android.content.pm.UserInfo;
138 import android.content.res.Resources;
139 import android.database.ContentObserver;
140 import android.database.Cursor;
141 import android.graphics.Bitmap;
142 import android.graphics.Color;
143 import android.media.AudioManager;
144 import android.media.IAudioService;
145 import android.net.ConnectivityManager;
146 import android.net.IIpConnectivityMetrics;
147 import android.net.ProxyInfo;
148 import android.net.Uri;
149 import android.net.metrics.IpConnectivityLog;
150 import android.net.wifi.WifiInfo;
151 import android.net.wifi.WifiManager;
152 import android.os.Binder;
153 import android.os.Build;
154 import android.os.Bundle;
155 import android.os.Environment;
156 import android.os.FileUtils;
157 import android.os.Handler;
158 import android.os.IBinder;
159 import android.os.Looper;
160 import android.os.ParcelFileDescriptor;
161 import android.os.PersistableBundle;
162 import android.os.PowerManager;
163 import android.os.PowerManagerInternal;
164 import android.os.Process;
165 import android.os.RecoverySystem;
166 import android.os.RemoteCallback;
167 import android.os.RemoteException;
168 import android.os.ServiceManager;
169 import android.os.ServiceSpecificException;
170 import android.os.SystemClock;
171 import android.os.SystemProperties;
172 import android.os.UserHandle;
173 import android.os.UserManager;
174 import android.os.UserManagerInternal;
175 import android.os.UserManagerInternal.UserRestrictionsListener;
176 import android.os.storage.StorageManager;
177 import android.provider.ContactsContract.QuickContact;
178 import android.provider.ContactsInternal;
179 import android.provider.Settings;
180 import android.provider.Settings.Global;
181 import android.security.IKeyChainAliasCallback;
182 import android.security.IKeyChainService;
183 import android.security.KeyChain;
184 import android.security.KeyChain.KeyChainConnection;
185 import android.security.KeyStore;
186 import android.security.keymaster.KeymasterCertificateChain;
187 import android.security.keystore.AttestationUtils;
188 import android.security.keystore.KeyGenParameterSpec;
189 import android.security.keystore.ParcelableKeyGenParameterSpec;
190 import android.service.persistentdata.PersistentDataBlockManager;
191 import android.telephony.TelephonyManager;
192 import android.telephony.data.ApnSetting;
193 import android.text.TextUtils;
194 import android.util.ArrayMap;
195 import android.util.ArraySet;
196 import android.util.AtomicFile;
197 import android.util.Log;
198 import android.util.Pair;
199 import android.util.Slog;
200 import android.util.SparseArray;
201 import android.util.Xml;
202 import android.view.IWindowManager;
203 import android.view.accessibility.AccessibilityManager;
204 import android.view.accessibility.IAccessibilityManager;
205 import android.view.inputmethod.InputMethodInfo;
206 import android.view.inputmethod.InputMethodManager;
207 
208 import com.android.internal.R;
209 import com.android.internal.annotations.GuardedBy;
210 import com.android.internal.annotations.VisibleForTesting;
211 import com.android.internal.logging.MetricsLogger;
212 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
213 import com.android.internal.notification.SystemNotificationChannels;
214 import com.android.internal.os.BackgroundThread;
215 import com.android.internal.statusbar.IStatusBarService;
216 import com.android.internal.telephony.SmsApplication;
217 import com.android.internal.util.DumpUtils;
218 import com.android.internal.util.FastXmlSerializer;
219 import com.android.internal.util.FunctionalUtils.ThrowingRunnable;
220 import com.android.internal.util.JournaledFile;
221 import com.android.internal.util.Preconditions;
222 import com.android.internal.util.XmlUtils;
223 import com.android.internal.widget.LockPatternUtils;
224 import com.android.server.LocalServices;
225 import com.android.server.LockGuard;
226 import com.android.internal.util.StatLogger;
227 import com.android.server.SystemServerInitThreadPool;
228 import com.android.server.SystemService;
229 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
230 import com.android.server.net.NetworkPolicyManagerInternal;
231 import com.android.server.pm.UserRestrictionsUtils;
232 import com.android.server.storage.DeviceStorageMonitorInternal;
233 
234 import com.google.android.collect.Sets;
235 
236 import org.xmlpull.v1.XmlPullParser;
237 import org.xmlpull.v1.XmlPullParserException;
238 import org.xmlpull.v1.XmlSerializer;
239 
240 import java.io.File;
241 import java.io.FileDescriptor;
242 import java.io.FileInputStream;
243 import java.io.FileNotFoundException;
244 import java.io.FileOutputStream;
245 import java.io.IOException;
246 import java.io.PrintWriter;
247 import java.lang.reflect.Constructor;
248 import java.nio.charset.StandardCharsets;
249 import java.text.DateFormat;
250 import java.time.LocalDate;
251 import java.util.ArrayList;
252 import java.util.Arrays;
253 import java.util.Collection;
254 import java.util.Collections;
255 import java.util.Date;
256 import java.util.HashMap;
257 import java.util.List;
258 import java.util.Map;
259 import java.util.Map.Entry;
260 import java.util.Objects;
261 import java.util.Set;
262 import java.util.concurrent.CountDownLatch;
263 import java.util.concurrent.TimeUnit;
264 import java.util.concurrent.atomic.AtomicBoolean;
265 import java.util.function.Function;
266 
267 /**
268  * Implementation of the device policy APIs.
269  */
270 public class DevicePolicyManagerService extends BaseIDevicePolicyManager {
271 
272     protected static final String LOG_TAG = "DevicePolicyManager";
273 
274     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
275 
276     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
277 
278     private static final String TRANSFER_OWNERSHIP_PARAMETERS_XML =
279             "transfer-ownership-parameters.xml";
280 
281     private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
282 
283     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
284 
285     private static final String TAG_LOCK_TASK_FEATURES = "lock-task-features";
286 
287     private static final String TAG_STATUS_BAR = "statusbar";
288 
289     private static final String ATTR_DISABLED = "disabled";
290 
291     private static final String ATTR_NAME = "name";
292 
293     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
294             "do-not-ask-credentials-on-boot";
295 
296     private static final String TAG_AFFILIATION_ID = "affiliation-id";
297 
298     private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval";
299 
300     private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request";
301 
302     private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval";
303 
304     private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
305 
306     private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set";
307 
308     private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert";
309 
310     private static final String ATTR_ID = "id";
311 
312     private static final String ATTR_VALUE = "value";
313 
314     private static final String ATTR_ALIAS = "alias";
315 
316     private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
317 
318     private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token";
319 
320     private static final String TAG_PASSWORD_VALIDITY = "password-validity";
321 
322     private static final String TAG_TRANSFER_OWNERSHIP_BUNDLE = "transfer-ownership-bundle";
323 
324     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
325 
326     private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1);
327 
328     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
329 
330     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
331             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
332 
333     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
334     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
335     private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
336     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
337     private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
338             "device-provisioning-config-applied";
339     private static final String ATTR_DEVICE_PAIRED = "device-paired";
340     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
341     private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
342             = "application-restrictions-manager";
343 
344     // Comprehensive list of delegations.
345     private static final String DELEGATIONS[] = {
346         DELEGATION_CERT_INSTALL,
347         DELEGATION_APP_RESTRICTIONS,
348         DELEGATION_BLOCK_UNINSTALL,
349         DELEGATION_ENABLE_SYSTEM_APP,
350         DELEGATION_KEEP_UNINSTALLED_PACKAGES,
351         DELEGATION_PACKAGE_ACCESS,
352         DELEGATION_PERMISSION_GRANT,
353         DELEGATION_INSTALL_EXISTING_PACKAGE,
354         DELEGATION_KEEP_UNINSTALLED_PACKAGES
355     };
356 
357     /**
358      *  System property whose value is either "true" or "false", indicating whether
359      *  device owner is present.
360      */
361     private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
362 
363     private static final int STATUS_BAR_DISABLE_MASK =
364             StatusBarManager.DISABLE_EXPAND |
365             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
366             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
367             StatusBarManager.DISABLE_SEARCH;
368 
369     private static final int STATUS_BAR_DISABLE2_MASK =
370             StatusBarManager.DISABLE2_QUICK_SETTINGS;
371 
372     private static final Set<String> SECURE_SETTINGS_WHITELIST;
373     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
374     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
375     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
376     private static final Set<String> SYSTEM_SETTINGS_WHITELIST;
377     static {
378         SECURE_SETTINGS_WHITELIST = new ArraySet<>();
379         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
380         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
381         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
382 
383         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
384         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
385         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
386 
387         GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
388         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
389         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
390         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
391         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
392         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
393         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
394         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
395         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
396 
397         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
398         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
399         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
400         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
401         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
402         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
403 
404         SYSTEM_SETTINGS_WHITELIST = new ArraySet<>();
405         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS);
406         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_BRIGHTNESS_MODE);
407         SYSTEM_SETTINGS_WHITELIST.add(Settings.System.SCREEN_OFF_TIMEOUT);
408     }
409 
410     /**
411      * Keyguard features that when set on a profile affect the profile content or challenge only.
412      * These cannot be set on the managed profile's parent DPM instance
413      */
414     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
415             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
416 
417     /** Keyguard features that are allowed to be set on a managed profile */
418     private static final int PROFILE_KEYGUARD_FEATURES =
419             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
420 
421     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
422 
423     /**
424      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
425      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
426      */
427     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
428 
429     /**
430      * Strings logged with {@link
431      * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}.
432      */
433     private static final String LOG_TAG_PROFILE_OWNER = "profile-owner";
434     private static final String LOG_TAG_DEVICE_OWNER = "device-owner";
435 
436     final Context mContext;
437     final Injector mInjector;
438     final IPackageManager mIPackageManager;
439     final UserManager mUserManager;
440     final UserManagerInternal mUserManagerInternal;
441     final UsageStatsManagerInternal mUsageStatsManagerInternal;
442     final TelephonyManager mTelephonyManager;
443     private final LockPatternUtils mLockPatternUtils;
444     private final DevicePolicyConstants mConstants;
445     private final DeviceAdminServiceController mDeviceAdminServiceController;
446     private final OverlayPackagesProvider mOverlayPackagesProvider;
447 
448     private final DevicePolicyCacheImpl mPolicyCache = new DevicePolicyCacheImpl();
449 
450     /**
451      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
452      * is requested for user u.
453      */
454     private final Set<Pair<String, Integer>> mPackagesToRemove =
455             new ArraySet<Pair<String, Integer>>();
456 
457     final LocalService mLocalService;
458 
459     // Stores and loads state on device and profile owners.
460     @VisibleForTesting
461     final Owners mOwners;
462 
463     private final Binder mToken = new Binder();
464 
465     /**
466      * Whether or not device admin feature is supported. If it isn't return defaults for all
467      * public methods.
468      */
469     final boolean mHasFeature;
470 
471     /**
472      * Whether or not this device is a watch.
473      */
474     final boolean mIsWatch;
475 
476     private final CertificateMonitor mCertificateMonitor;
477     private final SecurityLogMonitor mSecurityLogMonitor;
478 
479     @GuardedBy("getLockObject()")
480     private NetworkLogger mNetworkLogger;
481 
482     private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
483     private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
484 
485     private final SetupContentObserver mSetupContentObserver;
486 
487     private static boolean ENABLE_LOCK_GUARD = Build.IS_ENG
488             || (SystemProperties.getInt("debug.dpm.lock_guard", 0) == 1);
489 
490     interface Stats {
491         int LOCK_GUARD_GUARD = 0;
492 
493         int COUNT = LOCK_GUARD_GUARD + 1;
494     }
495 
496     private final StatLogger mStatLogger = new StatLogger(new String[] {
497             "LockGuard.guard()",
498     });
499 
500     private final Object mLockDoNoUseDirectly = LockGuard.installNewLock(
501             LockGuard.INDEX_DPMS, /* doWtf=*/ true);
502 
getLockObject()503     final Object getLockObject() {
504         if (ENABLE_LOCK_GUARD) {
505             final long start = mStatLogger.getTime();
506             LockGuard.guard(LockGuard.INDEX_DPMS);
507             mStatLogger.logDurationStat(Stats.LOCK_GUARD_GUARD, start);
508         }
509         return mLockDoNoUseDirectly;
510     }
511 
512     /**
513      * Check if the current thread holds the DPMS lock, and if not, do a WTF.
514      *
515      * (Doing this check too much may be costly, so don't call it in a hot path.)
516      */
ensureLocked()517     final void ensureLocked() {
518         if (Thread.holdsLock(mLockDoNoUseDirectly)) {
519             return;
520         }
521         Slog.wtfStack(LOG_TAG, "Not holding DPMS lock.");
522     }
523 
524     @VisibleForTesting
525     final TransferOwnershipMetadataManager mTransferOwnershipMetadataManager;
526 
527     private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
528         @Override
529         public void run() {
530             if(mRemoteBugreportServiceIsActive.get()) {
531                 onBugreportFailed();
532             }
533         }
534     };
535 
536     /** Listens only if mHasFeature == true. */
537     private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
538 
539         @Override
540         public void onReceive(Context context, Intent intent) {
541             if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
542                     && mRemoteBugreportServiceIsActive.get()) {
543                 onBugreportFinished(intent);
544             }
545         }
546     };
547 
548     /** Listens only if mHasFeature == true. */
549     private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
550 
551         @Override
552         public void onReceive(Context context, Intent intent) {
553             String action = intent.getAction();
554             mInjector.getNotificationManager().cancel(LOG_TAG,
555                     RemoteBugreportUtils.NOTIFICATION_ID);
556             if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
557                 onBugreportSharingAccepted();
558             } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
559                 onBugreportSharingDeclined();
560             }
561             mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
562         }
563     };
564 
565     public static final class Lifecycle extends SystemService {
566         private BaseIDevicePolicyManager mService;
567 
Lifecycle(Context context)568         public Lifecycle(Context context) {
569             super(context);
570             String dpmsClassName = context.getResources()
571                     .getString(R.string.config_deviceSpecificDevicePolicyManagerService);
572             if (TextUtils.isEmpty(dpmsClassName)) {
573                 dpmsClassName = DevicePolicyManagerService.class.getName();
574             }
575             try {
576                 Class serviceClass = Class.forName(dpmsClassName);
577                 Constructor constructor = serviceClass.getConstructor(Context.class);
578                 mService = (BaseIDevicePolicyManager) constructor.newInstance(context);
579             } catch (Exception e) {
580                 throw new IllegalStateException(
581                     "Failed to instantiate DevicePolicyManagerService with class name: "
582                     + dpmsClassName, e);
583             }
584         }
585 
586         @Override
onStart()587         public void onStart() {
588             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
589         }
590 
591         @Override
onBootPhase(int phase)592         public void onBootPhase(int phase) {
593             mService.systemReady(phase);
594         }
595 
596         @Override
onStartUser(int userHandle)597         public void onStartUser(int userHandle) {
598             mService.handleStartUser(userHandle);
599         }
600 
601         @Override
onUnlockUser(int userHandle)602         public void onUnlockUser(int userHandle) {
603             mService.handleUnlockUser(userHandle);
604         }
605 
606         @Override
onStopUser(int userHandle)607         public void onStopUser(int userHandle) {
608             mService.handleStopUser(userHandle);
609         }
610     }
611 
612     public static class DevicePolicyData {
613         int mFailedPasswordAttempts = 0;
614         boolean mPasswordValidAtLastCheckpoint = true;
615 
616         int mUserHandle;
617         int mPasswordOwner = -1;
618         long mLastMaximumTimeToLock = -1;
619         boolean mUserSetupComplete = false;
620         boolean mPaired = false;
621         int mUserProvisioningState;
622         int mPermissionPolicy;
623 
624         boolean mDeviceProvisioningConfigApplied = false;
625 
626         final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
627         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
628         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
629 
630         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
631         final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
632 
633         // This is the list of component allowed to start lock task mode.
634         List<String> mLockTaskPackages = new ArrayList<>();
635 
636         // Bitfield of feature flags to be enabled during LockTask mode.
637         // We default on the power button menu, in order to be consistent with pre-P behaviour.
638         int mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS;
639 
640         boolean mStatusBarDisabled = false;
641 
642         ComponentName mRestrictionsProvider;
643 
644         // Map of delegate package to delegation scopes
645         final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>();
646 
647         boolean doNotAskCredentialsOnBoot = false;
648 
649         Set<String> mAffiliationIds = new ArraySet<>();
650 
651         long mLastSecurityLogRetrievalTime = -1;
652 
653         long mLastBugReportRequestTime = -1;
654 
655         long mLastNetworkLogsRetrievalTime = -1;
656 
657         boolean mCurrentInputMethodSet = false;
658 
659         // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead.
660         Set<String> mOwnerInstalledCaCerts = new ArraySet<>();
661 
662         // Used for initialization of users created by createAndManageUser.
663         boolean mAdminBroadcastPending = false;
664         PersistableBundle mInitBundle = null;
665 
666         long mPasswordTokenHandle = 0;
667 
DevicePolicyData(int userHandle)668         public DevicePolicyData(int userHandle) {
669             mUserHandle = userHandle;
670         }
671     }
672 
673     @GuardedBy("getLockObject()")
674     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
675 
676     @GuardedBy("getLockObject()")
677     final SparseArray<PasswordMetrics> mUserPasswordMetrics = new SparseArray<>();
678 
679     final Handler mHandler;
680     final Handler mBackgroundHandler;
681 
682     /** Listens only if mHasFeature == true. */
683     final BroadcastReceiver mReceiver = new BroadcastReceiver() {
684         @Override
685         public void onReceive(Context context, Intent intent) {
686             final String action = intent.getAction();
687             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
688                     getSendingUserId());
689 
690             /*
691              * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(),
692              * however it's too early in the boot process to register with IIpConnectivityMetrics
693              * to listen for events.
694              */
695             if (Intent.ACTION_USER_STARTED.equals(action)
696                     && userHandle == mOwners.getDeviceOwnerUserId()) {
697                 synchronized (getLockObject()) {
698                     if (isNetworkLoggingEnabledInternalLocked()) {
699                         setNetworkLoggingActiveInternal(true);
700                     }
701                 }
702             }
703             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
704                     && userHandle == mOwners.getDeviceOwnerUserId()
705                     && getDeviceOwnerRemoteBugreportUri() != null) {
706                 IntentFilter filterConsent = new IntentFilter();
707                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
708                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
709                 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
710                 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
711                         RemoteBugreportUtils.NOTIFICATION_ID,
712                         RemoteBugreportUtils.buildNotification(mContext,
713                                 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
714                                 UserHandle.ALL);
715             }
716             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
717                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
718                 if (VERBOSE_LOG) {
719                     Slog.v(LOG_TAG, "Sending password expiration notifications for action "
720                             + action + " for user " + userHandle);
721                 }
722                 mHandler.post(new Runnable() {
723                     @Override
724                     public void run() {
725                         handlePasswordExpirationNotification(userHandle);
726                     }
727                 });
728             }
729 
730             if (Intent.ACTION_USER_ADDED.equals(action)) {
731                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle);
732                 synchronized (getLockObject()) {
733                     // It might take a while for the user to become affiliated. Make security
734                     // and network logging unavailable in the meantime.
735                     maybePauseDeviceWideLoggingLocked();
736                 }
737             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
738                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle);
739                 synchronized (getLockObject()) {
740                     // Check whether the user is affiliated, *before* removing its data.
741                     boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle);
742                     removeUserData(userHandle);
743                     if (!isRemovedUserAffiliated) {
744                         // We discard the logs when unaffiliated users are deleted (so that the
745                         // device owner cannot retrieve data about that user after it's gone).
746                         discardDeviceWideLogsLocked();
747                         // Resume logging if all remaining users are affiliated.
748                         maybeResumeDeviceWideLoggingLocked();
749                     }
750                 }
751             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
752                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STARTED, userHandle);
753                 synchronized (getLockObject()) {
754                     maybeSendAdminEnabledBroadcastLocked(userHandle);
755                     // Reset the policy data
756                     mUserData.remove(userHandle);
757                 }
758                 handlePackagesChanged(null /* check all admins */, userHandle);
759             } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
760                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_STOPPED, userHandle);
761             } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
762                 sendDeviceOwnerUserCommand(DeviceAdminReceiver.ACTION_USER_SWITCHED, userHandle);
763             } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
764                 synchronized (getLockObject()) {
765                     maybeSendAdminEnabledBroadcastLocked(userHandle);
766                 }
767             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
768                 handlePackagesChanged(null /* check all admins */, userHandle);
769             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
770                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
771                     && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
772                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
773             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
774                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
775                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
776             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
777                 clearWipeProfileNotification();
778             } else if (Intent.ACTION_DATE_CHANGED.equals(action)
779                     || Intent.ACTION_TIME_CHANGED.equals(action)) {
780                 // Update freeze period record when clock naturally progresses to the next day
781                 // (ACTION_DATE_CHANGED), or when manual clock adjustment is made
782                 // (ACTION_TIME_CHANGED)
783                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
784             }
785 
786         }
787 
788         private void sendDeviceOwnerUserCommand(String action, int userHandle) {
789             synchronized (getLockObject()) {
790                 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
791                 if (deviceOwner != null) {
792                     Bundle extras = new Bundle();
793                     extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
794                     sendAdminCommandLocked(deviceOwner, action, extras, /* result */ null,
795                             /* inForeground */ true);
796                 }
797             }
798         }
799     };
800 
801     protected static class RestrictionsListener implements UserRestrictionsListener {
802         private Context mContext;
803 
RestrictionsListener(Context context)804         public RestrictionsListener(Context context) {
805             mContext = context;
806         }
807 
onUserRestrictionsChanged(int userId, Bundle newRestrictions, Bundle prevRestrictions)808         public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
809                 Bundle prevRestrictions) {
810             final boolean newlyDisallowed =
811                     newRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
812             final boolean previouslyDisallowed =
813                     prevRestrictions.getBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE);
814             final boolean restrictionChanged = (newlyDisallowed != previouslyDisallowed);
815 
816             if (restrictionChanged) {
817                 // Notify ManagedProvisioning to update the built-in cross profile intent filters.
818                 Intent intent = new Intent(
819                         DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
820                 intent.setPackage(getManagedProvisioningPackage(mContext));
821                 intent.putExtra(Intent.EXTRA_USER_ID, userId);
822                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
823                 mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
824             }
825         }
826     }
827 
828     static class ActiveAdmin {
829         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
830         private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
831         private static final String TAG_DISABLE_CAMERA = "disable-camera";
832         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
833         private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
834         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
835                 = "disable-bt-contacts-sharing";
836         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
837         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
838         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
839         private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
840         private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled";
841         private static final String TAG_ACCOUNT_TYPE = "account-type";
842         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
843                 = "permitted-accessiblity-services";
844         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
845         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
846         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
847         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
848         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
849         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
850         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
851         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
852         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
853         private static final String TAG_PERMITTED_IMES = "permitted-imes";
854         private static final String TAG_PERMITTED_NOTIFICATION_LISTENERS =
855                 "permitted-notification-listeners";
856         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
857         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
858         private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
859         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
860         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
861         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
862         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
863         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
864         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
865         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
866         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
867         private static final String ATTR_VALUE = "value";
868         private static final String TAG_PASSWORD_QUALITY = "password-quality";
869         private static final String TAG_POLICIES = "policies";
870         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
871                 "cross-profile-widget-providers";
872         private static final String TAG_PROVIDER = "provider";
873         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
874         private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
875         private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
876         private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS =
877                 "default-enabled-user-restrictions";
878         private static final String TAG_RESTRICTION = "restriction";
879         private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
880         private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
881         private static final String TAG_PARENT_ADMIN = "parent-admin";
882         private static final String TAG_ORGANIZATION_COLOR = "organization-color";
883         private static final String TAG_ORGANIZATION_NAME = "organization-name";
884         private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification";
885         private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications";
886         private static final String TAG_IS_LOGOUT_ENABLED = "is_logout_enabled";
887         private static final String TAG_MANDATORY_BACKUP_TRANSPORT = "mandatory_backup_transport";
888         private static final String TAG_START_USER_SESSION_MESSAGE = "start_user_session_message";
889         private static final String TAG_END_USER_SESSION_MESSAGE = "end_user_session_message";
890         private static final String TAG_METERED_DATA_DISABLED_PACKAGES
891                 = "metered_data_disabled_packages";
892 
893         DeviceAdminInfo info;
894 
895 
896         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
897         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
898 
899         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
900         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
901         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
902         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
903         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
904         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
905         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
906         @NonNull
907         PasswordMetrics minimumPasswordMetrics = new PasswordMetrics(
908                 PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH,
909                 DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE,
910                 DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC,
911                 DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER);
912 
913         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
914         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
915 
916         long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
917 
918         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
919         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
920 
921         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
922         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
923 
924         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
925         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
926 
927         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
928 
929         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
930 
931         boolean encryptionRequested = false;
932         boolean testOnlyAdmin = false;
933         boolean disableCamera = false;
934         boolean disableCallerId = false;
935         boolean disableContactsSearch = false;
936         boolean disableBluetoothContactSharing = true;
937         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
938         boolean requireAutoTime = false; // Can only be set by a device owner.
939         boolean forceEphemeralUsers = false; // Can only be set by a device owner.
940         boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner.
941         boolean isLogoutEnabled = false; // Can only be set by a device owner.
942 
943         // one notification after enabling + one more after reboots
944         static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2;
945         int numNetworkLoggingNotifications = 0;
946         long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch
947 
948         ActiveAdmin parentAdmin;
949         final boolean isParent;
950 
951         static class TrustAgentInfo {
952             public PersistableBundle options;
TrustAgentInfo(PersistableBundle bundle)953             TrustAgentInfo(PersistableBundle bundle) {
954                 options = bundle;
955             }
956         }
957 
958         // The list of packages which are not allowed to use metered data.
959         List<String> meteredDisabledPackages;
960 
961         final Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
962 
963         // The list of permitted accessibility services package namesas set by a profile
964         // or device owner. Null means all accessibility services are allowed, empty means
965         // none except system services are allowed.
966         List<String> permittedAccessiblityServices;
967 
968         // The list of permitted input methods package names as set by a profile or device owner.
969         // Null means all input methods are allowed, empty means none except system imes are
970         // allowed.
971         List<String> permittedInputMethods;
972 
973         // The list of packages allowed to use a NotificationListenerService to receive events for
974         // notifications from this user. Null means that all packages are allowed. Empty list means
975         // that only packages from the system are allowed.
976         List<String> permittedNotificationListeners;
977 
978         // List of package names to keep cached.
979         List<String> keepUninstalledPackages;
980 
981         // TODO: review implementation decisions with frameworks team
982         boolean specifiesGlobalProxy = false;
983         String globalProxySpec = null;
984         String globalProxyExclusionList = null;
985 
986         ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
987 
988         List<String> crossProfileWidgetProviders;
989 
990         Bundle userRestrictions;
991 
992         // User restrictions that have already been enabled by default for this admin (either when
993         // setting the device or profile owner, or during a system update if one of those "enabled
994         // by default" restrictions is newly added).
995         final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>();
996 
997         // Support text provided by the admin to display to the user.
998         CharSequence shortSupportMessage = null;
999         CharSequence longSupportMessage = null;
1000 
1001         // Background color of confirm credentials screen. Default: teal.
1002         static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
1003         int organizationColor = DEF_ORGANIZATION_COLOR;
1004 
1005         // Default title of confirm credentials screen
1006         String organizationName = null;
1007 
1008         // The component name of the backup transport which has to be used if backups are mandatory
1009         // or null if backups are not mandatory.
1010         ComponentName mandatoryBackupTransport = null;
1011 
1012         // Message for user switcher
1013         String startUserSessionMessage = null;
1014         String endUserSessionMessage = null;
1015 
ActiveAdmin(DeviceAdminInfo _info, boolean parent)1016         ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
1017             info = _info;
1018             isParent = parent;
1019         }
1020 
getParentActiveAdmin()1021         ActiveAdmin getParentActiveAdmin() {
1022             Preconditions.checkState(!isParent);
1023 
1024             if (parentAdmin == null) {
1025                 parentAdmin = new ActiveAdmin(info, /* parent */ true);
1026             }
1027             return parentAdmin;
1028         }
1029 
hasParentActiveAdmin()1030         boolean hasParentActiveAdmin() {
1031             return parentAdmin != null;
1032         }
1033 
getUid()1034         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
1035 
getUserHandle()1036         public UserHandle getUserHandle() {
1037             return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
1038         }
1039 
writeToXml(XmlSerializer out)1040         void writeToXml(XmlSerializer out)
1041                 throws IllegalArgumentException, IllegalStateException, IOException {
1042             out.startTag(null, TAG_POLICIES);
1043             info.writePoliciesToXml(out);
1044             out.endTag(null, TAG_POLICIES);
1045             if (minimumPasswordMetrics.quality != PASSWORD_QUALITY_UNSPECIFIED) {
1046                 out.startTag(null, TAG_PASSWORD_QUALITY);
1047                 out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality));
1048                 out.endTag(null, TAG_PASSWORD_QUALITY);
1049                 if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) {
1050                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
1051                     out.attribute(
1052                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length));
1053                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
1054                 }
1055                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
1056                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1057                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
1058                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
1059                 }
1060                 if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
1061                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1062                     out.attribute(
1063                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase));
1064                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
1065                 }
1066                 if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
1067                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1068                     out.attribute(
1069                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase));
1070                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
1071                 }
1072                 if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) {
1073                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
1074                     out.attribute(
1075                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters));
1076                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
1077                 }
1078                 if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
1079                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
1080                     out.attribute(
1081                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric));
1082                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
1083                 }
1084                 if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
1085                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1086                     out.attribute(
1087                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols));
1088                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
1089                 }
1090                 if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
1091                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
1092                     out.attribute(
1093                             null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter));
1094                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
1095                 }
1096             }
1097             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
1098                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
1099                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
1100                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
1101             }
1102             if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
1103                 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1104                 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
1105                 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
1106             }
1107             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
1108                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1109                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
1110                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
1111             }
1112             if (specifiesGlobalProxy) {
1113                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1114                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
1115                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
1116                 if (globalProxySpec != null) {
1117                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
1118                     out.attribute(null, ATTR_VALUE, globalProxySpec);
1119                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
1120                 }
1121                 if (globalProxyExclusionList != null) {
1122                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1123                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
1124                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
1125                 }
1126             }
1127             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
1128                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1129                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
1130                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
1131             }
1132             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
1133                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1134                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
1135                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
1136             }
1137             if (encryptionRequested) {
1138                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
1139                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
1140                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
1141             }
1142             if (testOnlyAdmin) {
1143                 out.startTag(null, TAG_TEST_ONLY_ADMIN);
1144                 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
1145                 out.endTag(null, TAG_TEST_ONLY_ADMIN);
1146             }
1147             if (disableCamera) {
1148                 out.startTag(null, TAG_DISABLE_CAMERA);
1149                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
1150                 out.endTag(null, TAG_DISABLE_CAMERA);
1151             }
1152             if (disableCallerId) {
1153                 out.startTag(null, TAG_DISABLE_CALLER_ID);
1154                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
1155                 out.endTag(null, TAG_DISABLE_CALLER_ID);
1156             }
1157             if (disableContactsSearch) {
1158                 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1159                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
1160                 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
1161             }
1162             if (!disableBluetoothContactSharing) {
1163                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1164                 out.attribute(null, ATTR_VALUE,
1165                         Boolean.toString(disableBluetoothContactSharing));
1166                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
1167             }
1168             if (disableScreenCapture) {
1169                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1170                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
1171                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
1172             }
1173             if (requireAutoTime) {
1174                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
1175                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
1176                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
1177             }
1178             if (forceEphemeralUsers) {
1179                 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
1180                 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
1181                 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
1182             }
1183             if (isNetworkLoggingEnabled) {
1184                 out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1185                 out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled));
1186                 out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS,
1187                         Integer.toString(numNetworkLoggingNotifications));
1188                 out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION,
1189                         Long.toString(lastNetworkLoggingNotificationTimeMs));
1190                 out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED);
1191             }
1192             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
1193                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1194                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
1195                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
1196             }
1197             if (!accountTypesWithManagementDisabled.isEmpty()) {
1198                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
1199                 writeAttributeValuesToXml(
1200                         out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1201                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
1202             }
1203             if (!trustAgentInfos.isEmpty()) {
1204                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
1205                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1206                 for (Entry<String, TrustAgentInfo> entry : set) {
1207                     TrustAgentInfo trustAgentInfo = entry.getValue();
1208                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
1209                     out.attribute(null, ATTR_VALUE, entry.getKey());
1210                     if (trustAgentInfo.options != null) {
1211                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1212                         try {
1213                             trustAgentInfo.options.saveToXml(out);
1214                         } catch (XmlPullParserException e) {
1215                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
1216                         }
1217                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
1218                     }
1219                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
1220                 }
1221                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
1222             }
1223             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
1224                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1225                 writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders);
1226                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
1227             }
1228             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
1229                     permittedAccessiblityServices);
1230             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
1231             writePackageListToXml(out, TAG_PERMITTED_NOTIFICATION_LISTENERS,
1232                     permittedNotificationListeners);
1233             writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
1234             writePackageListToXml(out, TAG_METERED_DATA_DISABLED_PACKAGES, meteredDisabledPackages);
1235             if (hasUserRestrictions()) {
1236                 UserRestrictionsUtils.writeRestrictions(
1237                         out, userRestrictions, TAG_USER_RESTRICTIONS);
1238             }
1239             if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) {
1240                 out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1241                 writeAttributeValuesToXml(
1242                         out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1243                 out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS);
1244             }
1245             if (!TextUtils.isEmpty(shortSupportMessage)) {
1246                 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1247                 out.text(shortSupportMessage.toString());
1248                 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
1249             }
1250             if (!TextUtils.isEmpty(longSupportMessage)) {
1251                 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
1252                 out.text(longSupportMessage.toString());
1253                 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
1254             }
1255             if (parentAdmin != null) {
1256                 out.startTag(null, TAG_PARENT_ADMIN);
1257                 parentAdmin.writeToXml(out);
1258                 out.endTag(null, TAG_PARENT_ADMIN);
1259             }
1260             if (organizationColor != DEF_ORGANIZATION_COLOR) {
1261                 out.startTag(null, TAG_ORGANIZATION_COLOR);
1262                 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
1263                 out.endTag(null, TAG_ORGANIZATION_COLOR);
1264             }
1265             if (organizationName != null) {
1266                 out.startTag(null, TAG_ORGANIZATION_NAME);
1267                 out.text(organizationName);
1268                 out.endTag(null, TAG_ORGANIZATION_NAME);
1269             }
1270             if (isLogoutEnabled) {
1271                 out.startTag(null, TAG_IS_LOGOUT_ENABLED);
1272                 out.attribute(null, ATTR_VALUE, Boolean.toString(isLogoutEnabled));
1273                 out.endTag(null, TAG_IS_LOGOUT_ENABLED);
1274             }
1275             if (mandatoryBackupTransport != null) {
1276                 out.startTag(null, TAG_MANDATORY_BACKUP_TRANSPORT);
1277                 out.attribute(null, ATTR_VALUE, mandatoryBackupTransport.flattenToString());
1278                 out.endTag(null, TAG_MANDATORY_BACKUP_TRANSPORT);
1279             }
1280             if (startUserSessionMessage != null) {
1281                 out.startTag(null, TAG_START_USER_SESSION_MESSAGE);
1282                 out.text(startUserSessionMessage);
1283                 out.endTag(null, TAG_START_USER_SESSION_MESSAGE);
1284             }
1285             if (endUserSessionMessage != null) {
1286                 out.startTag(null, TAG_END_USER_SESSION_MESSAGE);
1287                 out.text(endUserSessionMessage);
1288                 out.endTag(null, TAG_END_USER_SESSION_MESSAGE);
1289             }
1290         }
1291 
writePackageListToXml(XmlSerializer out, String outerTag, List<String> packageList)1292         void writePackageListToXml(XmlSerializer out, String outerTag,
1293                 List<String> packageList)
1294                 throws IllegalArgumentException, IllegalStateException, IOException {
1295             if (packageList == null) {
1296                 return;
1297             }
1298 
1299             out.startTag(null, outerTag);
1300             writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList);
1301             out.endTag(null, outerTag);
1302         }
1303 
writeAttributeValuesToXml(XmlSerializer out, String tag, @NonNull Collection<String> values)1304         void writeAttributeValuesToXml(XmlSerializer out, String tag,
1305                 @NonNull Collection<String> values) throws IOException {
1306             for (String value : values) {
1307                 out.startTag(null, tag);
1308                 out.attribute(null, ATTR_VALUE, value);
1309                 out.endTag(null, tag);
1310             }
1311         }
1312 
readFromXml(XmlPullParser parser)1313         void readFromXml(XmlPullParser parser)
1314                 throws XmlPullParserException, IOException {
1315             int outerDepth = parser.getDepth();
1316             int type;
1317             while ((type=parser.next()) != END_DOCUMENT
1318                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
1319                 if (type == END_TAG || type == TEXT) {
1320                     continue;
1321                 }
1322                 String tag = parser.getName();
1323                 if (TAG_POLICIES.equals(tag)) {
1324                     info.readPoliciesFromXml(parser);
1325                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
1326                     minimumPasswordMetrics.quality = Integer.parseInt(
1327                             parser.getAttributeValue(null, ATTR_VALUE));
1328                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
1329                     minimumPasswordMetrics.length = Integer.parseInt(
1330                             parser.getAttributeValue(null, ATTR_VALUE));
1331                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
1332                     passwordHistoryLength = Integer.parseInt(
1333                             parser.getAttributeValue(null, ATTR_VALUE));
1334                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
1335                     minimumPasswordMetrics.upperCase = Integer.parseInt(
1336                             parser.getAttributeValue(null, ATTR_VALUE));
1337                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
1338                     minimumPasswordMetrics.lowerCase = Integer.parseInt(
1339                             parser.getAttributeValue(null, ATTR_VALUE));
1340                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
1341                     minimumPasswordMetrics.letters = Integer.parseInt(
1342                             parser.getAttributeValue(null, ATTR_VALUE));
1343                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
1344                     minimumPasswordMetrics.numeric = Integer.parseInt(
1345                             parser.getAttributeValue(null, ATTR_VALUE));
1346                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
1347                     minimumPasswordMetrics.symbols = Integer.parseInt(
1348                             parser.getAttributeValue(null, ATTR_VALUE));
1349                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
1350                     minimumPasswordMetrics.nonLetter = Integer.parseInt(
1351                             parser.getAttributeValue(null, ATTR_VALUE));
1352                 }else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
1353                     maximumTimeToUnlock = Long.parseLong(
1354                             parser.getAttributeValue(null, ATTR_VALUE));
1355                 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
1356                     strongAuthUnlockTimeout = Long.parseLong(
1357                             parser.getAttributeValue(null, ATTR_VALUE));
1358                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
1359                     maximumFailedPasswordsForWipe = Integer.parseInt(
1360                             parser.getAttributeValue(null, ATTR_VALUE));
1361                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
1362                     specifiesGlobalProxy = Boolean.parseBoolean(
1363                             parser.getAttributeValue(null, ATTR_VALUE));
1364                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1365                     globalProxySpec =
1366                         parser.getAttributeValue(null, ATTR_VALUE);
1367                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1368                     globalProxyExclusionList =
1369                         parser.getAttributeValue(null, ATTR_VALUE);
1370                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1371                     passwordExpirationTimeout = Long.parseLong(
1372                             parser.getAttributeValue(null, ATTR_VALUE));
1373                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1374                     passwordExpirationDate = Long.parseLong(
1375                             parser.getAttributeValue(null, ATTR_VALUE));
1376                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1377                     encryptionRequested = Boolean.parseBoolean(
1378                             parser.getAttributeValue(null, ATTR_VALUE));
1379                 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1380                     testOnlyAdmin = Boolean.parseBoolean(
1381                             parser.getAttributeValue(null, ATTR_VALUE));
1382                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1383                     disableCamera = Boolean.parseBoolean(
1384                             parser.getAttributeValue(null, ATTR_VALUE));
1385                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1386                     disableCallerId = Boolean.parseBoolean(
1387                             parser.getAttributeValue(null, ATTR_VALUE));
1388                 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1389                     disableContactsSearch = Boolean.parseBoolean(
1390                             parser.getAttributeValue(null, ATTR_VALUE));
1391                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1392                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
1393                             .getAttributeValue(null, ATTR_VALUE));
1394                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1395                     disableScreenCapture = Boolean.parseBoolean(
1396                             parser.getAttributeValue(null, ATTR_VALUE));
1397                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1398                     requireAutoTime = Boolean.parseBoolean(
1399                             parser.getAttributeValue(null, ATTR_VALUE));
1400                 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1401                     forceEphemeralUsers = Boolean.parseBoolean(
1402                             parser.getAttributeValue(null, ATTR_VALUE));
1403                 } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) {
1404                     isNetworkLoggingEnabled = Boolean.parseBoolean(
1405                             parser.getAttributeValue(null, ATTR_VALUE));
1406                     lastNetworkLoggingNotificationTimeMs = Long.parseLong(
1407                             parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION));
1408                     numNetworkLoggingNotifications = Integer.parseInt(
1409                             parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS));
1410                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1411                     disabledKeyguardFeatures = Integer.parseInt(
1412                             parser.getAttributeValue(null, ATTR_VALUE));
1413                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1414                     readAttributeValues(
1415                             parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled);
1416                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1417                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1418                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1419                     crossProfileWidgetProviders = new ArrayList<>();
1420                     readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders);
1421                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1422                     permittedAccessiblityServices = readPackageList(parser, tag);
1423                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1424                     permittedInputMethods = readPackageList(parser, tag);
1425                 } else if (TAG_PERMITTED_NOTIFICATION_LISTENERS.equals(tag)) {
1426                     permittedNotificationListeners = readPackageList(parser, tag);
1427                 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1428                     keepUninstalledPackages = readPackageList(parser, tag);
1429                 } else if (TAG_METERED_DATA_DISABLED_PACKAGES.equals(tag)) {
1430                     meteredDisabledPackages = readPackageList(parser, tag);
1431                 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1432                     userRestrictions = UserRestrictionsUtils.readRestrictions(parser);
1433                 } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) {
1434                     readAttributeValues(
1435                             parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet);
1436                 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1437                     type = parser.next();
1438                     if (type == XmlPullParser.TEXT) {
1439                         shortSupportMessage = parser.getText();
1440                     } else {
1441                         Log.w(LOG_TAG, "Missing text when loading short support message");
1442                     }
1443                 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1444                     type = parser.next();
1445                     if (type == XmlPullParser.TEXT) {
1446                         longSupportMessage = parser.getText();
1447                     } else {
1448                         Log.w(LOG_TAG, "Missing text when loading long support message");
1449                     }
1450                 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1451                     Preconditions.checkState(!isParent);
1452 
1453                     parentAdmin = new ActiveAdmin(info, /* parent */ true);
1454                     parentAdmin.readFromXml(parser);
1455                 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1456                     organizationColor = Integer.parseInt(
1457                             parser.getAttributeValue(null, ATTR_VALUE));
1458                 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1459                     type = parser.next();
1460                     if (type == XmlPullParser.TEXT) {
1461                         organizationName = parser.getText();
1462                     } else {
1463                         Log.w(LOG_TAG, "Missing text when loading organization name");
1464                     }
1465                 } else if (TAG_IS_LOGOUT_ENABLED.equals(tag)) {
1466                     isLogoutEnabled = Boolean.parseBoolean(
1467                             parser.getAttributeValue(null, ATTR_VALUE));
1468                 } else if (TAG_MANDATORY_BACKUP_TRANSPORT.equals(tag)) {
1469                     mandatoryBackupTransport = ComponentName.unflattenFromString(
1470                             parser.getAttributeValue(null, ATTR_VALUE));
1471                 } else if (TAG_START_USER_SESSION_MESSAGE.equals(tag)) {
1472                     type = parser.next();
1473                     if (type == XmlPullParser.TEXT) {
1474                         startUserSessionMessage = parser.getText();
1475                     } else {
1476                         Log.w(LOG_TAG, "Missing text when loading start session message");
1477                     }
1478                 } else if (TAG_END_USER_SESSION_MESSAGE.equals(tag)) {
1479                     type = parser.next();
1480                     if (type == XmlPullParser.TEXT) {
1481                         endUserSessionMessage = parser.getText();
1482                     } else {
1483                         Log.w(LOG_TAG, "Missing text when loading end session message");
1484                     }
1485                 } else {
1486                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1487                     XmlUtils.skipCurrentTag(parser);
1488                 }
1489             }
1490         }
1491 
readPackageList(XmlPullParser parser, String tag)1492         private List<String> readPackageList(XmlPullParser parser,
1493                 String tag) throws XmlPullParserException, IOException {
1494             List<String> result = new ArrayList<String>();
1495             int outerDepth = parser.getDepth();
1496             int outerType;
1497             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1498                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1499                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1500                     continue;
1501                 }
1502                 String outerTag = parser.getName();
1503                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1504                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1505                     if (packageName != null) {
1506                         result.add(packageName);
1507                     } else {
1508                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1509                     }
1510                 } else {
1511                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1512                 }
1513             }
1514             return result;
1515         }
1516 
readAttributeValues( XmlPullParser parser, String tag, Collection<String> result)1517         private void readAttributeValues(
1518                 XmlPullParser parser, String tag, Collection<String> result)
1519                 throws XmlPullParserException, IOException {
1520             result.clear();
1521             int outerDepthDAM = parser.getDepth();
1522             int typeDAM;
1523             while ((typeDAM=parser.next()) != END_DOCUMENT
1524                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1525                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1526                     continue;
1527                 }
1528                 String tagDAM = parser.getName();
1529                 if (tag.equals(tagDAM)) {
1530                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
1531                 } else {
1532                     Slog.e(LOG_TAG, "Expected tag " + tag +  " but found " + tagDAM);
1533                 }
1534             }
1535         }
1536 
getAllTrustAgentInfos( XmlPullParser parser, String tag)1537         private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1538                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1539             int outerDepthDAM = parser.getDepth();
1540             int typeDAM;
1541             final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1542             while ((typeDAM=parser.next()) != END_DOCUMENT
1543                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1544                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1545                     continue;
1546                 }
1547                 String tagDAM = parser.getName();
1548                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1549                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
1550                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1551                     result.put(component, trustAgentInfo);
1552                 } else {
1553                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1554                 }
1555             }
1556             return result;
1557         }
1558 
getTrustAgentInfo(XmlPullParser parser, String tag)1559         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1560                 throws XmlPullParserException, IOException  {
1561             int outerDepthDAM = parser.getDepth();
1562             int typeDAM;
1563             TrustAgentInfo result = new TrustAgentInfo(null);
1564             while ((typeDAM=parser.next()) != END_DOCUMENT
1565                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1566                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1567                     continue;
1568                 }
1569                 String tagDAM = parser.getName();
1570                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1571                     result.options = PersistableBundle.restoreFromXml(parser);
1572                 } else {
1573                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1574                 }
1575             }
1576             return result;
1577         }
1578 
hasUserRestrictions()1579         boolean hasUserRestrictions() {
1580             return userRestrictions != null && userRestrictions.size() > 0;
1581         }
1582 
ensureUserRestrictions()1583         Bundle ensureUserRestrictions() {
1584             if (userRestrictions == null) {
1585                 userRestrictions = new Bundle();
1586             }
1587             return userRestrictions;
1588         }
1589 
transfer(DeviceAdminInfo deviceAdminInfo)1590         public void transfer(DeviceAdminInfo deviceAdminInfo) {
1591             if (hasParentActiveAdmin()) {
1592                 parentAdmin.info = deviceAdminInfo;
1593             }
1594             info = deviceAdminInfo;
1595         }
1596 
dump(String prefix, PrintWriter pw)1597         void dump(String prefix, PrintWriter pw) {
1598             pw.print(prefix); pw.print("uid="); pw.println(getUid());
1599             pw.print(prefix); pw.print("testOnlyAdmin=");
1600             pw.println(testOnlyAdmin);
1601             pw.print(prefix); pw.println("policies:");
1602             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1603             if (pols != null) {
1604                 for (int i=0; i<pols.size(); i++) {
1605                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1606                 }
1607             }
1608             pw.print(prefix); pw.print("passwordQuality=0x");
1609                     pw.println(Integer.toHexString(minimumPasswordMetrics.quality));
1610             pw.print(prefix); pw.print("minimumPasswordLength=");
1611                     pw.println(minimumPasswordMetrics.length);
1612             pw.print(prefix); pw.print("passwordHistoryLength=");
1613                     pw.println(passwordHistoryLength);
1614             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1615                     pw.println(minimumPasswordMetrics.upperCase);
1616             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1617                     pw.println(minimumPasswordMetrics.lowerCase);
1618             pw.print(prefix); pw.print("minimumPasswordLetters=");
1619                     pw.println(minimumPasswordMetrics.letters);
1620             pw.print(prefix); pw.print("minimumPasswordNumeric=");
1621                     pw.println(minimumPasswordMetrics.numeric);
1622             pw.print(prefix); pw.print("minimumPasswordSymbols=");
1623                     pw.println(minimumPasswordMetrics.symbols);
1624             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1625                     pw.println(minimumPasswordMetrics.nonLetter);
1626             pw.print(prefix); pw.print("maximumTimeToUnlock=");
1627                     pw.println(maximumTimeToUnlock);
1628             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1629                     pw.println(strongAuthUnlockTimeout);
1630             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1631                     pw.println(maximumFailedPasswordsForWipe);
1632             pw.print(prefix); pw.print("specifiesGlobalProxy=");
1633                     pw.println(specifiesGlobalProxy);
1634             pw.print(prefix); pw.print("passwordExpirationTimeout=");
1635                     pw.println(passwordExpirationTimeout);
1636             pw.print(prefix); pw.print("passwordExpirationDate=");
1637                     pw.println(passwordExpirationDate);
1638             if (globalProxySpec != null) {
1639                 pw.print(prefix); pw.print("globalProxySpec=");
1640                         pw.println(globalProxySpec);
1641             }
1642             if (globalProxyExclusionList != null) {
1643                 pw.print(prefix); pw.print("globalProxyEclusionList=");
1644                         pw.println(globalProxyExclusionList);
1645             }
1646             pw.print(prefix); pw.print("encryptionRequested=");
1647                     pw.println(encryptionRequested);
1648             pw.print(prefix); pw.print("disableCamera=");
1649                     pw.println(disableCamera);
1650             pw.print(prefix); pw.print("disableCallerId=");
1651                     pw.println(disableCallerId);
1652             pw.print(prefix); pw.print("disableContactsSearch=");
1653                     pw.println(disableContactsSearch);
1654             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1655                     pw.println(disableBluetoothContactSharing);
1656             pw.print(prefix); pw.print("disableScreenCapture=");
1657                     pw.println(disableScreenCapture);
1658             pw.print(prefix); pw.print("requireAutoTime=");
1659                     pw.println(requireAutoTime);
1660             pw.print(prefix); pw.print("forceEphemeralUsers=");
1661                     pw.println(forceEphemeralUsers);
1662             pw.print(prefix); pw.print("isNetworkLoggingEnabled=");
1663                     pw.println(isNetworkLoggingEnabled);
1664             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1665                     pw.println(disabledKeyguardFeatures);
1666             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1667                     pw.println(crossProfileWidgetProviders);
1668             if (permittedAccessiblityServices != null) {
1669                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1670                     pw.println(permittedAccessiblityServices);
1671             }
1672             if (permittedInputMethods != null) {
1673                 pw.print(prefix); pw.print("permittedInputMethods=");
1674                     pw.println(permittedInputMethods);
1675             }
1676             if (permittedNotificationListeners != null) {
1677                 pw.print(prefix); pw.print("permittedNotificationListeners=");
1678                 pw.println(permittedNotificationListeners);
1679             }
1680             if (keepUninstalledPackages != null) {
1681                 pw.print(prefix); pw.print("keepUninstalledPackages=");
1682                     pw.println(keepUninstalledPackages);
1683             }
1684             pw.print(prefix); pw.print("organizationColor=");
1685                     pw.println(organizationColor);
1686             if (organizationName != null) {
1687                 pw.print(prefix); pw.print("organizationName=");
1688                     pw.println(organizationName);
1689             }
1690             pw.print(prefix); pw.println("userRestrictions:");
1691             UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1692             pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet=");
1693                     pw.println(defaultEnabledRestrictionsAlreadySet);
1694             pw.print(prefix); pw.print("isParent=");
1695                     pw.println(isParent);
1696             if (parentAdmin != null) {
1697                 pw.print(prefix);  pw.println("parentAdmin:");
1698                 parentAdmin.dump(prefix + "  ", pw);
1699             }
1700         }
1701     }
1702 
handlePackagesChanged(@ullable String packageName, int userHandle)1703     private void handlePackagesChanged(@Nullable String packageName, int userHandle) {
1704         boolean removedAdmin = false;
1705         if (VERBOSE_LOG) {
1706             Slog.d(LOG_TAG, "Handling package changes package " + packageName
1707                     + " for user " + userHandle);
1708         }
1709         DevicePolicyData policy = getUserData(userHandle);
1710         synchronized (getLockObject()) {
1711             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1712                 ActiveAdmin aa = policy.mAdminList.get(i);
1713                 try {
1714                     // If we're checking all packages or if the specific one we're checking matches,
1715                     // then check if the package and receiver still exist.
1716                     final String adminPackage = aa.info.getPackageName();
1717                     if (packageName == null || packageName.equals(adminPackage)) {
1718                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1719                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1720                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
1721                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1722                                 userHandle) == null) {
1723                             removedAdmin = true;
1724                             policy.mAdminList.remove(i);
1725                             policy.mAdminMap.remove(aa.info.getComponent());
1726                             pushActiveAdminPackagesLocked(userHandle);
1727                             pushMeteredDisabledPackagesLocked(userHandle);
1728                         }
1729                     }
1730                 } catch (RemoteException re) {
1731                     // Shouldn't happen.
1732                 }
1733             }
1734             if (removedAdmin) {
1735                 validatePasswordOwnerLocked(policy);
1736             }
1737 
1738             boolean removedDelegate = false;
1739 
1740             // Check if a delegate was removed.
1741             for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) {
1742                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
1743                 if (isRemovedPackage(packageName, delegatePackage, userHandle)) {
1744                     policy.mDelegationMap.removeAt(i);
1745                     removedDelegate = true;
1746                 }
1747             }
1748 
1749             // If it's an owner package, we may need to refresh the bound connection.
1750             final ComponentName owner = getOwnerComponent(userHandle);
1751             if ((packageName != null) && (owner != null)
1752                     && (owner.getPackageName().equals(packageName))) {
1753                 startOwnerService(userHandle, "package-broadcast");
1754             }
1755 
1756             // Persist updates if the removed package was an admin or delegate.
1757             if (removedAdmin || removedDelegate) {
1758                 saveSettingsLocked(policy.mUserHandle);
1759             }
1760         }
1761         if (removedAdmin) {
1762             // The removed admin might have disabled camera, so update user restrictions.
1763             pushUserRestrictions(userHandle);
1764         }
1765     }
1766 
isRemovedPackage(String changedPackage, String targetPackage, int userHandle)1767     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1768         try {
1769             return targetPackage != null
1770                     && (changedPackage == null || changedPackage.equals(targetPackage))
1771                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1772         } catch (RemoteException e) {
1773             // Shouldn't happen
1774         }
1775 
1776         return false;
1777     }
1778 
1779     /**
1780      * Unit test will subclass it to inject mocks.
1781      */
1782     @VisibleForTesting
1783     static class Injector {
1784 
1785         public final Context mContext;
1786 
Injector(Context context)1787         Injector(Context context) {
1788             mContext = context;
1789         }
1790 
hasFeature()1791         public boolean hasFeature() {
1792             return getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1793         }
1794 
createContextAsUser(UserHandle user)1795         Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException {
1796             final String packageName = mContext.getPackageName();
1797             return mContext.createPackageContextAsUser(packageName, 0, user);
1798         }
1799 
getResources()1800         Resources getResources() {
1801             return mContext.getResources();
1802         }
1803 
newOwners()1804         Owners newOwners() {
1805             return new Owners(getUserManager(), getUserManagerInternal(),
1806                     getPackageManagerInternal());
1807         }
1808 
getUserManager()1809         UserManager getUserManager() {
1810             return UserManager.get(mContext);
1811         }
1812 
getUserManagerInternal()1813         UserManagerInternal getUserManagerInternal() {
1814             return LocalServices.getService(UserManagerInternal.class);
1815         }
1816 
getPackageManagerInternal()1817         PackageManagerInternal getPackageManagerInternal() {
1818             return LocalServices.getService(PackageManagerInternal.class);
1819         }
1820 
getUsageStatsManagerInternal()1821         UsageStatsManagerInternal getUsageStatsManagerInternal() {
1822             return LocalServices.getService(UsageStatsManagerInternal.class);
1823         }
1824 
getNetworkPolicyManagerInternal()1825         NetworkPolicyManagerInternal getNetworkPolicyManagerInternal() {
1826             return LocalServices.getService(NetworkPolicyManagerInternal.class);
1827         }
1828 
getNotificationManager()1829         NotificationManager getNotificationManager() {
1830             return mContext.getSystemService(NotificationManager.class);
1831         }
1832 
getIIpConnectivityMetrics()1833         IIpConnectivityMetrics getIIpConnectivityMetrics() {
1834             return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface(
1835                 ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
1836         }
1837 
getPackageManager()1838         PackageManager getPackageManager() {
1839             return mContext.getPackageManager();
1840         }
1841 
getPowerManagerInternal()1842         PowerManagerInternal getPowerManagerInternal() {
1843             return LocalServices.getService(PowerManagerInternal.class);
1844         }
1845 
getTelephonyManager()1846         TelephonyManager getTelephonyManager() {
1847             return TelephonyManager.from(mContext);
1848         }
1849 
getTrustManager()1850         TrustManager getTrustManager() {
1851             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1852         }
1853 
getAlarmManager()1854         AlarmManager getAlarmManager() {
1855             return (AlarmManager) mContext.getSystemService(AlarmManager.class);
1856         }
1857 
getIWindowManager()1858         IWindowManager getIWindowManager() {
1859             return IWindowManager.Stub
1860                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1861         }
1862 
getIActivityManager()1863         IActivityManager getIActivityManager() {
1864             return ActivityManager.getService();
1865         }
1866 
getActivityManagerInternal()1867         ActivityManagerInternal getActivityManagerInternal() {
1868             return LocalServices.getService(ActivityManagerInternal.class);
1869         }
1870 
getIPackageManager()1871         IPackageManager getIPackageManager() {
1872             return AppGlobals.getPackageManager();
1873         }
1874 
getIBackupManager()1875         IBackupManager getIBackupManager() {
1876             return IBackupManager.Stub.asInterface(
1877                     ServiceManager.getService(Context.BACKUP_SERVICE));
1878         }
1879 
getIAudioService()1880         IAudioService getIAudioService() {
1881             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1882         }
1883 
isBuildDebuggable()1884         boolean isBuildDebuggable() {
1885             return Build.IS_DEBUGGABLE;
1886         }
1887 
newLockPatternUtils()1888         LockPatternUtils newLockPatternUtils() {
1889             return new LockPatternUtils(mContext);
1890         }
1891 
storageManagerIsFileBasedEncryptionEnabled()1892         boolean storageManagerIsFileBasedEncryptionEnabled() {
1893             return StorageManager.isFileEncryptedNativeOnly();
1894         }
1895 
storageManagerIsNonDefaultBlockEncrypted()1896         boolean storageManagerIsNonDefaultBlockEncrypted() {
1897             long identity = Binder.clearCallingIdentity();
1898             try {
1899                 return StorageManager.isNonDefaultBlockEncrypted();
1900             } finally {
1901                 Binder.restoreCallingIdentity(identity);
1902             }
1903         }
1904 
storageManagerIsEncrypted()1905         boolean storageManagerIsEncrypted() {
1906             return StorageManager.isEncrypted();
1907         }
1908 
storageManagerIsEncryptable()1909         boolean storageManagerIsEncryptable() {
1910             return StorageManager.isEncryptable();
1911         }
1912 
getMyLooper()1913         Looper getMyLooper() {
1914             return Looper.myLooper();
1915         }
1916 
getWifiManager()1917         WifiManager getWifiManager() {
1918             return mContext.getSystemService(WifiManager.class);
1919         }
1920 
binderClearCallingIdentity()1921         long binderClearCallingIdentity() {
1922             return Binder.clearCallingIdentity();
1923         }
1924 
binderRestoreCallingIdentity(long token)1925         void binderRestoreCallingIdentity(long token) {
1926             Binder.restoreCallingIdentity(token);
1927         }
1928 
binderGetCallingUid()1929         int binderGetCallingUid() {
1930             return Binder.getCallingUid();
1931         }
1932 
binderGetCallingPid()1933         int binderGetCallingPid() {
1934             return Binder.getCallingPid();
1935         }
1936 
binderGetCallingUserHandle()1937         UserHandle binderGetCallingUserHandle() {
1938             return Binder.getCallingUserHandle();
1939         }
1940 
binderIsCallingUidMyUid()1941         boolean binderIsCallingUidMyUid() {
1942             return getCallingUid() == Process.myUid();
1943         }
1944 
binderWithCleanCallingIdentity(@onNull ThrowingRunnable action)1945         void binderWithCleanCallingIdentity(@NonNull ThrowingRunnable action) {
1946              Binder.withCleanCallingIdentity(action);
1947         }
1948 
userHandleGetCallingUserId()1949         final int userHandleGetCallingUserId() {
1950             return UserHandle.getUserId(binderGetCallingUid());
1951         }
1952 
environmentGetUserSystemDirectory(int userId)1953         File environmentGetUserSystemDirectory(int userId) {
1954             return Environment.getUserSystemDirectory(userId);
1955         }
1956 
powerManagerGoToSleep(long time, int reason, int flags)1957         void powerManagerGoToSleep(long time, int reason, int flags) {
1958             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1959         }
1960 
powerManagerReboot(String reason)1961         void powerManagerReboot(String reason) {
1962             mContext.getSystemService(PowerManager.class).reboot(reason);
1963         }
1964 
recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force, boolean wipeEuicc)1965         void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force,
1966                 boolean wipeEuicc) throws IOException {
1967             RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force, wipeEuicc);
1968         }
1969 
systemPropertiesGetBoolean(String key, boolean def)1970         boolean systemPropertiesGetBoolean(String key, boolean def) {
1971             return SystemProperties.getBoolean(key, def);
1972         }
1973 
systemPropertiesGetLong(String key, long def)1974         long systemPropertiesGetLong(String key, long def) {
1975             return SystemProperties.getLong(key, def);
1976         }
1977 
systemPropertiesGet(String key, String def)1978         String systemPropertiesGet(String key, String def) {
1979             return SystemProperties.get(key, def);
1980         }
1981 
systemPropertiesGet(String key)1982         String systemPropertiesGet(String key) {
1983             return SystemProperties.get(key);
1984         }
1985 
systemPropertiesSet(String key, String value)1986         void systemPropertiesSet(String key, String value) {
1987             SystemProperties.set(key, value);
1988         }
1989 
userManagerIsSplitSystemUser()1990         boolean userManagerIsSplitSystemUser() {
1991             return UserManager.isSplitSystemUser();
1992         }
1993 
getDevicePolicyFilePathForSystemUser()1994         String getDevicePolicyFilePathForSystemUser() {
1995             return "/data/system/";
1996         }
1997 
pendingIntentGetActivityAsUser(Context context, int requestCode, @NonNull Intent intent, int flags, Bundle options, UserHandle user)1998         PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode,
1999                 @NonNull Intent intent, int flags, Bundle options, UserHandle user) {
2000             return PendingIntent.getActivityAsUser(
2001                     context, requestCode, intent, flags, options, user);
2002         }
2003 
registerContentObserver(Uri uri, boolean notifyForDescendents, ContentObserver observer, int userHandle)2004         void registerContentObserver(Uri uri, boolean notifyForDescendents,
2005                 ContentObserver observer, int userHandle) {
2006             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
2007                     observer, userHandle);
2008         }
2009 
settingsSecureGetIntForUser(String name, int def, int userHandle)2010         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
2011             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
2012                     name, def, userHandle);
2013         }
2014 
settingsSecureGetStringForUser(String name, int userHandle)2015         String settingsSecureGetStringForUser(String name, int userHandle) {
2016             return Settings.Secure.getStringForUser(mContext.getContentResolver(), name,
2017                     userHandle);
2018         }
2019 
settingsSecurePutIntForUser(String name, int value, int userHandle)2020         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
2021             Settings.Secure.putIntForUser(mContext.getContentResolver(),
2022                     name, value, userHandle);
2023         }
2024 
settingsSecurePutStringForUser(String name, String value, int userHandle)2025         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
2026             Settings.Secure.putStringForUser(mContext.getContentResolver(),
2027                     name, value, userHandle);
2028         }
2029 
settingsGlobalPutStringForUser(String name, String value, int userHandle)2030         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
2031             Settings.Global.putStringForUser(mContext.getContentResolver(),
2032                     name, value, userHandle);
2033         }
2034 
settingsSecurePutInt(String name, int value)2035         void settingsSecurePutInt(String name, int value) {
2036             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
2037         }
2038 
settingsGlobalGetInt(String name, int def)2039         int settingsGlobalGetInt(String name, int def) {
2040             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
2041         }
2042 
settingsGlobalGetString(String name)2043         String settingsGlobalGetString(String name) {
2044             return Settings.Global.getString(mContext.getContentResolver(), name);
2045         }
2046 
settingsGlobalPutInt(String name, int value)2047         void settingsGlobalPutInt(String name, int value) {
2048             Settings.Global.putInt(mContext.getContentResolver(), name, value);
2049         }
2050 
settingsSecurePutString(String name, String value)2051         void settingsSecurePutString(String name, String value) {
2052             Settings.Secure.putString(mContext.getContentResolver(), name, value);
2053         }
2054 
settingsGlobalPutString(String name, String value)2055         void settingsGlobalPutString(String name, String value) {
2056             Settings.Global.putString(mContext.getContentResolver(), name, value);
2057         }
2058 
settingsSystemPutStringForUser(String name, String value, int userId)2059         void settingsSystemPutStringForUser(String name, String value, int userId) {
2060           Settings.System.putStringForUser(
2061               mContext.getContentResolver(), name, value, userId);
2062         }
2063 
securityLogSetLoggingEnabledProperty(boolean enabled)2064         void securityLogSetLoggingEnabledProperty(boolean enabled) {
2065             SecurityLog.setLoggingEnabledProperty(enabled);
2066         }
2067 
securityLogGetLoggingEnabledProperty()2068         boolean securityLogGetLoggingEnabledProperty() {
2069             return SecurityLog.getLoggingEnabledProperty();
2070         }
2071 
securityLogIsLoggingEnabled()2072         boolean securityLogIsLoggingEnabled() {
2073             return SecurityLog.isLoggingEnabled();
2074         }
2075 
keyChainBindAsUser(UserHandle user)2076         KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException {
2077             return KeyChain.bindAsUser(mContext, user);
2078         }
2079 
postOnSystemServerInitThreadPool(Runnable runnable)2080         void postOnSystemServerInitThreadPool(Runnable runnable) {
2081             SystemServerInitThreadPool.get().submit(runnable, LOG_TAG);
2082         }
2083 
newTransferOwnershipMetadataManager()2084         public TransferOwnershipMetadataManager newTransferOwnershipMetadataManager() {
2085             return new TransferOwnershipMetadataManager();
2086         }
2087 
runCryptoSelfTest()2088         public void runCryptoSelfTest() {
2089             CryptoTestHelper.runAndLogSelfTest();
2090         }
2091     }
2092 
2093     /**
2094      * Instantiates the service.
2095      */
DevicePolicyManagerService(Context context)2096     public DevicePolicyManagerService(Context context) {
2097         this(new Injector(context));
2098     }
2099 
2100     @VisibleForTesting
DevicePolicyManagerService(Injector injector)2101     DevicePolicyManagerService(Injector injector) {
2102         mInjector = injector;
2103         mContext = Preconditions.checkNotNull(injector.mContext);
2104         mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
2105         mConstants = DevicePolicyConstants.loadFromString(
2106                 mInjector.settingsGlobalGetString(Global.DEVICE_POLICY_CONSTANTS));
2107 
2108         mOwners = Preconditions.checkNotNull(injector.newOwners());
2109 
2110         mUserManager = Preconditions.checkNotNull(injector.getUserManager());
2111         mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
2112         mUsageStatsManagerInternal = Preconditions.checkNotNull(
2113                 injector.getUsageStatsManagerInternal());
2114         mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
2115         mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
2116 
2117         mLocalService = new LocalService();
2118         mLockPatternUtils = injector.newLockPatternUtils();
2119 
2120         // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false?
2121         mSecurityLogMonitor = new SecurityLogMonitor(this);
2122 
2123         mHasFeature = mInjector.hasFeature();
2124         mIsWatch = mInjector.getPackageManager()
2125                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
2126         mBackgroundHandler = BackgroundThread.getHandler();
2127 
2128         // Needed when mHasFeature == false, because it controls the certificate warning text.
2129         mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler);
2130 
2131         mDeviceAdminServiceController = new DeviceAdminServiceController(this, mConstants);
2132 
2133         mOverlayPackagesProvider = new OverlayPackagesProvider(mContext);
2134 
2135         mTransferOwnershipMetadataManager = mInjector.newTransferOwnershipMetadataManager();
2136 
2137         if (!mHasFeature) {
2138             // Skip the rest of the initialization
2139             mSetupContentObserver = null;
2140             return;
2141         }
2142 
2143         IntentFilter filter = new IntentFilter();
2144         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
2145         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
2146         filter.addAction(Intent.ACTION_USER_ADDED);
2147         filter.addAction(Intent.ACTION_USER_REMOVED);
2148         filter.addAction(Intent.ACTION_USER_STARTED);
2149         filter.addAction(Intent.ACTION_USER_STOPPED);
2150         filter.addAction(Intent.ACTION_USER_SWITCHED);
2151         filter.addAction(Intent.ACTION_USER_UNLOCKED);
2152         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
2153         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2154         filter = new IntentFilter();
2155         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
2156         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
2157         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
2158         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
2159         filter.addDataScheme("package");
2160         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2161         filter = new IntentFilter();
2162         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
2163         filter.addAction(Intent.ACTION_TIME_CHANGED);
2164         filter.addAction(Intent.ACTION_DATE_CHANGED);
2165         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
2166 
2167         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
2168 
2169         mSetupContentObserver = new SetupContentObserver(mHandler);
2170 
2171         mUserManagerInternal.addUserRestrictionsListener(new RestrictionsListener(mContext));
2172     }
2173 
2174     /**
2175      * Creates and loads the policy data from xml.
2176      * @param userHandle the user for whom to load the policy data
2177      * @return
2178      */
2179     @NonNull
getUserData(int userHandle)2180     DevicePolicyData getUserData(int userHandle) {
2181         synchronized (getLockObject()) {
2182             DevicePolicyData policy = mUserData.get(userHandle);
2183             if (policy == null) {
2184                 policy = new DevicePolicyData(userHandle);
2185                 mUserData.append(userHandle, policy);
2186                 loadSettingsLocked(policy, userHandle);
2187             }
2188             return policy;
2189         }
2190     }
2191 
2192     /**
2193      * Provides PasswordMetrics object corresponding to the given user.
2194      * @param userHandle the user for whom to provide metrics.
2195      * @return the user password metrics, or {@code null} if none have been associated with
2196      * the user yet (for example, if the device has booted but not been unlocked).
2197      */
getUserPasswordMetricsLocked(int userHandle)2198     PasswordMetrics getUserPasswordMetricsLocked(int userHandle) {
2199         return mUserPasswordMetrics.get(userHandle);
2200     }
2201 
2202     /**
2203      * Creates and loads the policy data from xml for data that is shared between
2204      * various profiles of a user. In contrast to {@link #getUserData(int)}
2205      * it allows access to data of users other than the calling user.
2206      *
2207      * This function should only be used for shared data, e.g. everything regarding
2208      * passwords and should be removed once multiple screen locks are present.
2209      * @param userHandle the user for whom to load the policy data
2210      * @return
2211      */
getUserDataUnchecked(int userHandle)2212     DevicePolicyData getUserDataUnchecked(int userHandle) {
2213         long ident = mInjector.binderClearCallingIdentity();
2214         try {
2215             return getUserData(userHandle);
2216         } finally {
2217             mInjector.binderRestoreCallingIdentity(ident);
2218         }
2219     }
2220 
removeUserData(int userHandle)2221     void removeUserData(int userHandle) {
2222         synchronized (getLockObject()) {
2223             if (userHandle == UserHandle.USER_SYSTEM) {
2224                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
2225                 return;
2226             }
2227             mPolicyCache.onUserRemoved(userHandle);
2228 
2229             mOwners.removeProfileOwner(userHandle);
2230             mOwners.writeProfileOwner(userHandle);
2231 
2232             DevicePolicyData policy = mUserData.get(userHandle);
2233             if (policy != null) {
2234                 mUserData.remove(userHandle);
2235             }
2236             if (mUserPasswordMetrics.get(userHandle) != null) {
2237                 mUserPasswordMetrics.remove(userHandle);
2238             }
2239 
2240             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2241                     DEVICE_POLICIES_XML);
2242             policyFile.delete();
2243             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
2244         }
2245     }
2246 
loadOwners()2247     void loadOwners() {
2248         synchronized (getLockObject()) {
2249             mOwners.load();
2250             setDeviceOwnerSystemPropertyLocked();
2251             findOwnerComponentIfNecessaryLocked();
2252             migrateUserRestrictionsIfNecessaryLocked();
2253             maybeSetDefaultDeviceOwnerUserRestrictionsLocked();
2254 
2255             // TODO PO may not have a class name either due to b/17652534.  Address that too.
2256 
2257             updateDeviceOwnerLocked();
2258         }
2259     }
2260 
2261     /** Apply default restrictions that haven't been applied to device owners yet. */
maybeSetDefaultDeviceOwnerUserRestrictionsLocked()2262     private void maybeSetDefaultDeviceOwnerUserRestrictionsLocked() {
2263         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2264         if (deviceOwner != null) {
2265             maybeSetDefaultRestrictionsForAdminLocked(mOwners.getDeviceOwnerUserId(),
2266                     deviceOwner, UserRestrictionsUtils.getDefaultEnabledForDeviceOwner());
2267         }
2268     }
2269 
2270     /** Apply default restrictions that haven't been applied to profile owners yet. */
maybeSetDefaultProfileOwnerUserRestrictions()2271     private void maybeSetDefaultProfileOwnerUserRestrictions() {
2272         synchronized (getLockObject()) {
2273             for (final int userId : mOwners.getProfileOwnerKeys()) {
2274                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
2275                 // The following restrictions used to be applied to managed profiles by different
2276                 // means (via Settings or by disabling components). Now they are proper user
2277                 // restrictions so we apply them to managed profile owners. Non-managed secondary
2278                 // users didn't have those restrictions so we skip them to keep existing behavior.
2279                 if (profileOwner == null || !mUserManager.isManagedProfile(userId)) {
2280                     continue;
2281                 }
2282                 maybeSetDefaultRestrictionsForAdminLocked(userId, profileOwner,
2283                         UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
2284                 ensureUnknownSourcesRestrictionForProfileOwnerLocked(
2285                         userId, profileOwner, false /* newOwner */);
2286             }
2287         }
2288     }
2289 
2290     /**
2291      * Checks whether {@link UserManager#DISALLOW_INSTALL_UNKNOWN_SOURCES} should be added to the
2292      * set of restrictions for this profile owner.
2293      */
ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId, ActiveAdmin profileOwner, boolean newOwner)2294     private void ensureUnknownSourcesRestrictionForProfileOwnerLocked(int userId,
2295             ActiveAdmin profileOwner, boolean newOwner) {
2296         if (newOwner || mInjector.settingsSecureGetIntForUser(
2297                 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) != 0) {
2298             profileOwner.ensureUserRestrictions().putBoolean(
2299                     UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, true);
2300             saveUserRestrictionsLocked(userId);
2301             mInjector.settingsSecurePutIntForUser(
2302                     Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId);
2303         }
2304     }
2305 
2306     /**
2307      * Apply default restrictions that haven't been applied to a given admin yet.
2308      */
maybeSetDefaultRestrictionsForAdminLocked( int userId, ActiveAdmin admin, Set<String> defaultRestrictions)2309     private void maybeSetDefaultRestrictionsForAdminLocked(
2310             int userId, ActiveAdmin admin, Set<String> defaultRestrictions) {
2311         if (defaultRestrictions.equals(admin.defaultEnabledRestrictionsAlreadySet)) {
2312             return; // The same set of default restrictions has been already applied.
2313         }
2314         Slog.i(LOG_TAG, "New user restrictions need to be set by default for user " + userId);
2315 
2316         if (VERBOSE_LOG) {
2317             Slog.d(LOG_TAG,"Default enabled restrictions: "
2318                     + defaultRestrictions
2319                     + ". Restrictions already enabled: "
2320                     + admin.defaultEnabledRestrictionsAlreadySet);
2321         }
2322 
2323         final Set<String> restrictionsToSet = new ArraySet<>(defaultRestrictions);
2324         restrictionsToSet.removeAll(admin.defaultEnabledRestrictionsAlreadySet);
2325         if (!restrictionsToSet.isEmpty()) {
2326             for (final String restriction : restrictionsToSet) {
2327                 admin.ensureUserRestrictions().putBoolean(restriction, true);
2328             }
2329             admin.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet);
2330             Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictionsToSet);
2331             saveUserRestrictionsLocked(userId);
2332         }
2333     }
2334 
setDeviceOwnerSystemPropertyLocked()2335     private void setDeviceOwnerSystemPropertyLocked() {
2336         final boolean deviceProvisioned =
2337                 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0;
2338         final boolean hasDeviceOwner = mOwners.hasDeviceOwner();
2339         // If the device is not provisioned and there is currently no device owner, do not set the
2340         // read-only system property yet, since Device owner may still be provisioned.
2341         if (!hasDeviceOwner && !deviceProvisioned) {
2342             return;
2343         }
2344         // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
2345         // always false at this point.
2346         if (StorageManager.inCryptKeeperBounce()) {
2347             return;
2348         }
2349 
2350         if (!mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT, "").isEmpty()) {
2351             Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
2352         } else {
2353             final String value = Boolean.toString(hasDeviceOwner);
2354             mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, value);
2355             Slog.i(LOG_TAG, "Set ro.device_owner property to " + value);
2356         }
2357     }
2358 
maybeStartSecurityLogMonitorOnActivityManagerReady()2359     private void maybeStartSecurityLogMonitorOnActivityManagerReady() {
2360         synchronized (getLockObject()) {
2361             if (mInjector.securityLogIsLoggingEnabled()) {
2362                 mSecurityLogMonitor.start();
2363                 mInjector.runCryptoSelfTest();
2364                 maybePauseDeviceWideLoggingLocked();
2365             }
2366         }
2367     }
2368 
findOwnerComponentIfNecessaryLocked()2369     private void findOwnerComponentIfNecessaryLocked() {
2370         if (!mOwners.hasDeviceOwner()) {
2371             return;
2372         }
2373         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
2374 
2375         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
2376             return; // Already a full component name.
2377         }
2378 
2379         final ComponentName doComponent = findAdminComponentWithPackageLocked(
2380                 doComponentName.getPackageName(),
2381                 mOwners.getDeviceOwnerUserId());
2382         if (doComponent == null) {
2383             Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
2384         } else {
2385             mOwners.setDeviceOwnerWithRestrictionsMigrated(
2386                     doComponent,
2387                     mOwners.getDeviceOwnerName(),
2388                     mOwners.getDeviceOwnerUserId(),
2389                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
2390             mOwners.writeDeviceOwner();
2391             if (VERBOSE_LOG) {
2392                 Log.v(LOG_TAG, "Device owner component filled in");
2393             }
2394         }
2395     }
2396 
2397     /**
2398      * We didn't use to persist user restrictions for each owners but only persisted in user
2399      * manager.
2400      */
migrateUserRestrictionsIfNecessaryLocked()2401     private void migrateUserRestrictionsIfNecessaryLocked() {
2402         boolean migrated = false;
2403         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
2404         // except for the "system controlled" ones.
2405         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
2406             if (VERBOSE_LOG) {
2407                 Log.v(LOG_TAG, "Migrating DO user restrictions");
2408             }
2409             migrated = true;
2410 
2411             // Migrate user 0 restrictions to DO.
2412             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
2413 
2414             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
2415                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
2416 
2417             // Push DO user restrictions to user manager.
2418             pushUserRestrictions(UserHandle.USER_SYSTEM);
2419 
2420             mOwners.setDeviceOwnerUserRestrictionsMigrated();
2421         }
2422 
2423         // Migrate for POs.
2424 
2425         // The following restrictions can be set on secondary users by the device owner, so we
2426         // assume they're not from the PO.
2427         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
2428                 UserManager.DISALLOW_OUTGOING_CALLS,
2429                 UserManager.DISALLOW_SMS);
2430 
2431         for (UserInfo ui : mUserManager.getUsers()) {
2432             final int userId = ui.id;
2433             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
2434                 if (VERBOSE_LOG) {
2435                     Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
2436                 }
2437                 migrated = true;
2438 
2439                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
2440 
2441                 final Set<String> exceptionList =
2442                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
2443 
2444                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
2445                         exceptionList, /* isDeviceOwner =*/ false);
2446 
2447                 // Note if a secondary user has no PO but has a DA that disables camera, we
2448                 // don't get here and won't push the camera user restriction to UserManager
2449                 // here.  That's okay because we'll push user restrictions anyway when a user
2450                 // starts.  But we still do it because we want to let user manager persist
2451                 // upon migration.
2452                 pushUserRestrictions(userId);
2453 
2454                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
2455             }
2456         }
2457         if (VERBOSE_LOG && migrated) {
2458             Log.v(LOG_TAG, "User restrictions migrated.");
2459         }
2460     }
2461 
migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, Set<String> exceptionList, boolean isDeviceOwner)2462     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
2463             Set<String> exceptionList, boolean isDeviceOwner) {
2464         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
2465                 user.getIdentifier());
2466 
2467         final Bundle newBaseRestrictions = new Bundle();
2468         final Bundle newOwnerRestrictions = new Bundle();
2469 
2470         for (String key : origRestrictions.keySet()) {
2471             if (!origRestrictions.getBoolean(key)) {
2472                 continue;
2473             }
2474             final boolean canOwnerChange = isDeviceOwner
2475                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
2476                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
2477 
2478             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
2479                 newBaseRestrictions.putBoolean(key, true);
2480             } else {
2481                 newOwnerRestrictions.putBoolean(key, true);
2482             }
2483         }
2484 
2485         if (VERBOSE_LOG) {
2486             Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
2487             Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
2488             Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
2489         }
2490         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
2491                 newBaseRestrictions);
2492 
2493         if (admin != null) {
2494             admin.ensureUserRestrictions().clear();
2495             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
2496         } else {
2497             Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
2498         }
2499         saveSettingsLocked(user.getIdentifier());
2500     }
2501 
findAdminComponentWithPackageLocked(String packageName, int userId)2502     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
2503         final DevicePolicyData policy = getUserData(userId);
2504         final int n = policy.mAdminList.size();
2505         ComponentName found = null;
2506         int nFound = 0;
2507         for (int i = 0; i < n; i++) {
2508             final ActiveAdmin admin = policy.mAdminList.get(i);
2509             if (packageName.equals(admin.info.getPackageName())) {
2510                 // Found!
2511                 if (nFound == 0) {
2512                     found = admin.info.getComponent();
2513                 }
2514                 nFound++;
2515             }
2516         }
2517         if (nFound > 1) {
2518             Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
2519         }
2520         return found;
2521     }
2522 
2523     /**
2524      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
2525      * reminders.  Clears alarm if no expirations are configured.
2526      */
setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent)2527     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
2528         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
2529         final long now = System.currentTimeMillis();
2530         final long timeToExpire = expiration - now;
2531         final long alarmTime;
2532         if (expiration == 0) {
2533             // No expirations are currently configured:  Cancel alarm.
2534             alarmTime = 0;
2535         } else if (timeToExpire <= 0) {
2536             // The password has already expired:  Repeat every 24 hours.
2537             alarmTime = now + MS_PER_DAY;
2538         } else {
2539             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
2540             // the expiration time.
2541             long alarmInterval = timeToExpire % MS_PER_DAY;
2542             if (alarmInterval == 0) {
2543                 alarmInterval = MS_PER_DAY;
2544             }
2545             alarmTime = now + alarmInterval;
2546         }
2547 
2548         long token = mInjector.binderClearCallingIdentity();
2549         try {
2550             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
2551             AlarmManager am = mInjector.getAlarmManager();
2552             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
2553                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
2554                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
2555                     UserHandle.of(affectedUserHandle));
2556             am.cancel(pi);
2557             if (alarmTime != 0) {
2558                 am.set(AlarmManager.RTC, alarmTime, pi);
2559             }
2560         } finally {
2561             mInjector.binderRestoreCallingIdentity(token);
2562         }
2563     }
2564 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle)2565     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
2566         ensureLocked();
2567         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
2568         if (admin != null
2569                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
2570                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
2571             return admin;
2572         }
2573         return null;
2574     }
2575 
getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent)2576     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
2577         ensureLocked();
2578         if (parent) {
2579             enforceManagedProfile(userHandle, "call APIs on the parent profile");
2580         }
2581         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
2582         if (admin != null && parent) {
2583             admin = admin.getParentActiveAdmin();
2584         }
2585         return admin;
2586     }
2587 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)2588     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
2589             throws SecurityException {
2590         ensureLocked();
2591         final int callingUid = mInjector.binderGetCallingUid();
2592 
2593         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
2594         if (result != null) {
2595             return result;
2596         }
2597 
2598         if (who != null) {
2599             final int userId = UserHandle.getUserId(callingUid);
2600             final DevicePolicyData policy = getUserData(userId);
2601             ActiveAdmin admin = policy.mAdminMap.get(who);
2602             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2603                 throw new SecurityException("Admin " + admin.info.getComponent()
2604                          + " does not own the device");
2605             }
2606             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2607                 throw new SecurityException("Admin " + admin.info.getComponent()
2608                         + " does not own the profile");
2609             }
2610             throw new SecurityException("Admin " + admin.info.getComponent()
2611                     + " did not specify uses-policy for: "
2612                     + admin.info.getTagForPolicy(reqPolicy));
2613         } else {
2614             throw new SecurityException("No active admin owned by uid "
2615                     + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
2616         }
2617     }
2618 
getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)2619     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2620             throws SecurityException {
2621         ensureLocked();
2622         if (parent) {
2623             enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2624                     "call APIs on the parent profile");
2625         }
2626         ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2627         return parent ? admin.getParentActiveAdmin() : admin;
2628     }
2629     /**
2630      * Find the admin for the component and userId bit of the uid, then check
2631      * the admin's uid matches the uid.
2632      */
getActiveAdminForUidLocked(ComponentName who, int uid)2633     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2634         ensureLocked();
2635         final int userId = UserHandle.getUserId(uid);
2636         final DevicePolicyData policy = getUserData(userId);
2637         ActiveAdmin admin = policy.mAdminMap.get(who);
2638         if (admin == null) {
2639             throw new SecurityException("No active admin " + who);
2640         }
2641         if (admin.getUid() != uid) {
2642             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2643         }
2644         return admin;
2645     }
2646 
getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, int uid)2647     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2648             int uid) {
2649         ensureLocked();
2650         // Try to find an admin which can use reqPolicy
2651         final int userId = UserHandle.getUserId(uid);
2652         final DevicePolicyData policy = getUserData(userId);
2653         if (who != null) {
2654             ActiveAdmin admin = policy.mAdminMap.get(who);
2655             if (admin == null) {
2656                 throw new SecurityException("No active admin " + who);
2657             }
2658             if (admin.getUid() != uid) {
2659                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2660             }
2661             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2662                 return admin;
2663             }
2664         } else {
2665             for (ActiveAdmin admin : policy.mAdminList) {
2666                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2667                         userId)) {
2668                     return admin;
2669                 }
2670             }
2671         }
2672 
2673         return null;
2674     }
2675 
2676     @VisibleForTesting
isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, int userId)2677     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2678             int userId) {
2679         ensureLocked();
2680         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2681         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2682 
2683         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2684             return ownsDevice;
2685         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2686             // DO always has the PO power.
2687             return ownsDevice || ownsProfile;
2688         } else {
2689             return admin.info.usesPolicy(reqPolicy);
2690         }
2691     }
2692 
sendAdminCommandLocked(ActiveAdmin admin, String action)2693     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2694         sendAdminCommandLocked(admin, action, null);
2695     }
2696 
sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result)2697     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2698         sendAdminCommandLocked(admin, action, null, result);
2699     }
2700 
sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, BroadcastReceiver result)2701     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2702             BroadcastReceiver result) {
2703         sendAdminCommandLocked(admin, action, adminExtras, result, false);
2704     }
2705 
2706     /**
2707      * Send an update to one specific admin, get notified when that admin returns a result.
2708      *
2709      * @return whether the broadcast was successfully sent
2710      */
sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, BroadcastReceiver result, boolean inForeground)2711     boolean sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2712             BroadcastReceiver result, boolean inForeground) {
2713         Intent intent = new Intent(action);
2714         intent.setComponent(admin.info.getComponent());
2715         if (UserManager.isDeviceInDemoMode(mContext)) {
2716             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2717         }
2718         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2719             intent.putExtra("expiration", admin.passwordExpirationDate);
2720         }
2721         if (inForeground) {
2722             intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
2723         }
2724         if (adminExtras != null) {
2725             intent.putExtras(adminExtras);
2726         }
2727         if (mInjector.getPackageManager().queryBroadcastReceiversAsUser(
2728                 intent,
2729                 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2730                 admin.getUserHandle()).isEmpty()) {
2731             return false;
2732         }
2733         if (result != null) {
2734             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2735                     null, result, mHandler, Activity.RESULT_OK, null, null);
2736         } else {
2737             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2738         }
2739         return true;
2740     }
2741 
2742     /**
2743      * Send an update to all admins of a user that enforce a specified policy.
2744      */
sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras)2745     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) {
2746         final DevicePolicyData policy = getUserData(userHandle);
2747         final int count = policy.mAdminList.size();
2748         for (int i = 0; i < count; i++) {
2749             final ActiveAdmin admin = policy.mAdminList.get(i);
2750             if (admin.info.usesPolicy(reqPolicy)) {
2751                 sendAdminCommandLocked(admin, action, adminExtras, null);
2752             }
2753         }
2754     }
2755 
2756     /**
2757      * Send an update intent to all admins of a user and its profiles. Only send to admins that
2758      * enforce a specified policy.
2759      */
sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras)2760     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2761             int userHandle, Bundle adminExtras) {
2762         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2763         for (int profileId : profileIds) {
2764             sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras);
2765         }
2766     }
2767 
2768     /**
2769      * Sends a broadcast to each profile that share the password unlock with the given user id.
2770      */
sendAdminCommandForLockscreenPoliciesLocked( String action, int reqPolicy, int userHandle)2771     private void sendAdminCommandForLockscreenPoliciesLocked(
2772             String action, int reqPolicy, int userHandle) {
2773         final Bundle extras = new Bundle();
2774         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
2775         if (isSeparateProfileChallengeEnabled(userHandle)) {
2776             sendAdminCommandLocked(action, reqPolicy, userHandle, extras);
2777         } else {
2778             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras);
2779         }
2780     }
2781 
removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle)2782     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2783         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2784         DevicePolicyData policy = getUserData(userHandle);
2785         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2786             policy.mRemovingAdmins.add(adminReceiver);
2787             sendAdminCommandLocked(admin,
2788                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2789                     new BroadcastReceiver() {
2790                         @Override
2791                         public void onReceive(Context context, Intent intent) {
2792                             removeAdminArtifacts(adminReceiver, userHandle);
2793                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2794                         }
2795                     });
2796         }
2797     }
2798 
2799 
findAdmin(ComponentName adminName, int userHandle, boolean throwForMissingPermission)2800     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2801             boolean throwForMissingPermission) {
2802         if (!mHasFeature) {
2803             return null;
2804         }
2805         enforceFullCrossUsersPermission(userHandle);
2806         ActivityInfo ai = null;
2807         try {
2808             ai = mIPackageManager.getReceiverInfo(adminName,
2809                     PackageManager.GET_META_DATA |
2810                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2811                     PackageManager.MATCH_DIRECT_BOOT_AWARE |
2812                     PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2813         } catch (RemoteException e) {
2814             // shouldn't happen.
2815         }
2816         if (ai == null) {
2817             throw new IllegalArgumentException("Unknown admin: " + adminName);
2818         }
2819 
2820         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2821             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2822                     + permission.BIND_DEVICE_ADMIN;
2823             Slog.w(LOG_TAG, message);
2824             if (throwForMissingPermission &&
2825                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2826                 throw new IllegalArgumentException(message);
2827             }
2828         }
2829 
2830         try {
2831             return new DeviceAdminInfo(mContext, ai);
2832         } catch (XmlPullParserException | IOException e) {
2833             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2834                     e);
2835             return null;
2836         }
2837     }
2838 
getPolicyFileDirectory(@serIdInt int userId)2839     private File getPolicyFileDirectory(@UserIdInt int userId) {
2840         return userId == UserHandle.USER_SYSTEM
2841                 ? new File(mInjector.getDevicePolicyFilePathForSystemUser())
2842                 : mInjector.environmentGetUserSystemDirectory(userId);
2843     }
2844 
makeJournaledFile(@serIdInt int userId)2845     private JournaledFile makeJournaledFile(@UserIdInt int userId) {
2846         final String base = new File(getPolicyFileDirectory(userId), DEVICE_POLICIES_XML)
2847                 .getAbsolutePath();
2848         if (VERBOSE_LOG) {
2849             Log.v(LOG_TAG, "Opening " + base);
2850         }
2851         return new JournaledFile(new File(base), new File(base + ".tmp"));
2852     }
2853 
saveSettingsLocked(int userHandle)2854     private void saveSettingsLocked(int userHandle) {
2855         DevicePolicyData policy = getUserData(userHandle);
2856         JournaledFile journal = makeJournaledFile(userHandle);
2857         FileOutputStream stream = null;
2858         try {
2859             stream = new FileOutputStream(journal.chooseForWrite(), false);
2860             XmlSerializer out = new FastXmlSerializer();
2861             out.setOutput(stream, StandardCharsets.UTF_8.name());
2862             out.startDocument(null, true);
2863 
2864             out.startTag(null, "policies");
2865             if (policy.mRestrictionsProvider != null) {
2866                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2867                         policy.mRestrictionsProvider.flattenToString());
2868             }
2869             if (policy.mUserSetupComplete) {
2870                 out.attribute(null, ATTR_SETUP_COMPLETE,
2871                         Boolean.toString(true));
2872             }
2873             if (policy.mPaired) {
2874                 out.attribute(null, ATTR_DEVICE_PAIRED,
2875                         Boolean.toString(true));
2876             }
2877             if (policy.mDeviceProvisioningConfigApplied) {
2878                 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2879                         Boolean.toString(true));
2880             }
2881             if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2882                 out.attribute(null, ATTR_PROVISIONING_STATE,
2883                         Integer.toString(policy.mUserProvisioningState));
2884             }
2885             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2886                 out.attribute(null, ATTR_PERMISSION_POLICY,
2887                         Integer.toString(policy.mPermissionPolicy));
2888             }
2889 
2890             // Serialize delegations.
2891             for (int i = 0; i < policy.mDelegationMap.size(); ++i) {
2892                 final String delegatePackage = policy.mDelegationMap.keyAt(i);
2893                 final List<String> scopes = policy.mDelegationMap.valueAt(i);
2894 
2895                 // Every "delegation" tag serializes the information of one delegate-scope pair.
2896                 for (String scope : scopes) {
2897                     out.startTag(null, "delegation");
2898                     out.attribute(null, "delegatePackage", delegatePackage);
2899                     out.attribute(null, "scope", scope);
2900                     out.endTag(null, "delegation");
2901                 }
2902             }
2903 
2904             final int N = policy.mAdminList.size();
2905             for (int i=0; i<N; i++) {
2906                 ActiveAdmin ap = policy.mAdminList.get(i);
2907                 if (ap != null) {
2908                     out.startTag(null, "admin");
2909                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
2910                     ap.writeToXml(out);
2911                     out.endTag(null, "admin");
2912                 }
2913             }
2914 
2915             if (policy.mPasswordOwner >= 0) {
2916                 out.startTag(null, "password-owner");
2917                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2918                 out.endTag(null, "password-owner");
2919             }
2920 
2921             if (policy.mFailedPasswordAttempts != 0) {
2922                 out.startTag(null, "failed-password-attempts");
2923                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2924                 out.endTag(null, "failed-password-attempts");
2925             }
2926 
2927             // For FDE devices only, we save this flag so we can report on password sufficiency
2928             // before the user enters their password for the first time after a reboot.  For
2929             // security reasons, we don't want to store the full set of active password metrics.
2930             if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2931                 out.startTag(null, TAG_PASSWORD_VALIDITY);
2932                 out.attribute(null, ATTR_VALUE,
2933                         Boolean.toString(policy.mPasswordValidAtLastCheckpoint));
2934                 out.endTag(null, TAG_PASSWORD_VALIDITY);
2935             }
2936 
2937             for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2938                 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2939                 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2940                 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2941             }
2942 
2943             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2944                 String component = policy.mLockTaskPackages.get(i);
2945                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2946                 out.attribute(null, "name", component);
2947                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2948             }
2949 
2950             if (policy.mLockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE) {
2951                 out.startTag(null, TAG_LOCK_TASK_FEATURES);
2952                 out.attribute(null, ATTR_VALUE, Integer.toString(policy.mLockTaskFeatures));
2953                 out.endTag(null, TAG_LOCK_TASK_FEATURES);
2954             }
2955 
2956             if (policy.mStatusBarDisabled) {
2957                 out.startTag(null, TAG_STATUS_BAR);
2958                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2959                 out.endTag(null, TAG_STATUS_BAR);
2960             }
2961 
2962             if (policy.doNotAskCredentialsOnBoot) {
2963                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2964                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2965             }
2966 
2967             for (String id : policy.mAffiliationIds) {
2968                 out.startTag(null, TAG_AFFILIATION_ID);
2969                 out.attribute(null, ATTR_ID, id);
2970                 out.endTag(null, TAG_AFFILIATION_ID);
2971             }
2972 
2973             if (policy.mLastSecurityLogRetrievalTime >= 0) {
2974                 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2975                 out.attribute(null, ATTR_VALUE,
2976                         Long.toString(policy.mLastSecurityLogRetrievalTime));
2977                 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL);
2978             }
2979 
2980             if (policy.mLastBugReportRequestTime >= 0) {
2981                 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2982                 out.attribute(null, ATTR_VALUE,
2983                         Long.toString(policy.mLastBugReportRequestTime));
2984                 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST);
2985             }
2986 
2987             if (policy.mLastNetworkLogsRetrievalTime >= 0) {
2988                 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2989                 out.attribute(null, ATTR_VALUE,
2990                         Long.toString(policy.mLastNetworkLogsRetrievalTime));
2991                 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL);
2992             }
2993 
2994             if (policy.mAdminBroadcastPending) {
2995                 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2996                 out.attribute(null, ATTR_VALUE,
2997                         Boolean.toString(policy.mAdminBroadcastPending));
2998                 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2999             }
3000 
3001             if (policy.mInitBundle != null) {
3002                 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
3003                 policy.mInitBundle.saveToXml(out);
3004                 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
3005             }
3006 
3007             if (policy.mPasswordTokenHandle != 0) {
3008                 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE);
3009                 out.attribute(null, ATTR_VALUE,
3010                         Long.toString(policy.mPasswordTokenHandle));
3011                 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE);
3012             }
3013 
3014             if (policy.mCurrentInputMethodSet) {
3015                 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET);
3016                 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET);
3017             }
3018 
3019             for (final String cert : policy.mOwnerInstalledCaCerts) {
3020                 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT);
3021                 out.attribute(null, ATTR_ALIAS, cert);
3022                 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT);
3023             }
3024 
3025             out.endTag(null, "policies");
3026 
3027             out.endDocument();
3028             stream.flush();
3029             FileUtils.sync(stream);
3030             stream.close();
3031             journal.commit();
3032             sendChangedNotification(userHandle);
3033         } catch (XmlPullParserException | IOException e) {
3034             Slog.w(LOG_TAG, "failed writing file", e);
3035             try {
3036                 if (stream != null) {
3037                     stream.close();
3038                 }
3039             } catch (IOException ex) {
3040                 // Ignore
3041             }
3042             journal.rollback();
3043         }
3044     }
3045 
sendChangedNotification(int userHandle)3046     private void sendChangedNotification(int userHandle) {
3047         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
3048         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3049         long ident = mInjector.binderClearCallingIdentity();
3050         try {
3051             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
3052         } finally {
3053             mInjector.binderRestoreCallingIdentity(ident);
3054         }
3055     }
3056 
loadSettingsLocked(DevicePolicyData policy, int userHandle)3057     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
3058         JournaledFile journal = makeJournaledFile(userHandle);
3059         FileInputStream stream = null;
3060         File file = journal.chooseForRead();
3061         boolean needsRewrite = false;
3062         try {
3063             stream = new FileInputStream(file);
3064             XmlPullParser parser = Xml.newPullParser();
3065             parser.setInput(stream, StandardCharsets.UTF_8.name());
3066 
3067             int type;
3068             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3069                     && type != XmlPullParser.START_TAG) {
3070             }
3071             String tag = parser.getName();
3072             if (!"policies".equals(tag)) {
3073                 throw new XmlPullParserException(
3074                         "Settings do not start with policies tag: found " + tag);
3075             }
3076 
3077             // Extract the permission provider component name if available
3078             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
3079             if (permissionProvider != null) {
3080                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
3081             }
3082             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
3083             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
3084                 policy.mUserSetupComplete = true;
3085             }
3086             String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
3087             if (paired != null && Boolean.toString(true).equals(paired)) {
3088                 policy.mPaired = true;
3089             }
3090             String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
3091                     ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
3092             if (deviceProvisioningConfigApplied != null
3093                     && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
3094                 policy.mDeviceProvisioningConfigApplied = true;
3095             }
3096             String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
3097             if (!TextUtils.isEmpty(provisioningState)) {
3098                 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
3099             }
3100             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
3101             if (!TextUtils.isEmpty(permissionPolicy)) {
3102                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
3103             }
3104             // Check for delegation compatibility with pre-O.
3105             // TODO(edmanp) remove in P.
3106             {
3107                 final String certDelegate = parser.getAttributeValue(null,
3108                         ATTR_DELEGATED_CERT_INSTALLER);
3109                 if (certDelegate != null) {
3110                     List<String> scopes = policy.mDelegationMap.get(certDelegate);
3111                     if (scopes == null) {
3112                         scopes = new ArrayList<>();
3113                         policy.mDelegationMap.put(certDelegate, scopes);
3114                     }
3115                     if (!scopes.contains(DELEGATION_CERT_INSTALL)) {
3116                         scopes.add(DELEGATION_CERT_INSTALL);
3117                         needsRewrite = true;
3118                     }
3119                 }
3120                 final String appRestrictionsDelegate = parser.getAttributeValue(null,
3121                         ATTR_APPLICATION_RESTRICTIONS_MANAGER);
3122                 if (appRestrictionsDelegate != null) {
3123                     List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate);
3124                     if (scopes == null) {
3125                         scopes = new ArrayList<>();
3126                         policy.mDelegationMap.put(appRestrictionsDelegate, scopes);
3127                     }
3128                     if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) {
3129                         scopes.add(DELEGATION_APP_RESTRICTIONS);
3130                         needsRewrite = true;
3131                     }
3132                 }
3133             }
3134 
3135             type = parser.next();
3136             int outerDepth = parser.getDepth();
3137             policy.mLockTaskPackages.clear();
3138             policy.mAdminList.clear();
3139             policy.mAdminMap.clear();
3140             policy.mAffiliationIds.clear();
3141             policy.mOwnerInstalledCaCerts.clear();
3142             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
3143                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
3144                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
3145                     continue;
3146                 }
3147                 tag = parser.getName();
3148                 if ("admin".equals(tag)) {
3149                     String name = parser.getAttributeValue(null, "name");
3150                     try {
3151                         DeviceAdminInfo dai = findAdmin(
3152                                 ComponentName.unflattenFromString(name), userHandle,
3153                                 /* throwForMissingPermission= */ false);
3154                         if (VERBOSE_LOG
3155                                 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
3156                                 != userHandle)) {
3157                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
3158                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
3159                                     + userHandle);
3160                         }
3161                         if (dai != null) {
3162                             ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
3163                             ap.readFromXml(parser);
3164                             policy.mAdminMap.put(ap.info.getComponent(), ap);
3165                         }
3166                     } catch (RuntimeException e) {
3167                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
3168                     }
3169                 } else if ("delegation".equals(tag)) {
3170                     // Parse delegation info.
3171                     final String delegatePackage = parser.getAttributeValue(null,
3172                             "delegatePackage");
3173                     final String scope = parser.getAttributeValue(null, "scope");
3174 
3175                     // Get a reference to the scopes list for the delegatePackage.
3176                     List<String> scopes = policy.mDelegationMap.get(delegatePackage);
3177                     // Or make a new list if none was found.
3178                     if (scopes == null) {
3179                         scopes = new ArrayList<>();
3180                         policy.mDelegationMap.put(delegatePackage, scopes);
3181                     }
3182                     // Add the new scope to the list of delegatePackage if it's not already there.
3183                     if (!scopes.contains(scope)) {
3184                         scopes.add(scope);
3185                     }
3186                 } else if ("failed-password-attempts".equals(tag)) {
3187                     policy.mFailedPasswordAttempts = Integer.parseInt(
3188                             parser.getAttributeValue(null, "value"));
3189                 } else if ("password-owner".equals(tag)) {
3190                     policy.mPasswordOwner = Integer.parseInt(
3191                             parser.getAttributeValue(null, "value"));
3192                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
3193                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
3194                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
3195                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
3196                 } else if (TAG_LOCK_TASK_FEATURES.equals(tag)) {
3197                     policy.mLockTaskFeatures = Integer.parseInt(
3198                             parser.getAttributeValue(null, ATTR_VALUE));
3199                 } else if (TAG_STATUS_BAR.equals(tag)) {
3200                     policy.mStatusBarDisabled = Boolean.parseBoolean(
3201                             parser.getAttributeValue(null, ATTR_DISABLED));
3202                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
3203                     policy.doNotAskCredentialsOnBoot = true;
3204                 } else if (TAG_AFFILIATION_ID.equals(tag)) {
3205                     policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID));
3206                 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) {
3207                     policy.mLastSecurityLogRetrievalTime = Long.parseLong(
3208                             parser.getAttributeValue(null, ATTR_VALUE));
3209                 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) {
3210                     policy.mLastBugReportRequestTime = Long.parseLong(
3211                             parser.getAttributeValue(null, ATTR_VALUE));
3212                 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) {
3213                     policy.mLastNetworkLogsRetrievalTime = Long.parseLong(
3214                             parser.getAttributeValue(null, ATTR_VALUE));
3215                 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
3216                     String pending = parser.getAttributeValue(null, ATTR_VALUE);
3217                     policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
3218                 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
3219                     policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
3220                 } else if ("active-password".equals(tag)) {
3221                     // Remove password metrics from saved settings, as we no longer wish to store
3222                     // these on disk
3223                     needsRewrite = true;
3224                 } else if (TAG_PASSWORD_VALIDITY.equals(tag)) {
3225                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
3226                         // This flag is only used for FDE devices
3227                         policy.mPasswordValidAtLastCheckpoint = Boolean.parseBoolean(
3228                                 parser.getAttributeValue(null, ATTR_VALUE));
3229                     }
3230                 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) {
3231                     policy.mPasswordTokenHandle = Long.parseLong(
3232                             parser.getAttributeValue(null, ATTR_VALUE));
3233                 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) {
3234                     policy.mCurrentInputMethodSet = true;
3235                 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) {
3236                     policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS));
3237                 } else {
3238                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
3239                     XmlUtils.skipCurrentTag(parser);
3240                 }
3241             }
3242         } catch (FileNotFoundException e) {
3243             // Don't be noisy, this is normal if we haven't defined any policies.
3244         } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
3245                 | IndexOutOfBoundsException e) {
3246             Slog.w(LOG_TAG, "failed parsing " + file, e);
3247         }
3248         try {
3249             if (stream != null) {
3250                 stream.close();
3251             }
3252         } catch (IOException e) {
3253             // Ignore
3254         }
3255 
3256         // Generate a list of admins from the admin map
3257         policy.mAdminList.addAll(policy.mAdminMap.values());
3258 
3259         // Might need to upgrade the file by rewriting it
3260         if (needsRewrite) {
3261             saveSettingsLocked(userHandle);
3262         }
3263 
3264         validatePasswordOwnerLocked(policy);
3265         updateMaximumTimeToLockLocked(userHandle);
3266         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
3267         updateLockTaskFeaturesLocked(policy.mLockTaskFeatures, userHandle);
3268         if (policy.mStatusBarDisabled) {
3269             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
3270         }
3271     }
3272 
updateLockTaskPackagesLocked(List<String> packages, int userId)3273     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
3274         long ident = mInjector.binderClearCallingIdentity();
3275         try {
3276             mInjector.getIActivityManager()
3277                     .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
3278         } catch (RemoteException e) {
3279             // Not gonna happen.
3280         } finally {
3281             mInjector.binderRestoreCallingIdentity(ident);
3282         }
3283     }
3284 
updateLockTaskFeaturesLocked(int flags, int userId)3285     private void updateLockTaskFeaturesLocked(int flags, int userId) {
3286         long ident = mInjector.binderClearCallingIdentity();
3287         try {
3288             mInjector.getIActivityManager()
3289                     .updateLockTaskFeatures(userId, flags);
3290         } catch (RemoteException e) {
3291             // Not gonna happen.
3292         } finally {
3293             mInjector.binderRestoreCallingIdentity(ident);
3294         }
3295     }
3296 
updateDeviceOwnerLocked()3297     private void updateDeviceOwnerLocked() {
3298         long ident = mInjector.binderClearCallingIdentity();
3299         try {
3300             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
3301             // user id and also protect all other DAs too.
3302             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
3303             if (deviceOwnerComponent != null) {
3304                 mInjector.getIActivityManager()
3305                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
3306             }
3307         } catch (RemoteException e) {
3308             // Not gonna happen.
3309         } finally {
3310             mInjector.binderRestoreCallingIdentity(ident);
3311         }
3312     }
3313 
validateQualityConstant(int quality)3314     static void validateQualityConstant(int quality) {
3315         switch (quality) {
3316             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
3317             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
3318             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
3319             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
3320             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
3321             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
3322             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
3323             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
3324             case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
3325                 return;
3326         }
3327         throw new IllegalArgumentException("Invalid quality constant: 0x"
3328                 + Integer.toHexString(quality));
3329     }
3330 
validatePasswordOwnerLocked(DevicePolicyData policy)3331     void validatePasswordOwnerLocked(DevicePolicyData policy) {
3332         if (policy.mPasswordOwner >= 0) {
3333             boolean haveOwner = false;
3334             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
3335                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
3336                     haveOwner = true;
3337                     break;
3338                 }
3339             }
3340             if (!haveOwner) {
3341                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
3342                         + " no longer active; disabling");
3343                 policy.mPasswordOwner = -1;
3344             }
3345         }
3346     }
3347 
3348     @VisibleForTesting
3349     @Override
systemReady(int phase)3350     void systemReady(int phase) {
3351         if (!mHasFeature) {
3352             return;
3353         }
3354         switch (phase) {
3355             case SystemService.PHASE_LOCK_SETTINGS_READY:
3356                 onLockSettingsReady();
3357                 loadAdminDataAsync();
3358                 mOwners.systemReady();
3359                 break;
3360             case SystemService.PHASE_ACTIVITY_MANAGER_READY:
3361                 maybeStartSecurityLogMonitorOnActivityManagerReady();
3362                 break;
3363             case SystemService.PHASE_BOOT_COMPLETED:
3364                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
3365                 break;
3366         }
3367     }
3368 
onLockSettingsReady()3369     private void onLockSettingsReady() {
3370         getUserData(UserHandle.USER_SYSTEM);
3371         loadOwners();
3372         cleanUpOldUsers();
3373         maybeSetDefaultProfileOwnerUserRestrictions();
3374         handleStartUser(UserHandle.USER_SYSTEM);
3375         maybeLogStart();
3376 
3377         // Register an observer for watching for user setup complete and settings changes.
3378         mSetupContentObserver.register();
3379         // Initialize the user setup state, to handle the upgrade case.
3380         updateUserSetupCompleteAndPaired();
3381 
3382         List<String> packageList;
3383         synchronized (getLockObject()) {
3384             packageList = getKeepUninstalledPackagesLocked();
3385         }
3386         if (packageList != null) {
3387             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
3388         }
3389 
3390         synchronized (getLockObject()) {
3391             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
3392             if (deviceOwner != null) {
3393                 // Push the force-ephemeral-users policy to the user manager.
3394                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
3395 
3396                 // Update user switcher message to activity manager.
3397                 ActivityManagerInternal activityManagerInternal =
3398                         mInjector.getActivityManagerInternal();
3399                 activityManagerInternal.setSwitchingFromSystemUserMessage(
3400                         deviceOwner.startUserSessionMessage);
3401                 activityManagerInternal.setSwitchingToSystemUserMessage(
3402                         deviceOwner.endUserSessionMessage);
3403             }
3404 
3405             revertTransferOwnershipIfNecessaryLocked();
3406         }
3407     }
3408 
revertTransferOwnershipIfNecessaryLocked()3409     private void revertTransferOwnershipIfNecessaryLocked() {
3410         if (!mTransferOwnershipMetadataManager.metadataFileExists()) {
3411             return;
3412         }
3413         Slog.e(LOG_TAG, "Owner transfer metadata file exists! Reverting transfer.");
3414         final TransferOwnershipMetadataManager.Metadata metadata =
3415                 mTransferOwnershipMetadataManager.loadMetadataFile();
3416         // Revert transfer
3417         if (metadata.adminType.equals(ADMIN_TYPE_PROFILE_OWNER)) {
3418             transferProfileOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3419                     metadata.userId);
3420             deleteTransferOwnershipMetadataFileLocked();
3421             deleteTransferOwnershipBundleLocked(metadata.userId);
3422         } else if (metadata.adminType.equals(ADMIN_TYPE_DEVICE_OWNER)) {
3423             transferDeviceOwnershipLocked(metadata.targetComponent, metadata.sourceComponent,
3424                     metadata.userId);
3425             deleteTransferOwnershipMetadataFileLocked();
3426             deleteTransferOwnershipBundleLocked(metadata.userId);
3427         }
3428         updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ true);
3429     }
3430 
maybeLogStart()3431     private void maybeLogStart() {
3432         if (!SecurityLog.isLoggingEnabled()) {
3433             return;
3434         }
3435         final String verifiedBootState =
3436                 mInjector.systemPropertiesGet("ro.boot.verifiedbootstate");
3437         final String verityMode = mInjector.systemPropertiesGet("ro.boot.veritymode");
3438         SecurityLog.writeEvent(SecurityLog.TAG_OS_STARTUP, verifiedBootState, verityMode);
3439     }
3440 
ensureDeviceOwnerUserStarted()3441     private void ensureDeviceOwnerUserStarted() {
3442         final int userId;
3443         synchronized (getLockObject()) {
3444             if (!mOwners.hasDeviceOwner()) {
3445                 return;
3446             }
3447             userId = mOwners.getDeviceOwnerUserId();
3448         }
3449         if (VERBOSE_LOG) {
3450             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
3451         }
3452         if (userId != UserHandle.USER_SYSTEM) {
3453             try {
3454                 mInjector.getIActivityManager().startUserInBackground(userId);
3455 
3456                 // STOPSHIP Prevent the DO user from being killed.
3457 
3458             } catch (RemoteException e) {
3459                 Slog.w(LOG_TAG, "Exception starting user", e);
3460             }
3461         }
3462     }
3463 
3464     @Override
handleStartUser(int userId)3465     void handleStartUser(int userId) {
3466         updateScreenCaptureDisabled(userId,
3467                 getScreenCaptureDisabled(null, userId));
3468         pushUserRestrictions(userId);
3469 
3470         startOwnerService(userId, "start-user");
3471     }
3472 
3473     @Override
handleUnlockUser(int userId)3474     void handleUnlockUser(int userId) {
3475         startOwnerService(userId, "unlock-user");
3476     }
3477 
3478     @Override
handleStopUser(int userId)3479     void handleStopUser(int userId) {
3480         stopOwnerService(userId, "stop-user");
3481     }
3482 
startOwnerService(int userId, String actionForLog)3483     private void startOwnerService(int userId, String actionForLog) {
3484         final ComponentName owner = getOwnerComponent(userId);
3485         if (owner != null) {
3486             mDeviceAdminServiceController.startServiceForOwner(
3487                     owner.getPackageName(), userId, actionForLog);
3488         }
3489     }
3490 
stopOwnerService(int userId, String actionForLog)3491     private void stopOwnerService(int userId, String actionForLog) {
3492         mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog);
3493     }
3494 
cleanUpOldUsers()3495     private void cleanUpOldUsers() {
3496         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
3497         // before reboot
3498         Set<Integer> usersWithProfileOwners;
3499         Set<Integer> usersWithData;
3500         synchronized (getLockObject()) {
3501             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
3502             usersWithData = new ArraySet<>();
3503             for (int i = 0; i < mUserData.size(); i++) {
3504                 usersWithData.add(mUserData.keyAt(i));
3505             }
3506         }
3507         List<UserInfo> allUsers = mUserManager.getUsers();
3508 
3509         Set<Integer> deletedUsers = new ArraySet<>();
3510         deletedUsers.addAll(usersWithProfileOwners);
3511         deletedUsers.addAll(usersWithData);
3512         for (UserInfo userInfo : allUsers) {
3513             deletedUsers.remove(userInfo.id);
3514         }
3515         for (Integer userId : deletedUsers) {
3516             removeUserData(userId);
3517         }
3518     }
3519 
handlePasswordExpirationNotification(int userHandle)3520     private void handlePasswordExpirationNotification(int userHandle) {
3521         final Bundle adminExtras = new Bundle();
3522         adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle));
3523 
3524         synchronized (getLockObject()) {
3525             final long now = System.currentTimeMillis();
3526 
3527             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
3528                     userHandle, /* parent */ false);
3529             final int N = admins.size();
3530             for (int i = 0; i < N; i++) {
3531                 ActiveAdmin admin = admins.get(i);
3532                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
3533                         && admin.passwordExpirationTimeout > 0L
3534                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
3535                         && admin.passwordExpirationDate > 0L) {
3536                     sendAdminCommandLocked(admin,
3537                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null);
3538                 }
3539             }
3540             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
3541         }
3542     }
3543 
3544     /**
3545      * Clean up internal state when the set of installed trusted CA certificates changes.
3546      *
3547      * @param userHandle user to check for. This must be a real user and not, for example,
3548      *        {@link UserHandle#ALL}.
3549      * @param installedCertificates the full set of certificate authorities currently installed for
3550      *        {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will
3551      *        correspond to some subset of this.
3552      */
onInstalledCertificatesChanged(final UserHandle userHandle, final @NonNull Collection<String> installedCertificates)3553     protected void onInstalledCertificatesChanged(final UserHandle userHandle,
3554             final @NonNull Collection<String> installedCertificates) {
3555         if (!mHasFeature) {
3556             return;
3557         }
3558         enforceManageUsers();
3559 
3560         synchronized (getLockObject()) {
3561             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3562 
3563             boolean changed = false;
3564             changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates);
3565             changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates);
3566             if (changed) {
3567                 saveSettingsLocked(userHandle.getIdentifier());
3568             }
3569         }
3570     }
3571 
3572     /**
3573      * Internal method used by {@link CertificateMonitor}.
3574      */
getAcceptedCaCertificates(final UserHandle userHandle)3575     protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) {
3576         if (!mHasFeature) {
3577             return Collections.<String> emptySet();
3578         }
3579         synchronized (getLockObject()) {
3580             final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
3581             return policy.mAcceptedCaCertificates;
3582         }
3583     }
3584 
3585     /**
3586      * @param adminReceiver The admin to add
3587      * @param refreshing true = update an active admin, no error
3588      */
3589     @Override
setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle)3590     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
3591         if (!mHasFeature) {
3592             return;
3593         }
3594         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
3595     }
3596 
setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, Bundle onEnableData)3597     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
3598             Bundle onEnableData) {
3599         mContext.enforceCallingOrSelfPermission(
3600                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3601         enforceFullCrossUsersPermission(userHandle);
3602 
3603         DevicePolicyData policy = getUserData(userHandle);
3604         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
3605                 /* throwForMissingPermission= */ true);
3606         synchronized (getLockObject()) {
3607             checkActiveAdminPrecondition(adminReceiver, info, policy);
3608             long ident = mInjector.binderClearCallingIdentity();
3609             try {
3610                 final ActiveAdmin existingAdmin
3611                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3612                 if (!refreshing && existingAdmin != null) {
3613                     throw new IllegalArgumentException("Admin is already added");
3614                 }
3615                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
3616                 newAdmin.testOnlyAdmin =
3617                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
3618                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
3619                 policy.mAdminMap.put(adminReceiver, newAdmin);
3620                 int replaceIndex = -1;
3621                 final int N = policy.mAdminList.size();
3622                 for (int i=0; i < N; i++) {
3623                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
3624                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
3625                         replaceIndex = i;
3626                         break;
3627                     }
3628                 }
3629                 if (replaceIndex == -1) {
3630                     policy.mAdminList.add(newAdmin);
3631                     enableIfNecessary(info.getPackageName(), userHandle);
3632                     mUsageStatsManagerInternal.onActiveAdminAdded(
3633                             adminReceiver.getPackageName(), userHandle);
3634                 } else {
3635                     policy.mAdminList.set(replaceIndex, newAdmin);
3636                 }
3637                 saveSettingsLocked(userHandle);
3638                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3639                         onEnableData, null);
3640             } finally {
3641                 mInjector.binderRestoreCallingIdentity(ident);
3642             }
3643         }
3644     }
3645 
loadAdminDataAsync()3646     private void loadAdminDataAsync() {
3647         mInjector.postOnSystemServerInitThreadPool(() -> {
3648             pushActiveAdminPackages();
3649             mUsageStatsManagerInternal.onAdminDataAvailable();
3650             pushAllMeteredRestrictedPackages();
3651             mInjector.getNetworkPolicyManagerInternal().onAdminDataAvailable();
3652         });
3653     }
3654 
pushActiveAdminPackages()3655     private void pushActiveAdminPackages() {
3656         synchronized (getLockObject()) {
3657             final List<UserInfo> users = mUserManager.getUsers();
3658             for (int i = users.size() - 1; i >= 0; --i) {
3659                 final int userId = users.get(i).id;
3660                 mUsageStatsManagerInternal.setActiveAdminApps(
3661                         getActiveAdminPackagesLocked(userId), userId);
3662             }
3663         }
3664     }
3665 
pushAllMeteredRestrictedPackages()3666     private void pushAllMeteredRestrictedPackages() {
3667         synchronized (getLockObject()) {
3668             final List<UserInfo> users = mUserManager.getUsers();
3669             for (int i = users.size() - 1; i >= 0; --i) {
3670                 final int userId = users.get(i).id;
3671                 mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackagesAsync(
3672                         getMeteredDisabledPackagesLocked(userId), userId);
3673             }
3674         }
3675     }
3676 
pushActiveAdminPackagesLocked(int userId)3677     private void pushActiveAdminPackagesLocked(int userId) {
3678         mUsageStatsManagerInternal.setActiveAdminApps(
3679                 getActiveAdminPackagesLocked(userId), userId);
3680     }
3681 
getActiveAdminPackagesLocked(int userId)3682     private Set<String> getActiveAdminPackagesLocked(int userId) {
3683         final DevicePolicyData policy = getUserData(userId);
3684         Set<String> adminPkgs = null;
3685         for (int i = policy.mAdminList.size() - 1; i >= 0; --i) {
3686             final String pkgName = policy.mAdminList.get(i).info.getPackageName();
3687             if (adminPkgs == null) {
3688                 adminPkgs = new ArraySet<>();
3689             }
3690             adminPkgs.add(pkgName);
3691         }
3692         return adminPkgs;
3693     }
3694 
transferActiveAdminUncheckedLocked(ComponentName incomingReceiver, ComponentName outgoingReceiver, int userHandle)3695     private void transferActiveAdminUncheckedLocked(ComponentName incomingReceiver,
3696             ComponentName outgoingReceiver, int userHandle) {
3697         final DevicePolicyData policy = getUserData(userHandle);
3698         if (!policy.mAdminMap.containsKey(outgoingReceiver)
3699                 && policy.mAdminMap.containsKey(incomingReceiver)) {
3700             // Nothing to transfer - the incoming receiver is already the active admin.
3701             return;
3702         }
3703         final DeviceAdminInfo incomingDeviceInfo = findAdmin(incomingReceiver, userHandle,
3704             /* throwForMissingPermission= */ true);
3705         final ActiveAdmin adminToTransfer = policy.mAdminMap.get(outgoingReceiver);
3706         final int oldAdminUid = adminToTransfer.getUid();
3707 
3708         adminToTransfer.transfer(incomingDeviceInfo);
3709         policy.mAdminMap.remove(outgoingReceiver);
3710         policy.mAdminMap.put(incomingReceiver, adminToTransfer);
3711         if (policy.mPasswordOwner == oldAdminUid) {
3712             policy.mPasswordOwner = adminToTransfer.getUid();
3713         }
3714 
3715         saveSettingsLocked(userHandle);
3716         sendAdminCommandLocked(adminToTransfer, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
3717                 null, null);
3718     }
3719 
checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info, DevicePolicyData policy)3720     private void checkActiveAdminPrecondition(ComponentName adminReceiver, DeviceAdminInfo info,
3721             DevicePolicyData policy) {
3722         if (info == null) {
3723             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
3724         }
3725         if (!info.getActivityInfo().applicationInfo.isInternal()) {
3726             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
3727                     + adminReceiver);
3728         }
3729         if (info.getActivityInfo().applicationInfo.isInstantApp()) {
3730             throw new IllegalArgumentException("Instant apps cannot be device admins: "
3731                     + adminReceiver);
3732         }
3733         if (policy.mRemovingAdmins.contains(adminReceiver)) {
3734             throw new IllegalArgumentException(
3735                     "Trying to set an admin which is being removed");
3736         }
3737     }
3738 
3739     @Override
isAdminActive(ComponentName adminReceiver, int userHandle)3740     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
3741         if (!mHasFeature) {
3742             return false;
3743         }
3744         enforceFullCrossUsersPermission(userHandle);
3745         synchronized (getLockObject()) {
3746             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
3747         }
3748     }
3749 
3750     @Override
isRemovingAdmin(ComponentName adminReceiver, int userHandle)3751     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
3752         if (!mHasFeature) {
3753             return false;
3754         }
3755         enforceFullCrossUsersPermission(userHandle);
3756         synchronized (getLockObject()) {
3757             DevicePolicyData policyData = getUserData(userHandle);
3758             return policyData.mRemovingAdmins.contains(adminReceiver);
3759         }
3760     }
3761 
3762     @Override
hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle)3763     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
3764         if (!mHasFeature) {
3765             return false;
3766         }
3767         enforceFullCrossUsersPermission(userHandle);
3768         synchronized (getLockObject()) {
3769             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3770             if (administrator == null) {
3771                 throw new SecurityException("No active admin " + adminReceiver);
3772             }
3773             return administrator.info.usesPolicy(policyId);
3774         }
3775     }
3776 
3777     @Override
3778     @SuppressWarnings("unchecked")
getActiveAdmins(int userHandle)3779     public List<ComponentName> getActiveAdmins(int userHandle) {
3780         if (!mHasFeature) {
3781             return Collections.EMPTY_LIST;
3782         }
3783 
3784         enforceFullCrossUsersPermission(userHandle);
3785         synchronized (getLockObject()) {
3786             DevicePolicyData policy = getUserData(userHandle);
3787             final int N = policy.mAdminList.size();
3788             if (N <= 0) {
3789                 return null;
3790             }
3791             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
3792             for (int i=0; i<N; i++) {
3793                 res.add(policy.mAdminList.get(i).info.getComponent());
3794             }
3795             return res;
3796         }
3797     }
3798 
3799     @Override
packageHasActiveAdmins(String packageName, int userHandle)3800     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
3801         if (!mHasFeature) {
3802             return false;
3803         }
3804         enforceFullCrossUsersPermission(userHandle);
3805         synchronized (getLockObject()) {
3806             DevicePolicyData policy = getUserData(userHandle);
3807             final int N = policy.mAdminList.size();
3808             for (int i=0; i<N; i++) {
3809                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
3810                     return true;
3811                 }
3812             }
3813             return false;
3814         }
3815     }
3816 
3817     @Override
forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle)3818     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
3819         if (!mHasFeature) {
3820             return;
3821         }
3822         Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
3823         enforceShell("forceRemoveActiveAdmin");
3824         long ident = mInjector.binderClearCallingIdentity();
3825         try {
3826             synchronized (getLockObject()) {
3827                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
3828                     throw new SecurityException("Attempt to remove non-test admin "
3829                             + adminReceiver + " " + userHandle);
3830                 }
3831 
3832                 // If admin is a device or profile owner tidy that up first.
3833                 if (isDeviceOwner(adminReceiver, userHandle)) {
3834                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3835                 }
3836                 if (isProfileOwner(adminReceiver, userHandle)) {
3837                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3838                             userHandle, /* parent */ false);
3839                     clearProfileOwnerLocked(admin, userHandle);
3840                 }
3841             }
3842             // Remove the admin skipping sending the broadcast.
3843             removeAdminArtifacts(adminReceiver, userHandle);
3844             Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3845         } finally {
3846             mInjector.binderRestoreCallingIdentity(ident);
3847         }
3848     }
3849 
clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle)3850     private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) {
3851         // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state
3852         if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) {
3853             mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle);
3854         }
3855     }
3856 
3857     /**
3858      * Return if a given package has testOnly="true", in which case we'll relax certain rules
3859      * for CTS.
3860      *
3861      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3862      * to check wehter an active admin is test-only or not.
3863      *
3864      * The system allows this flag to be changed when an app is updated, which is not good
3865      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3866      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3867      */
isPackageTestOnly(String packageName, int userHandle)3868     private boolean isPackageTestOnly(String packageName, int userHandle) {
3869         final ApplicationInfo ai;
3870         try {
3871             ai = mInjector.getIPackageManager().getApplicationInfo(packageName,
3872                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
3873                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3874         } catch (RemoteException e) {
3875             throw new IllegalStateException(e);
3876         }
3877         if (ai == null) {
3878             throw new IllegalStateException("Couldn't find package: "
3879                     + packageName + " on user " + userHandle);
3880         }
3881         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3882     }
3883 
3884     /**
3885      * See {@link #isPackageTestOnly}.
3886      */
isAdminTestOnlyLocked(ComponentName who, int userHandle)3887     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3888         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3889         return (admin != null) && admin.testOnlyAdmin;
3890     }
3891 
enforceShell(String method)3892     private void enforceShell(String method) {
3893         final int callingUid = mInjector.binderGetCallingUid();
3894         if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3895             throw new SecurityException("Non-shell user attempted to call " + method);
3896         }
3897     }
3898 
3899     @Override
removeActiveAdmin(ComponentName adminReceiver, int userHandle)3900     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3901         if (!mHasFeature) {
3902             return;
3903         }
3904         enforceFullCrossUsersPermission(userHandle);
3905         enforceUserUnlocked(userHandle);
3906         synchronized (getLockObject()) {
3907             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3908             if (admin == null) {
3909                 return;
3910             }
3911             // Active device/profile owners must remain active admins.
3912             if (isDeviceOwner(adminReceiver, userHandle)
3913                     || isProfileOwner(adminReceiver, userHandle)) {
3914                 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3915                         adminReceiver);
3916                 return;
3917             }
3918             if (admin.getUid() != mInjector.binderGetCallingUid()) {
3919                 mContext.enforceCallingOrSelfPermission(
3920                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3921             }
3922             long ident = mInjector.binderClearCallingIdentity();
3923             try {
3924                 removeActiveAdminLocked(adminReceiver, userHandle);
3925             } finally {
3926                 mInjector.binderRestoreCallingIdentity(ident);
3927             }
3928         }
3929     }
3930 
3931     @Override
isSeparateProfileChallengeAllowed(int userHandle)3932     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3933         if (!isCallerWithSystemUid()) {
3934             throw new SecurityException("Caller must be system");
3935         }
3936         ComponentName profileOwner = getProfileOwner(userHandle);
3937         // Profile challenge is supported on N or newer release.
3938         return profileOwner != null &&
3939                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3940     }
3941 
3942     @Override
setPasswordQuality(ComponentName who, int quality, boolean parent)3943     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3944         if (!mHasFeature) {
3945             return;
3946         }
3947         Preconditions.checkNotNull(who, "ComponentName is null");
3948         validateQualityConstant(quality);
3949 
3950         final int userId = mInjector.userHandleGetCallingUserId();
3951         synchronized (getLockObject()) {
3952             ActiveAdmin ap = getActiveAdminForCallerLocked(
3953                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3954             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
3955             if (metrics.quality != quality) {
3956                 metrics.quality = quality;
3957                 updatePasswordValidityCheckpointLocked(userId, parent);
3958                 saveSettingsLocked(userId);
3959             }
3960             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
3961         }
3962     }
3963 
3964     /**
3965      * Updates a flag that tells us whether the user's password currently satisfies the
3966      * requirements set by all of the user's active admins. The flag is updated both in memory
3967      * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag
3968      * be the correct one upon boot.
3969      * This should be called whenever the password or the admin policies have changed.
3970      */
updatePasswordValidityCheckpointLocked(int userHandle, boolean parent)3971     private void updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
3972         final int credentialOwner = getCredentialOwner(userHandle, parent);
3973         DevicePolicyData policy = getUserData(credentialOwner);
3974         PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
3975         if (metrics == null) {
3976             metrics = new PasswordMetrics();
3977         }
3978         policy.mPasswordValidAtLastCheckpoint =
3979                 isPasswordSufficientForUserWithoutCheckpointLocked(
3980                         metrics, userHandle, parent);
3981 
3982         saveSettingsLocked(credentialOwner);
3983     }
3984 
3985     @Override
getPasswordQuality(ComponentName who, int userHandle, boolean parent)3986     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3987         if (!mHasFeature) {
3988             return PASSWORD_QUALITY_UNSPECIFIED;
3989         }
3990         enforceFullCrossUsersPermission(userHandle);
3991         synchronized (getLockObject()) {
3992             int mode = PASSWORD_QUALITY_UNSPECIFIED;
3993 
3994             if (who != null) {
3995                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3996                 return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3997             }
3998 
3999             // Return the strictest policy across all participating admins.
4000             List<ActiveAdmin> admins =
4001                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4002             final int N = admins.size();
4003             for (int i = 0; i < N; i++) {
4004                 ActiveAdmin admin = admins.get(i);
4005                 if (mode < admin.minimumPasswordMetrics.quality) {
4006                     mode = admin.minimumPasswordMetrics.quality;
4007                 }
4008             }
4009             return mode;
4010         }
4011     }
4012 
getActiveAdminsForLockscreenPoliciesLocked( int userHandle, boolean parent)4013     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
4014             int userHandle, boolean parent) {
4015         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
4016             // If this user has a separate challenge, only return its restrictions.
4017             return getUserDataUnchecked(userHandle).mAdminList;
4018         } else {
4019             // Return all admins for this user and the profiles that are visible from this
4020             // user that do not use a separate work challenge.
4021             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4022             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4023                 DevicePolicyData policy = getUserData(userInfo.id);
4024                 if (!userInfo.isManagedProfile()) {
4025                     admins.addAll(policy.mAdminList);
4026                 } else {
4027                     // For managed profiles, we always include the policies set on the parent
4028                     // profile. Additionally, we include the ones set on the managed profile
4029                     // if no separate challenge is in place.
4030                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
4031                     final int N = policy.mAdminList.size();
4032                     for (int i = 0; i < N; i++) {
4033                         ActiveAdmin admin = policy.mAdminList.get(i);
4034                         if (admin.hasParentActiveAdmin()) {
4035                             admins.add(admin.getParentActiveAdmin());
4036                         }
4037                         if (!hasSeparateChallenge) {
4038                             admins.add(admin);
4039                         }
4040                     }
4041                 }
4042             }
4043             return admins;
4044         }
4045     }
4046 
isSeparateProfileChallengeEnabled(int userHandle)4047     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4048         long ident = mInjector.binderClearCallingIdentity();
4049         try {
4050             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
4051         } finally {
4052             mInjector.binderRestoreCallingIdentity(ident);
4053         }
4054     }
4055 
4056     @Override
setPasswordMinimumLength(ComponentName who, int length, boolean parent)4057     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4058         if (!mHasFeature) {
4059             return;
4060         }
4061         Preconditions.checkNotNull(who, "ComponentName is null");
4062         final int userId = mInjector.userHandleGetCallingUserId();
4063         synchronized (getLockObject()) {
4064             ActiveAdmin ap = getActiveAdminForCallerLocked(
4065                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4066             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4067             if (metrics.length != length) {
4068                 metrics.length = length;
4069                 updatePasswordValidityCheckpointLocked(userId, parent);
4070                 saveSettingsLocked(userId);
4071             }
4072             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4073         }
4074     }
4075 
4076     @Override
getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent)4077     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4078         return getStrictestPasswordRequirement(who, userHandle, parent,
4079                 admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
4080     }
4081 
4082     @Override
setPasswordHistoryLength(ComponentName who, int length, boolean parent)4083     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4084         if (!mHasFeature) {
4085             return;
4086         }
4087         Preconditions.checkNotNull(who, "ComponentName is null");
4088         final int userId = mInjector.userHandleGetCallingUserId();
4089         synchronized (getLockObject()) {
4090             ActiveAdmin ap = getActiveAdminForCallerLocked(
4091                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4092             if (ap.passwordHistoryLength != length) {
4093                 ap.passwordHistoryLength = length;
4094                 updatePasswordValidityCheckpointLocked(userId, parent);
4095                 saveSettingsLocked(userId);
4096             }
4097         }
4098         if (SecurityLog.isLoggingEnabled()) {
4099             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4100             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4101                     who.getPackageName(), userId, affectedUserId, length);
4102         }
4103     }
4104 
4105     @Override
getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent)4106     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4107         return getStrictestPasswordRequirement(who, userHandle, parent,
4108                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4109     }
4110 
4111     @Override
setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent)4112     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
4113         if (!mHasFeature) {
4114             return;
4115         }
4116         Preconditions.checkNotNull(who, "ComponentName is null");
4117         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4118         final int userHandle = mInjector.userHandleGetCallingUserId();
4119         synchronized (getLockObject()) {
4120             ActiveAdmin ap = getActiveAdminForCallerLocked(
4121                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4122             // Calling this API automatically bumps the expiration date
4123             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4124             ap.passwordExpirationDate = expiration;
4125             ap.passwordExpirationTimeout = timeout;
4126             if (timeout > 0L) {
4127                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4128                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4129                         .format(new Date(expiration)));
4130             }
4131             saveSettingsLocked(userHandle);
4132 
4133             // in case this is the first one, set the alarm on the appropriate user.
4134             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4135         }
4136         if (SecurityLog.isLoggingEnabled()) {
4137             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4138             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(),
4139                     userHandle, affectedUserId, timeout);
4140         }
4141     }
4142 
4143     /**
4144      * Return a single admin's expiration cycle time, or the min of all cycle times.
4145      * Returns 0 if not configured.
4146      */
4147     @Override
getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent)4148     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4149         if (!mHasFeature) {
4150             return 0L;
4151         }
4152         enforceFullCrossUsersPermission(userHandle);
4153         synchronized (getLockObject()) {
4154             long timeout = 0L;
4155 
4156             if (who != null) {
4157                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4158                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4159             }
4160 
4161             // Return the strictest policy across all participating admins.
4162             List<ActiveAdmin> admins =
4163                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4164             final int N = admins.size();
4165             for (int i = 0; i < N; i++) {
4166                 ActiveAdmin admin = admins.get(i);
4167                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4168                         && timeout > admin.passwordExpirationTimeout)) {
4169                     timeout = admin.passwordExpirationTimeout;
4170                 }
4171             }
4172             return timeout;
4173         }
4174     }
4175 
4176     @Override
addCrossProfileWidgetProvider(ComponentName admin, String packageName)4177     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4178         final int userId = UserHandle.getCallingUserId();
4179         List<String> changedProviders = null;
4180 
4181         synchronized (getLockObject()) {
4182             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4183                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4184             if (activeAdmin.crossProfileWidgetProviders == null) {
4185                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4186             }
4187             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4188             if (!providers.contains(packageName)) {
4189                 providers.add(packageName);
4190                 changedProviders = new ArrayList<>(providers);
4191                 saveSettingsLocked(userId);
4192             }
4193         }
4194 
4195         if (changedProviders != null) {
4196             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4197             return true;
4198         }
4199 
4200         return false;
4201     }
4202 
4203     @Override
removeCrossProfileWidgetProvider(ComponentName admin, String packageName)4204     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4205         final int userId = UserHandle.getCallingUserId();
4206         List<String> changedProviders = null;
4207 
4208         synchronized (getLockObject()) {
4209             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4210                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4211             if (activeAdmin.crossProfileWidgetProviders == null
4212                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4213                 return false;
4214             }
4215             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4216             if (providers.remove(packageName)) {
4217                 changedProviders = new ArrayList<>(providers);
4218                 saveSettingsLocked(userId);
4219             }
4220         }
4221 
4222         if (changedProviders != null) {
4223             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4224             return true;
4225         }
4226 
4227         return false;
4228     }
4229 
4230     @Override
getCrossProfileWidgetProviders(ComponentName admin)4231     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4232         synchronized (getLockObject()) {
4233             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4234                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4235             if (activeAdmin.crossProfileWidgetProviders == null
4236                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4237                 return null;
4238             }
4239             if (mInjector.binderIsCallingUidMyUid()) {
4240                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4241             } else {
4242                 return activeAdmin.crossProfileWidgetProviders;
4243             }
4244         }
4245     }
4246 
4247     /**
4248      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4249      * Returns 0 if not configured.
4250      */
getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent)4251     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4252         long timeout = 0L;
4253 
4254         if (who != null) {
4255             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4256             return admin != null ? admin.passwordExpirationDate : timeout;
4257         }
4258 
4259         // Return the strictest policy across all participating admins.
4260         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4261         final int N = admins.size();
4262         for (int i = 0; i < N; i++) {
4263             ActiveAdmin admin = admins.get(i);
4264             if (timeout == 0L || (admin.passwordExpirationDate != 0
4265                     && timeout > admin.passwordExpirationDate)) {
4266                 timeout = admin.passwordExpirationDate;
4267             }
4268         }
4269         return timeout;
4270     }
4271 
4272     @Override
getPasswordExpiration(ComponentName who, int userHandle, boolean parent)4273     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4274         if (!mHasFeature) {
4275             return 0L;
4276         }
4277         enforceFullCrossUsersPermission(userHandle);
4278         synchronized (getLockObject()) {
4279             return getPasswordExpirationLocked(who, userHandle, parent);
4280         }
4281     }
4282 
4283     @Override
setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent)4284     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4285         if (!mHasFeature) {
4286             return;
4287         }
4288         Preconditions.checkNotNull(who, "ComponentName is null");
4289         final int userId = mInjector.userHandleGetCallingUserId();
4290         synchronized (getLockObject()) {
4291             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4292                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4293             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4294             if (metrics.upperCase != length) {
4295                 metrics.upperCase = length;
4296                 updatePasswordValidityCheckpointLocked(userId, parent);
4297                 saveSettingsLocked(userId);
4298             }
4299             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4300         }
4301     }
4302 
4303     @Override
getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent)4304     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4305         return getStrictestPasswordRequirement(who, userHandle, parent,
4306                 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX);
4307     }
4308 
4309     @Override
setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent)4310     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4311         Preconditions.checkNotNull(who, "ComponentName is null");
4312         final int userId = mInjector.userHandleGetCallingUserId();
4313         synchronized (getLockObject()) {
4314             ActiveAdmin ap = getActiveAdminForCallerLocked(
4315                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4316             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4317             if (metrics.lowerCase != length) {
4318                 metrics.lowerCase = length;
4319                 updatePasswordValidityCheckpointLocked(userId, parent);
4320                 saveSettingsLocked(userId);
4321             }
4322             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4323         }
4324     }
4325 
4326     @Override
getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent)4327     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4328         return getStrictestPasswordRequirement(who, userHandle, parent,
4329                 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX);
4330     }
4331 
4332     @Override
setPasswordMinimumLetters(ComponentName who, int length, boolean parent)4333     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4334         if (!mHasFeature) {
4335             return;
4336         }
4337         Preconditions.checkNotNull(who, "ComponentName is null");
4338         final int userId = mInjector.userHandleGetCallingUserId();
4339         synchronized (getLockObject()) {
4340             ActiveAdmin ap = getActiveAdminForCallerLocked(
4341                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4342             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4343             if (metrics.letters != length) {
4344                 metrics.letters = length;
4345                 updatePasswordValidityCheckpointLocked(userId, parent);
4346                 saveSettingsLocked(userId);
4347             }
4348             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4349         }
4350     }
4351 
4352     @Override
getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent)4353     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4354         return getStrictestPasswordRequirement(who, userHandle, parent,
4355                 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX);
4356     }
4357 
4358     @Override
setPasswordMinimumNumeric(ComponentName who, int length, boolean parent)4359     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4360         if (!mHasFeature) {
4361             return;
4362         }
4363         Preconditions.checkNotNull(who, "ComponentName is null");
4364         final int userId = mInjector.userHandleGetCallingUserId();
4365         synchronized (getLockObject()) {
4366             ActiveAdmin ap = getActiveAdminForCallerLocked(
4367                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4368             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4369             if (metrics.numeric != length) {
4370                 metrics.numeric = length;
4371                 updatePasswordValidityCheckpointLocked(userId, parent);
4372                 saveSettingsLocked(userId);
4373             }
4374             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4375         }
4376     }
4377 
4378     @Override
getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent)4379     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
4380         return getStrictestPasswordRequirement(who, userHandle, parent,
4381                 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX);
4382     }
4383 
4384     @Override
setPasswordMinimumSymbols(ComponentName who, int length, boolean parent)4385     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
4386         if (!mHasFeature) {
4387             return;
4388         }
4389         Preconditions.checkNotNull(who, "ComponentName is null");
4390         final int userId = mInjector.userHandleGetCallingUserId();
4391         synchronized (getLockObject()) {
4392             ActiveAdmin ap = getActiveAdminForCallerLocked(
4393                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4394             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4395             if (metrics.symbols != length) {
4396                 ap.minimumPasswordMetrics.symbols = length;
4397                 updatePasswordValidityCheckpointLocked(userId, parent);
4398                 saveSettingsLocked(userId);
4399             }
4400             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4401         }
4402     }
4403 
4404     @Override
getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent)4405     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4406         return getStrictestPasswordRequirement(who, userHandle, parent,
4407                 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX);
4408     }
4409 
4410     @Override
setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent)4411     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4412         if (!mHasFeature) {
4413             return;
4414         }
4415         Preconditions.checkNotNull(who, "ComponentName is null");
4416         final int userId = mInjector.userHandleGetCallingUserId();
4417         synchronized (getLockObject()) {
4418             ActiveAdmin ap = getActiveAdminForCallerLocked(
4419                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4420             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4421             if (metrics.nonLetter != length) {
4422                 ap.minimumPasswordMetrics.nonLetter = length;
4423                 updatePasswordValidityCheckpointLocked(userId, parent);
4424                 saveSettingsLocked(userId);
4425             }
4426             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4427         }
4428     }
4429 
4430     @Override
getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent)4431     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4432         return getStrictestPasswordRequirement(who, userHandle, parent,
4433                 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX);
4434     }
4435 
4436     /**
4437      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4438      */
getStrictestPasswordRequirement(ComponentName who, int userHandle, boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality)4439     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4440             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4441         if (!mHasFeature) {
4442             return 0;
4443         }
4444         enforceFullCrossUsersPermission(userHandle);
4445         synchronized (getLockObject()) {
4446             if (who != null) {
4447                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4448                 return admin != null ? getter.apply(admin) : 0;
4449             }
4450 
4451             int maxValue = 0;
4452             final List<ActiveAdmin> admins =
4453                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4454             final int N = admins.size();
4455             for (int i = 0; i < N; i++) {
4456                 final ActiveAdmin admin = admins.get(i);
4457                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4458                     continue;
4459                 }
4460                 final Integer adminValue = getter.apply(admin);
4461                 if (adminValue > maxValue) {
4462                     maxValue = adminValue;
4463                 }
4464             }
4465             return maxValue;
4466         }
4467     }
4468 
4469     @Override
isActivePasswordSufficient(int userHandle, boolean parent)4470     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4471         if (!mHasFeature) {
4472             return true;
4473         }
4474         enforceFullCrossUsersPermission(userHandle);
4475         enforceUserUnlocked(userHandle, parent);
4476 
4477         synchronized (getLockObject()) {
4478             // This API can only be called by an active device admin,
4479             // so try to retrieve it to check that the caller is one.
4480             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4481             int credentialOwner = getCredentialOwner(userHandle, parent);
4482             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4483             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4484             return isActivePasswordSufficientForUserLocked(
4485                     policy.mPasswordValidAtLastCheckpoint, metrics, userHandle, parent);
4486         }
4487     }
4488 
4489     @Override
isUsingUnifiedPassword(ComponentName admin)4490     public boolean isUsingUnifiedPassword(ComponentName admin) {
4491         if (!mHasFeature) {
4492             return true;
4493         }
4494         final int userId = mInjector.userHandleGetCallingUserId();
4495         enforceProfileOrDeviceOwner(admin);
4496         enforceManagedProfile(userId, "query unified challenge status");
4497         return !isSeparateProfileChallengeEnabled(userId);
4498     }
4499 
4500     @Override
isProfileActivePasswordSufficientForParent(int userHandle)4501     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4502         if (!mHasFeature) {
4503             return true;
4504         }
4505         enforceFullCrossUsersPermission(userHandle);
4506         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4507 
4508         synchronized (getLockObject()) {
4509             final int targetUser = getProfileParentId(userHandle);
4510             enforceUserUnlocked(targetUser, false);
4511             int credentialOwner = getCredentialOwner(userHandle, false);
4512             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4513             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4514             return isActivePasswordSufficientForUserLocked(
4515                     policy.mPasswordValidAtLastCheckpoint, metrics, targetUser, false);
4516         }
4517     }
4518 
isActivePasswordSufficientForUserLocked( boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, boolean parent)4519     private boolean isActivePasswordSufficientForUserLocked(
4520             boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle,
4521             boolean parent) {
4522         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
4523             // Before user enters their password for the first time after a reboot, return the
4524             // value of this flag, which tells us whether the password was valid the last time
4525             // settings were saved.  If DPC changes password requirements on boot so that the
4526             // current password no longer meets the requirements, this value will be stale until
4527             // the next time the password is entered.
4528             return passwordValidAtLastCheckpoint;
4529         }
4530 
4531         if (metrics == null) {
4532             // This could happen if the user never had a password set, for example, so
4533             // setActivePasswordState has never been called for it.
4534             metrics = new PasswordMetrics();
4535         }
4536         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle, parent);
4537     }
4538 
4539     /**
4540      * Returns {@code true} if the password represented by the {@code passwordMetrics} argument
4541      * sufficiently fulfills the password requirements for the user corresponding to
4542      * {@code userHandle} (or its parent, if {@code parent} is set to {@code true}).
4543      */
isPasswordSufficientForUserWithoutCheckpointLocked( PasswordMetrics passwordMetrics, int userHandle, boolean parent)4544     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
4545             PasswordMetrics passwordMetrics, int userHandle, boolean parent) {
4546         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4547 
4548         if (passwordMetrics.quality < requiredPasswordQuality) {
4549             return false;
4550         }
4551         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4552                 && passwordMetrics.length < getPasswordMinimumLength(
4553                         null, userHandle, parent)) {
4554             return false;
4555         }
4556         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4557             return true;
4558         }
4559         return passwordMetrics.upperCase >= getPasswordMinimumUpperCase(
4560                     null, userHandle, parent)
4561                 && passwordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4562                         null, userHandle, parent)
4563                 && passwordMetrics.letters >= getPasswordMinimumLetters(
4564                         null, userHandle, parent)
4565                 && passwordMetrics.numeric >= getPasswordMinimumNumeric(
4566                         null, userHandle, parent)
4567                 && passwordMetrics.symbols >= getPasswordMinimumSymbols(
4568                         null, userHandle, parent)
4569                 && passwordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4570                         null, userHandle, parent);
4571     }
4572 
4573     @Override
getCurrentFailedPasswordAttempts(int userHandle, boolean parent)4574     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4575         enforceFullCrossUsersPermission(userHandle);
4576         synchronized (getLockObject()) {
4577             if (!isCallerWithSystemUid()) {
4578                 // This API can only be called by an active device admin,
4579                 // so try to retrieve it to check that the caller is one.
4580                 getActiveAdminForCallerLocked(
4581                         null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4582             }
4583 
4584             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4585 
4586             return policy.mFailedPasswordAttempts;
4587         }
4588     }
4589 
4590     @Override
setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent)4591     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4592         if (!mHasFeature) {
4593             return;
4594         }
4595         Preconditions.checkNotNull(who, "ComponentName is null");
4596         final int userId = mInjector.userHandleGetCallingUserId();
4597         synchronized (getLockObject()) {
4598             // This API can only be called by an active device admin,
4599             // so try to retrieve it to check that the caller is one.
4600             getActiveAdminForCallerLocked(
4601                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4602             ActiveAdmin ap = getActiveAdminForCallerLocked(
4603                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4604             if (ap.maximumFailedPasswordsForWipe != num) {
4605                 ap.maximumFailedPasswordsForWipe = num;
4606                 saveSettingsLocked(userId);
4607             }
4608         }
4609         if (SecurityLog.isLoggingEnabled()) {
4610             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4611             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(),
4612                     userId, affectedUserId, num);
4613         }
4614     }
4615 
4616     @Override
getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent)4617     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4618         if (!mHasFeature) {
4619             return 0;
4620         }
4621         enforceFullCrossUsersPermission(userHandle);
4622         synchronized (getLockObject()) {
4623             ActiveAdmin admin = (who != null)
4624                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4625                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4626             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4627         }
4628     }
4629 
4630     @Override
getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent)4631     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4632         if (!mHasFeature) {
4633             return UserHandle.USER_NULL;
4634         }
4635         enforceFullCrossUsersPermission(userHandle);
4636         synchronized (getLockObject()) {
4637             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4638                     userHandle, parent);
4639             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4640         }
4641     }
4642 
4643     /**
4644      * Returns the admin with the strictest policy on maximum failed passwords for:
4645      * <ul>
4646      *   <li>this user if it has a separate profile challenge, or
4647      *   <li>this user and all profiles that don't have their own challenge otherwise.
4648      * </ul>
4649      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4650      * the primary profile.
4651      * Returns {@code null} if no participating admin has that policy set.
4652      */
getAdminWithMinimumFailedPasswordsForWipeLocked( int userHandle, boolean parent)4653     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4654             int userHandle, boolean parent) {
4655         int count = 0;
4656         ActiveAdmin strictestAdmin = null;
4657 
4658         // Return the strictest policy across all participating admins.
4659         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4660         final int N = admins.size();
4661         for (int i = 0; i < N; i++) {
4662             ActiveAdmin admin = admins.get(i);
4663             if (admin.maximumFailedPasswordsForWipe ==
4664                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4665                 continue;  // No max number of failed passwords policy set for this profile.
4666             }
4667 
4668             // We always favor the primary profile if several profiles have the same value set.
4669             int userId = admin.getUserHandle().getIdentifier();
4670             if (count == 0 ||
4671                     count > admin.maximumFailedPasswordsForWipe ||
4672                     (count == admin.maximumFailedPasswordsForWipe &&
4673                             getUserInfo(userId).isPrimary())) {
4674                 count = admin.maximumFailedPasswordsForWipe;
4675                 strictestAdmin = admin;
4676             }
4677         }
4678         return strictestAdmin;
4679     }
4680 
getUserInfo(@serIdInt int userId)4681     private UserInfo getUserInfo(@UserIdInt int userId) {
4682         final long token = mInjector.binderClearCallingIdentity();
4683         try {
4684             return mUserManager.getUserInfo(userId);
4685         } finally {
4686             mInjector.binderRestoreCallingIdentity(token);
4687         }
4688     }
4689 
canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId)4690     private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) {
4691         // Only if the admins targets a pre-O SDK
4692         return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O;
4693     }
4694 
4695     /* PO or DO could do an untrusted reset in certain conditions. */
canUserHaveUntrustedCredentialReset(@serIdInt int userId)4696     private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
4697         synchronized (getLockObject()) {
4698             // An active DO or PO might be able to fo an untrusted credential reset
4699             for (final ActiveAdmin admin : getUserData(userId).mAdminList) {
4700                 if (!isActiveAdminWithPolicyForUserLocked(admin,
4701                           DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) {
4702                     continue;
4703                 }
4704                 if (canPOorDOCallResetPassword(admin, userId)) {
4705                     return true;
4706                 }
4707             }
4708             return false;
4709         }
4710     }
4711     @Override
resetPassword(String passwordOrNull, int flags)4712     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4713         final int callingUid = mInjector.binderGetCallingUid();
4714         final int userHandle = mInjector.userHandleGetCallingUserId();
4715 
4716         String password = passwordOrNull != null ? passwordOrNull : "";
4717 
4718         // Password resetting to empty/null is not allowed for managed profiles.
4719         if (TextUtils.isEmpty(password)) {
4720             enforceNotManagedProfile(userHandle, "clear the active password");
4721         }
4722 
4723         synchronized (getLockObject()) {
4724             // If caller has PO (or DO) it can change the password, so see if that's the case first.
4725             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4726                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4727             final boolean preN;
4728             if (admin != null) {
4729                 if (!canPOorDOCallResetPassword(admin, userHandle)) {
4730                     throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4731                             + " or later");
4732                 }
4733                 preN = getTargetSdk(admin.info.getPackageName(),
4734                         userHandle) <= android.os.Build.VERSION_CODES.M;
4735             } else {
4736                 // Otherwise, make sure the caller has any active admin with the right policy.
4737                 admin = getActiveAdminForCallerLocked(null,
4738                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4739                 preN = getTargetSdk(admin.info.getPackageName(),
4740                         userHandle) <= android.os.Build.VERSION_CODES.M;
4741 
4742                 // As of N, password resetting to empty/null is not allowed anymore.
4743                 // TODO Should we allow DO/PO to set an empty password?
4744                 if (TextUtils.isEmpty(password)) {
4745                     if (!preN) {
4746                         throw new SecurityException("Cannot call with null password");
4747                     } else {
4748                         Slog.e(LOG_TAG, "Cannot call with null password");
4749                         return false;
4750                     }
4751                 }
4752                 // As of N, password cannot be changed by the admin if it is already set.
4753                 if (isLockScreenSecureUnchecked(userHandle)) {
4754                     if (!preN) {
4755                         throw new SecurityException("Admin cannot change current password");
4756                     } else {
4757                         Slog.e(LOG_TAG, "Admin cannot change current password");
4758                         return false;
4759                     }
4760                 }
4761             }
4762             // Do not allow to reset password when current user has a managed profile
4763             if (!isManagedProfile(userHandle)) {
4764                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4765                     if (userInfo.isManagedProfile()) {
4766                         if (!preN) {
4767                             throw new IllegalStateException(
4768                                     "Cannot reset password on user has managed profile");
4769                         } else {
4770                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4771                             return false;
4772                         }
4773                     }
4774                 }
4775             }
4776             // Do not allow to reset password when user is locked
4777             if (!mUserManager.isUserUnlocked(userHandle)) {
4778                 if (!preN) {
4779                     throw new IllegalStateException("Cannot reset password when user is locked");
4780                 } else {
4781                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4782                     return false;
4783                 }
4784             }
4785         }
4786 
4787         return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4788     }
4789 
resetPasswordInternal(String password, long tokenHandle, byte[] token, int flags, int callingUid, int userHandle)4790     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4791             int flags, int callingUid, int userHandle) {
4792         int quality;
4793         synchronized (getLockObject()) {
4794             quality = getPasswordQuality(null, userHandle, /* parent */ false);
4795             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4796                 quality = PASSWORD_QUALITY_UNSPECIFIED;
4797             }
4798             final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4799             final int realQuality = metrics.quality;
4800             if (realQuality < quality
4801                     && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4802                 Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4803                         + Integer.toHexString(realQuality)
4804                         + " does not meet required quality 0x"
4805                         + Integer.toHexString(quality));
4806                 return false;
4807             }
4808             quality = Math.max(realQuality, quality);
4809             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4810             if (password.length() < length) {
4811                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4812                         + " does not meet required length " + length);
4813                 return false;
4814             }
4815             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4816                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4817                 if(metrics.letters < neededLetters) {
4818                     Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4819                             + " does not meet required number of letters " + neededLetters);
4820                     return false;
4821                 }
4822                 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4823                 if (metrics.numeric < neededNumeric) {
4824                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4825                             + " does not meet required number of numerical digits "
4826                             + neededNumeric);
4827                     return false;
4828                 }
4829                 int neededLowerCase = getPasswordMinimumLowerCase(
4830                         null, userHandle, /* parent */ false);
4831                 if (metrics.lowerCase < neededLowerCase) {
4832                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4833                             + metrics.lowerCase
4834                             + " does not meet required number of lowercase letters "
4835                             + neededLowerCase);
4836                     return false;
4837                 }
4838                 int neededUpperCase = getPasswordMinimumUpperCase(
4839                         null, userHandle, /* parent */ false);
4840                 if (metrics.upperCase < neededUpperCase) {
4841                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4842                             + metrics.upperCase
4843                             + " does not meet required number of uppercase letters "
4844                             + neededUpperCase);
4845                     return false;
4846                 }
4847                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4848                 if (metrics.symbols < neededSymbols) {
4849                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4850                             + " does not meet required number of special symbols " + neededSymbols);
4851                     return false;
4852                 }
4853                 int neededNonLetter = getPasswordMinimumNonLetter(
4854                         null, userHandle, /* parent */ false);
4855                 if (metrics.nonLetter < neededNonLetter) {
4856                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4857                             + metrics.nonLetter
4858                             + " does not meet required number of non-letter characters "
4859                             + neededNonLetter);
4860                     return false;
4861                 }
4862             }
4863         }
4864 
4865         DevicePolicyData policy = getUserData(userHandle);
4866         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4867             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4868             return false;
4869         }
4870 
4871         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4872         boolean doNotAskCredentialsOnBoot =
4873                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4874         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4875             setDoNotAskCredentialsOnBoot();
4876         }
4877 
4878         // Don't do this with the lock held, because it is going to call
4879         // back in to the service.
4880         final long ident = mInjector.binderClearCallingIdentity();
4881         final boolean result;
4882         try {
4883             if (token == null) {
4884                 if (!TextUtils.isEmpty(password)) {
4885                     mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4886                 } else {
4887                     mLockPatternUtils.clearLock(null, userHandle);
4888                 }
4889                 result = true;
4890             } else {
4891                 result = mLockPatternUtils.setLockCredentialWithToken(password,
4892                         TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4893                                 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4894                         quality, tokenHandle, token, userHandle);
4895             }
4896             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4897             if (requireEntry) {
4898                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4899                         UserHandle.USER_ALL);
4900             }
4901             synchronized (getLockObject()) {
4902                 int newOwner = requireEntry ? callingUid : -1;
4903                 if (policy.mPasswordOwner != newOwner) {
4904                     policy.mPasswordOwner = newOwner;
4905                     saveSettingsLocked(userHandle);
4906                 }
4907             }
4908         } finally {
4909             mInjector.binderRestoreCallingIdentity(ident);
4910         }
4911         return result;
4912     }
4913 
isLockScreenSecureUnchecked(int userId)4914     private boolean isLockScreenSecureUnchecked(int userId) {
4915         long ident = mInjector.binderClearCallingIdentity();
4916         try {
4917             return mLockPatternUtils.isSecure(userId);
4918         } finally {
4919             mInjector.binderRestoreCallingIdentity(ident);
4920         }
4921     }
4922 
setDoNotAskCredentialsOnBoot()4923     private void setDoNotAskCredentialsOnBoot() {
4924         synchronized (getLockObject()) {
4925             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4926             if (!policyData.doNotAskCredentialsOnBoot) {
4927                 policyData.doNotAskCredentialsOnBoot = true;
4928                 saveSettingsLocked(UserHandle.USER_SYSTEM);
4929             }
4930         }
4931     }
4932 
4933     @Override
getDoNotAskCredentialsOnBoot()4934     public boolean getDoNotAskCredentialsOnBoot() {
4935         mContext.enforceCallingOrSelfPermission(
4936                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4937         synchronized (getLockObject()) {
4938             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4939             return policyData.doNotAskCredentialsOnBoot;
4940         }
4941     }
4942 
4943     @Override
setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent)4944     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4945         if (!mHasFeature) {
4946             return;
4947         }
4948         Preconditions.checkNotNull(who, "ComponentName is null");
4949         final int userHandle = mInjector.userHandleGetCallingUserId();
4950         synchronized (getLockObject()) {
4951             ActiveAdmin ap = getActiveAdminForCallerLocked(
4952                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4953             if (ap.maximumTimeToUnlock != timeMs) {
4954                 ap.maximumTimeToUnlock = timeMs;
4955                 saveSettingsLocked(userHandle);
4956                 updateMaximumTimeToLockLocked(userHandle);
4957             }
4958         }
4959         if (SecurityLog.isLoggingEnabled()) {
4960             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4961             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
4962                     who.getPackageName(), userHandle, affectedUserId, timeMs);
4963         }
4964     }
4965 
updateMaximumTimeToLockLocked(@serIdInt int userId)4966     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
4967         // Update the profile's timeout
4968         if (isManagedProfile(userId)) {
4969             updateProfileLockTimeoutLocked(userId);
4970         }
4971 
4972         final long timeMs;
4973         final long ident = mInjector.binderClearCallingIdentity();
4974         try {
4975             // Update the device timeout
4976             final int parentId = getProfileParentId(userId);
4977             timeMs = getMaximumTimeToLockPolicyFromAdmins(
4978                     getActiveAdminsForLockscreenPoliciesLocked(parentId, false));
4979 
4980             final DevicePolicyData policy = getUserDataUnchecked(parentId);
4981             if (policy.mLastMaximumTimeToLock == timeMs) {
4982                 return;
4983             }
4984             policy.mLastMaximumTimeToLock = timeMs;
4985 
4986             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4987                 // Make sure KEEP_SCREEN_ON is disabled, since that
4988                 // would allow bypassing of the maximum time to lock.
4989                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4990             }
4991         } finally {
4992             mInjector.binderRestoreCallingIdentity(ident);
4993         }
4994 
4995         mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4996                 UserHandle.USER_SYSTEM, timeMs);
4997     }
4998 
updateProfileLockTimeoutLocked(@serIdInt int userId)4999     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
5000         final long timeMs;
5001         if (isSeparateProfileChallengeEnabled(userId)) {
5002             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5003                     getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */));
5004         } else {
5005             timeMs = Long.MAX_VALUE;
5006         }
5007 
5008         final DevicePolicyData policy = getUserDataUnchecked(userId);
5009         if (policy.mLastMaximumTimeToLock == timeMs) {
5010             return;
5011         }
5012         policy.mLastMaximumTimeToLock = timeMs;
5013 
5014         mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5015                 userId, policy.mLastMaximumTimeToLock);
5016     }
5017 
5018     @Override
getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent)5019     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5020         if (!mHasFeature) {
5021             return 0;
5022         }
5023         enforceFullCrossUsersPermission(userHandle);
5024         synchronized (getLockObject()) {
5025             if (who != null) {
5026                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5027                 return admin != null ? admin.maximumTimeToUnlock : 0;
5028             }
5029             // Return the strictest policy across all participating admins.
5030             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5031                     userHandle, parent);
5032             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5033             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5034         }
5035     }
5036 
getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins)5037     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5038         long time = Long.MAX_VALUE;
5039         for (final ActiveAdmin admin : admins) {
5040             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5041                 time = admin.maximumTimeToUnlock;
5042             }
5043         }
5044         return time;
5045     }
5046 
5047     @Override
setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, boolean parent)5048     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
5049             boolean parent) {
5050         if (!mHasFeature) {
5051             return;
5052         }
5053         Preconditions.checkNotNull(who, "ComponentName is null");
5054         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5055         // timeoutMs with value 0 means that the admin doesn't participate
5056         // timeoutMs is clamped to the interval in case the internal constants change in the future
5057         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5058         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5059             timeoutMs = minimumStrongAuthTimeout;
5060         }
5061         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5062             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5063         }
5064 
5065         final int userHandle = mInjector.userHandleGetCallingUserId();
5066         synchronized (getLockObject()) {
5067             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5068                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
5069             if (ap.strongAuthUnlockTimeout != timeoutMs) {
5070                 ap.strongAuthUnlockTimeout = timeoutMs;
5071                 saveSettingsLocked(userHandle);
5072             }
5073         }
5074     }
5075 
5076     /**
5077      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
5078      * admins if who is null.
5079      * Returns 0 if not configured for the provided admin.
5080      */
5081     @Override
getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent)5082     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
5083         if (!mHasFeature) {
5084             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5085         }
5086         enforceFullCrossUsersPermission(userId);
5087         synchronized (getLockObject()) {
5088             if (who != null) {
5089                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
5090                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
5091             }
5092 
5093             // Return the strictest policy across all participating admins.
5094             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
5095 
5096             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5097             for (int i = 0; i < admins.size(); i++) {
5098                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
5099                 if (timeout != 0) { // take only participating admins into account
5100                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
5101                 }
5102             }
5103             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
5104         }
5105     }
5106 
getMinimumStrongAuthTimeoutMs()5107     private long getMinimumStrongAuthTimeoutMs() {
5108         if (!mInjector.isBuildDebuggable()) {
5109             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
5110         }
5111         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
5112         // name cannot be longer than 31 characters
5113         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
5114                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
5115                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
5116     }
5117 
5118     @Override
lockNow(int flags, boolean parent)5119     public void lockNow(int flags, boolean parent) {
5120         if (!mHasFeature) {
5121             return;
5122         }
5123 
5124         final int callingUserId = mInjector.userHandleGetCallingUserId();
5125         synchronized (getLockObject()) {
5126             // This API can only be called by an active device admin,
5127             // so try to retrieve it to check that the caller is one.
5128             final ActiveAdmin admin = getActiveAdminForCallerLocked(
5129                     null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5130 
5131             final long ident = mInjector.binderClearCallingIdentity();
5132             try {
5133                 final ComponentName adminComponent = admin.info.getComponent();
5134                 // Evict key
5135                 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
5136                     enforceManagedProfile(
5137                             callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5138                     if (!isProfileOwner(adminComponent, callingUserId)) {
5139                         throw new SecurityException("Only profile owner admins can set "
5140                                 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5141                     }
5142                     if (parent) {
5143                         throw new IllegalArgumentException(
5144                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
5145                     }
5146                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5147                         throw new UnsupportedOperationException(
5148                                 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
5149                     }
5150                     mUserManager.evictCredentialEncryptionKey(callingUserId);
5151                 }
5152 
5153                 // Lock all users unless this is a managed profile with a separate challenge
5154                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
5155                         ? UserHandle.USER_ALL : callingUserId);
5156                 mLockPatternUtils.requireStrongAuth(
5157                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
5158 
5159                 // Require authentication for the device or profile
5160                 if (userToLock == UserHandle.USER_ALL) {
5161                     // Power off the display
5162                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
5163                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
5164                     mInjector.getIWindowManager().lockNow(null);
5165                 } else {
5166                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
5167                 }
5168 
5169                 if (SecurityLog.isLoggingEnabled()) {
5170                     final int affectedUserId =
5171                             parent ? getProfileParentId(callingUserId) : callingUserId;
5172                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
5173                             adminComponent.getPackageName(), callingUserId, affectedUserId);
5174                 }
5175             } catch (RemoteException e) {
5176             } finally {
5177                 mInjector.binderRestoreCallingIdentity(ident);
5178             }
5179         }
5180     }
5181 
5182     @Override
enforceCanManageCaCerts(ComponentName who, String callerPackage)5183     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
5184         if (who == null) {
5185             if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5186                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
5187             }
5188         } else {
5189             enforceProfileOrDeviceOwner(who);
5190         }
5191     }
5192 
enforceProfileOrDeviceOwner(ComponentName who)5193     private void enforceProfileOrDeviceOwner(ComponentName who) {
5194         synchronized (getLockObject()) {
5195             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5196         }
5197     }
5198 
5199     @Override
approveCaCert(String alias, int userId, boolean approval)5200     public boolean approveCaCert(String alias, int userId, boolean approval) {
5201         enforceManageUsers();
5202         synchronized (getLockObject()) {
5203             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
5204             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
5205             if (!changed) {
5206                 return false;
5207             }
5208             saveSettingsLocked(userId);
5209         }
5210         mCertificateMonitor.onCertificateApprovalsChanged(userId);
5211         return true;
5212     }
5213 
5214     @Override
isCaCertApproved(String alias, int userId)5215     public boolean isCaCertApproved(String alias, int userId) {
5216         enforceManageUsers();
5217         synchronized (getLockObject()) {
5218             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
5219         }
5220     }
5221 
removeCaApprovalsIfNeeded(int userId)5222     private void removeCaApprovalsIfNeeded(int userId) {
5223         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
5224             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
5225             if (userInfo.isManagedProfile()){
5226                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
5227             }
5228             if (!isSecure) {
5229                 synchronized (getLockObject()) {
5230                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
5231                     saveSettingsLocked(userInfo.id);
5232                 }
5233                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
5234             }
5235         }
5236     }
5237 
5238     @Override
installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)5239     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
5240             throws RemoteException {
5241         if (!mHasFeature) {
5242             return false;
5243         }
5244         enforceCanManageCaCerts(admin, callerPackage);
5245 
5246         final String alias;
5247 
5248         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5249         final long id = mInjector.binderClearCallingIdentity();
5250         try {
5251             alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
5252             if (alias == null) {
5253                 Log.w(LOG_TAG, "Problem installing cert");
5254                 return false;
5255             }
5256         } finally {
5257             mInjector.binderRestoreCallingIdentity(id);
5258         }
5259 
5260         synchronized (getLockObject()) {
5261             getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
5262             saveSettingsLocked(userHandle.getIdentifier());
5263         }
5264         return true;
5265     }
5266 
5267     @Override
uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases)5268     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
5269         if (!mHasFeature) {
5270             return;
5271         }
5272         enforceCanManageCaCerts(admin, callerPackage);
5273 
5274         final int userId = mInjector.userHandleGetCallingUserId();
5275         final long id = mInjector.binderClearCallingIdentity();
5276         try {
5277             mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
5278         } finally {
5279             mInjector.binderRestoreCallingIdentity(id);
5280         }
5281 
5282         synchronized (getLockObject()) {
5283             if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
5284                 saveSettingsLocked(userId);
5285             }
5286         }
5287     }
5288 
5289     @Override
installKeyPair(ComponentName who, String callerPackage, byte[] privKey, byte[] cert, byte[] chain, String alias, boolean requestAccess, boolean isUserSelectable)5290     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
5291             byte[] cert, byte[] chain, String alias, boolean requestAccess,
5292             boolean isUserSelectable) {
5293         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5294                 DELEGATION_CERT_INSTALL);
5295 
5296 
5297         final int callingUid = mInjector.binderGetCallingUid();
5298         final long id = mInjector.binderClearCallingIdentity();
5299         try {
5300             final KeyChainConnection keyChainConnection =
5301                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
5302             try {
5303                 IKeyChainService keyChain = keyChainConnection.getService();
5304                 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
5305                     return false;
5306                 }
5307                 if (requestAccess) {
5308                     keyChain.setGrant(callingUid, alias, true);
5309                 }
5310                 keyChain.setUserSelectable(alias, isUserSelectable);
5311                 return true;
5312             } catch (RemoteException e) {
5313                 Log.e(LOG_TAG, "Installing certificate", e);
5314             } finally {
5315                 keyChainConnection.close();
5316             }
5317         } catch (InterruptedException e) {
5318             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
5319             Thread.currentThread().interrupt();
5320         } finally {
5321             mInjector.binderRestoreCallingIdentity(id);
5322         }
5323         return false;
5324     }
5325 
5326     @Override
removeKeyPair(ComponentName who, String callerPackage, String alias)5327     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
5328         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5329                 DELEGATION_CERT_INSTALL);
5330 
5331         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5332         final long id = Binder.clearCallingIdentity();
5333         try {
5334             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
5335             try {
5336                 IKeyChainService keyChain = keyChainConnection.getService();
5337                 return keyChain.removeKeyPair(alias);
5338             } catch (RemoteException e) {
5339                 Log.e(LOG_TAG, "Removing keypair", e);
5340             } finally {
5341                 keyChainConnection.close();
5342             }
5343         } catch (InterruptedException e) {
5344             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
5345             Thread.currentThread().interrupt();
5346         } finally {
5347             Binder.restoreCallingIdentity(id);
5348         }
5349         return false;
5350     }
5351 
enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner( ComponentName who, String callerPackage, int callerUid)5352     private void enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(
5353             ComponentName who, String callerPackage, int callerUid) throws SecurityException {
5354         if (who == null) {
5355             if (!mOwners.hasDeviceOwner()) {
5356                 throw new SecurityException("Not in Device Owner mode.");
5357             }
5358             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
5359                 throw new SecurityException("Caller not from device owner user");
5360             }
5361             if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5362                 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() +
5363                         "has no permission to generate keys.");
5364             }
5365         } else {
5366             // Caller provided - check it is the device owner.
5367             synchronized (getLockObject()) {
5368                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5369             }
5370         }
5371     }
5372 
5373     @VisibleForTesting
translateIdAttestationFlags( int idAttestationFlags)5374     public static int[] translateIdAttestationFlags(
5375             int idAttestationFlags) {
5376         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
5377         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
5378         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
5379         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
5380 
5381         int numFlagsSet = Integer.bitCount(idAttestationFlags);
5382         // No flags are set - return null to indicate no device ID attestation information should
5383         // be included in the attestation record.
5384         if (numFlagsSet == 0) {
5385             return null;
5386         }
5387 
5388         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
5389         // no other flag is set. That will lead to inclusion of general device make data in the
5390         // attestation record, but no specific device identifiers.
5391         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
5392             numFlagsSet -= 1;
5393             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
5394         }
5395 
5396         int[] attestationUtilsFlags = new int[numFlagsSet];
5397         int i = 0;
5398         for (Integer idType: idTypeToAttestationFlag.keySet()) {
5399             if ((idType & idAttestationFlags) != 0) {
5400                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
5401             }
5402         }
5403 
5404         return attestationUtilsFlags;
5405     }
5406 
5407     @Override
generateKeyPair(ComponentName who, String callerPackage, String algorithm, ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, KeymasterCertificateChain attestationChain)5408     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
5409             ParcelableKeyGenParameterSpec parcelableKeySpec,
5410             int idAttestationFlags,
5411             KeymasterCertificateChain attestationChain) {
5412         // Get attestation flags, if any.
5413         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
5414         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
5415         final int callingUid = mInjector.binderGetCallingUid();
5416 
5417         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
5418             enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(who, callerPackage, callingUid);
5419         } else {
5420             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5421                     DELEGATION_CERT_INSTALL);
5422         }
5423         final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
5424         final String alias = keySpec.getKeystoreAlias();
5425         if (TextUtils.isEmpty(alias)) {
5426             throw new IllegalArgumentException("Empty alias provided.");
5427         }
5428         // As the caller will be granted access to the key, ensure no UID was specified, as
5429         // it will not have the desired effect.
5430         if (keySpec.getUid() != KeyStore.UID_SELF) {
5431             Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
5432             return false;
5433         }
5434 
5435         if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) {
5436             throw new IllegalArgumentException(
5437                     "Requested Device ID attestation but challenge is empty.");
5438         }
5439 
5440         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5441         final long id = mInjector.binderClearCallingIdentity();
5442         try {
5443             try (KeyChainConnection keyChainConnection =
5444                     KeyChain.bindAsUser(mContext, userHandle)) {
5445                 IKeyChainService keyChain = keyChainConnection.getService();
5446 
5447                 // Copy the provided keySpec, excluding the attestation challenge, which will be
5448                 // used later for requesting key attestation record.
5449                 final KeyGenParameterSpec noAttestationSpec =
5450                     new KeyGenParameterSpec.Builder(keySpec)
5451                         .setAttestationChallenge(null)
5452                         .build();
5453 
5454                 final int generationResult = keyChain.generateKeyPair(algorithm,
5455                     new ParcelableKeyGenParameterSpec(noAttestationSpec));
5456                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
5457                     Log.e(LOG_TAG, String.format(
5458                             "KeyChain failed to generate a keypair, error %d.", generationResult));
5459                     return false;
5460                 }
5461 
5462                 // Set a grant for the caller here so that when the client calls
5463                 // requestPrivateKey, it will be able to get the key from Keystore.
5464                 // Note the use of the calling  UID, since the request for the private
5465                 // key will come from the client's process, so the grant has to be for
5466                 // that UID.
5467                 keyChain.setGrant(callingUid, alias, true);
5468 
5469                 final byte[] attestationChallenge = keySpec.getAttestationChallenge();
5470                 if (attestationChallenge != null) {
5471                     final int attestationResult = keyChain.attestKey(
5472                             alias, attestationChallenge, attestationUtilsFlags, attestationChain);
5473                     if (attestationResult != KeyChain.KEY_ATTESTATION_SUCCESS) {
5474                         Log.e(LOG_TAG, String.format(
5475                                 "Attestation for %s failed (rc=%d), deleting key.",
5476                                 alias, attestationResult));
5477                         keyChain.removeKeyPair(alias);
5478                         if (attestationResult == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) {
5479                             throw new UnsupportedOperationException(
5480                                     "Device does not support Device ID attestation.");
5481                         }
5482                         return false;
5483                     }
5484                 }
5485                 return true;
5486             }
5487         } catch (RemoteException e) {
5488             Log.e(LOG_TAG, "KeyChain error while generating a keypair", e);
5489         } catch (InterruptedException e) {
5490             Log.w(LOG_TAG, "Interrupted while generating keypair", e);
5491             Thread.currentThread().interrupt();
5492         } finally {
5493             mInjector.binderRestoreCallingIdentity(id);
5494         }
5495         return false;
5496     }
5497 
5498     @Override
setKeyPairCertificate(ComponentName who, String callerPackage, String alias, byte[] cert, byte[] chain, boolean isUserSelectable)5499     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
5500             byte[] cert, byte[] chain, boolean isUserSelectable) {
5501         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5502                 DELEGATION_CERT_INSTALL);
5503 
5504         final int callingUid = mInjector.binderGetCallingUid();
5505         final long id = mInjector.binderClearCallingIdentity();
5506         try (final KeyChainConnection keyChainConnection =
5507                 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) {
5508             IKeyChainService keyChain = keyChainConnection.getService();
5509             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
5510                 return false;
5511             }
5512             keyChain.setUserSelectable(alias, isUserSelectable);
5513             return true;
5514         } catch (InterruptedException e) {
5515             Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
5516             Thread.currentThread().interrupt();
5517         } catch (RemoteException e) {
5518             Log.e(LOG_TAG, "Failed setting keypair certificate", e);
5519         } finally {
5520             mInjector.binderRestoreCallingIdentity(id);
5521         }
5522         return false;
5523     }
5524 
5525     @Override
choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, final IBinder response)5526     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
5527             final IBinder response) {
5528         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
5529         if (!isCallerWithSystemUid()) {
5530             return;
5531         }
5532 
5533         final UserHandle caller = mInjector.binderGetCallingUserHandle();
5534         // If there is a profile owner, redirect to that; otherwise query the device owner.
5535         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
5536         if (aliasChooser == null && caller.isSystem()) {
5537             synchronized (getLockObject()) {
5538                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
5539                 if (deviceOwnerAdmin != null) {
5540                     aliasChooser = deviceOwnerAdmin.info.getComponent();
5541                 }
5542             }
5543         }
5544         if (aliasChooser == null) {
5545             sendPrivateKeyAliasResponse(null, response);
5546             return;
5547         }
5548 
5549         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
5550         intent.setComponent(aliasChooser);
5551         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
5552         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
5553         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
5554         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
5555         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5556 
5557         final long id = mInjector.binderClearCallingIdentity();
5558         try {
5559             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
5560                 @Override
5561                 public void onReceive(Context context, Intent intent) {
5562                     final String chosenAlias = getResultData();
5563                     sendPrivateKeyAliasResponse(chosenAlias, response);
5564                 }
5565             }, null, Activity.RESULT_OK, null, null);
5566         } finally {
5567             mInjector.binderRestoreCallingIdentity(id);
5568         }
5569     }
5570 
sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder)5571     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
5572         final IKeyChainAliasCallback keyChainAliasResponse =
5573                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
5574         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
5575         // is oneway, which means it won't block if the recipient lives in another process.
5576         try {
5577             keyChainAliasResponse.alias(alias);
5578         } catch (Exception e) {
5579             // Caller could throw RuntimeException or RemoteException back across processes. Catch
5580             // everything just to be sure.
5581             Log.e(LOG_TAG, "error while responding to callback", e);
5582         }
5583     }
5584 
5585     /**
5586      * Determine whether DPMS should check if a delegate package is already installed before
5587      * granting it new delegations via {@link #setDelegatedScopes}.
5588      */
shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, int targetSdk, List<String> scopes)5589     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
5590             int targetSdk, List<String> scopes) {
5591         // 1) Never skip is installed check from N.
5592         if (targetSdk >= Build.VERSION_CODES.N) {
5593             return true;
5594         }
5595         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
5596         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
5597             return false;
5598         }
5599         // 3) Skip if all previously granted scopes are being cleared.
5600         if (scopes.isEmpty()) {
5601             return false;
5602         }
5603         // Otherwise it should check that delegatePackage is installed.
5604         return true;
5605     }
5606 
5607     /**
5608      * Set the scopes of a device owner or profile owner delegate.
5609      *
5610      * @param who the device owner or profile owner.
5611      * @param delegatePackage the name of the delegate package.
5612      * @param scopes the list of delegation scopes to be given to the delegate package.
5613      */
5614     @Override
setDelegatedScopes(ComponentName who, String delegatePackage, List<String> scopes)5615     public void setDelegatedScopes(ComponentName who, String delegatePackage,
5616             List<String> scopes) throws SecurityException {
5617         Preconditions.checkNotNull(who, "ComponentName is null");
5618         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5619         Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5620         // Remove possible duplicates.
5621         scopes = new ArrayList(new ArraySet(scopes));
5622         // Ensure given scopes are valid.
5623         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5624             throw new IllegalArgumentException("Unexpected delegation scopes");
5625         }
5626 
5627         // Retrieve the user ID of the calling process.
5628         final int userId = mInjector.userHandleGetCallingUserId();
5629         synchronized (getLockObject()) {
5630             // Ensure calling process is device/profile owner.
5631             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5632             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5633             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5634                         getTargetSdk(who.getPackageName(), userId), scopes)) {
5635                 // Throw when the delegate package is not installed.
5636                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
5637                     throw new IllegalArgumentException("Package " + delegatePackage
5638                             + " is not installed on the current user");
5639                 }
5640             }
5641 
5642             // Set the new delegate in user policies.
5643             final DevicePolicyData policy = getUserData(userId);
5644             if (!scopes.isEmpty()) {
5645                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5646             } else {
5647                 // Remove any delegation info if the given scopes list is empty.
5648                 policy.mDelegationMap.remove(delegatePackage);
5649             }
5650 
5651             // Notify delegate package of updates.
5652             final Intent intent = new Intent(
5653                     DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5654             // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5655             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5656             // Limit components this intent resolves to to the delegate package.
5657             intent.setPackage(delegatePackage);
5658             // Include the list of delegated scopes as an extra.
5659             intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5660                     (ArrayList<String>) scopes);
5661             // Send the broadcast.
5662             mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5663 
5664             // Persist updates.
5665             saveSettingsLocked(userId);
5666         }
5667     }
5668 
5669     /**
5670      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5671      *
5672      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5673      * passing in {@code null} as the {@code who} parameter and its own name as the
5674      * {@code delegatepackage}.
5675      *
5676      * @param who the device owner or profile owner, or {@code null} if the caller is
5677      *            {@code delegatePackage}.
5678      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5679      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5680      */
5681     @Override
5682     @NonNull
getDelegatedScopes(ComponentName who, String delegatePackage)5683     public List<String> getDelegatedScopes(ComponentName who,
5684             String delegatePackage) throws SecurityException {
5685         Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5686 
5687         // Retrieve the user ID of the calling process.
5688         final int callingUid = mInjector.binderGetCallingUid();
5689         final int userId = UserHandle.getUserId(callingUid);
5690         synchronized (getLockObject()) {
5691             // Ensure calling process is device/profile owner.
5692             if (who != null) {
5693                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5694             // Or ensure calling process is delegatePackage itself.
5695             } else {
5696                 int uid = 0;
5697                 try {
5698                   uid = mInjector.getPackageManager()
5699                           .getPackageUidAsUser(delegatePackage, userId);
5700                 } catch(NameNotFoundException e) {
5701                 }
5702                 if (uid != callingUid) {
5703                     throw new SecurityException("Caller with uid " + callingUid + " is not "
5704                             + delegatePackage);
5705                 }
5706             }
5707             final DevicePolicyData policy = getUserData(userId);
5708             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5709             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5710             return scopes == null ? Collections.EMPTY_LIST : scopes;
5711         }
5712     }
5713 
5714     /**
5715      * Get a list of  packages that were given a specific delegation scopes by a device owner or
5716      * profile owner.
5717      *
5718      * @param who the device owner or profile owner.
5719      * @param scope the scope whose delegates are to be retrieved.
5720      * @return a list of the delegate packages currently given the {@code scope} delegation.
5721      */
5722     @NonNull
getDelegatePackages(ComponentName who, String scope)5723     public List<String> getDelegatePackages(ComponentName who, String scope)
5724             throws SecurityException {
5725         Preconditions.checkNotNull(who, "ComponentName is null");
5726         Preconditions.checkNotNull(scope, "Scope is null");
5727         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5728             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5729         }
5730 
5731         // Retrieve the user ID of the calling process.
5732         final int userId = mInjector.userHandleGetCallingUserId();
5733         synchronized (getLockObject()) {
5734             // Ensure calling process is device/profile owner.
5735             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5736             final DevicePolicyData policy = getUserData(userId);
5737 
5738             // Create a list to hold the resulting delegate packages.
5739             final List<String> delegatePackagesWithScope = new ArrayList<>();
5740             // Add all delegations containing scope to the result list.
5741             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5742                 if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5743                     delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5744                 }
5745             }
5746             return delegatePackagesWithScope;
5747         }
5748     }
5749 
5750     /**
5751      * Check whether a caller application has been delegated a given scope via
5752      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5753      * device owner.
5754      * <p>
5755      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5756      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5757      * {@link PackageManager#getPackageUidAsUser}.
5758      *
5759      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5760      * @param scope the delegation scope to be checked.
5761      * @return {@code true} if the calling process is a delegate of {@code scope}.
5762      */
isCallerDelegate(String callerPackage, String scope)5763     private boolean isCallerDelegate(String callerPackage, String scope) {
5764         Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5765         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5766             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5767         }
5768 
5769         // Retrieve the UID and user ID of the calling process.
5770         final int callingUid = mInjector.binderGetCallingUid();
5771         final int userId = UserHandle.getUserId(callingUid);
5772         synchronized (getLockObject()) {
5773             // Retrieve user policy data.
5774             final DevicePolicyData policy = getUserData(userId);
5775             // Retrieve the list of delegation scopes granted to callerPackage.
5776             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5777             // Check callingUid only if callerPackage has the required scope delegation.
5778             if (scopes != null && scopes.contains(scope)) {
5779                 try {
5780                     // Retrieve the expected UID for callerPackage.
5781                     final int uid = mInjector.getPackageManager()
5782                             .getPackageUidAsUser(callerPackage, userId);
5783                     // Return true if the caller is actually callerPackage.
5784                     return uid == callingUid;
5785                 } catch (NameNotFoundException e) {
5786                     // Ignore.
5787                 }
5788             }
5789             return false;
5790         }
5791     }
5792 
5793     /**
5794      * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5795      * or if the calling process is not a delegate of the given scope.
5796      *
5797      * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5798      *            {@code scope} delegate.
5799      * @param callerPackage the name of the calling package. Required if {@code who} is
5800      *            {@code null}.
5801      * @param reqPolicy the policy used in the API whose access permission is being checked.
5802      * @param scope the delegation scope corresponding to the API being checked.
5803      * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5804      *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5805      *            of {@code scope}.
5806      */
enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, String scope)5807     private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5808             String scope) {
5809         // If a ComponentName is given ensure it is a device or profile owner according to policy.
5810         if (who != null) {
5811             synchronized (getLockObject()) {
5812                 getActiveAdminForCallerLocked(who, reqPolicy);
5813             }
5814         // If no ComponentName is given ensure calling process has scope delegation.
5815         } else if (!isCallerDelegate(callerPackage, scope)) {
5816             throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5817                     + " is not a delegate of scope " + scope + ".");
5818         }
5819     }
5820 
5821     /**
5822      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5823      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5824      */
setDelegatedScopePreO(ComponentName who, String delegatePackage, String scope)5825     private void setDelegatedScopePreO(ComponentName who,
5826             String delegatePackage, String scope) {
5827         Preconditions.checkNotNull(who, "ComponentName is null");
5828 
5829         final int userId = mInjector.userHandleGetCallingUserId();
5830         synchronized (getLockObject()) {
5831             // Ensure calling process is device/profile owner.
5832             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5833             final DevicePolicyData policy = getUserData(userId);
5834 
5835             if (delegatePackage != null) {
5836                 // Set package as a delegate for scope if it is not already one.
5837                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5838                 if (scopes == null) {
5839                     scopes = new ArrayList<>();
5840                 }
5841                 if (!scopes.contains(scope)) {
5842                     scopes.add(scope);
5843                     setDelegatedScopes(who, delegatePackage, scopes);
5844                 }
5845             }
5846 
5847             // Clear any existing scope delegates.
5848             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5849                 final String currentPackage = policy.mDelegationMap.keyAt(i);
5850                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5851 
5852                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5853                     final List<String> newScopes = new ArrayList(currentScopes);
5854                     newScopes.remove(scope);
5855                     setDelegatedScopes(who, currentPackage, newScopes);
5856                 }
5857             }
5858         }
5859     }
5860 
5861     @Override
setCertInstallerPackage(ComponentName who, String installerPackage)5862     public void setCertInstallerPackage(ComponentName who, String installerPackage)
5863             throws SecurityException {
5864         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5865     }
5866 
5867     @Override
getCertInstallerPackage(ComponentName who)5868     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5869         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5870         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5871     }
5872 
5873     /**
5874      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5875      * not installed and therefore not available.
5876      *
5877      * @throws SecurityException if the caller is not a profile or device owner.
5878      * @throws UnsupportedOperationException if the package does not support being set as always-on.
5879      */
5880     @Override
setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)5881     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5882             throws SecurityException {
5883         enforceProfileOrDeviceOwner(admin);
5884 
5885         final int userId = mInjector.userHandleGetCallingUserId();
5886         final long token = mInjector.binderClearCallingIdentity();
5887         try {
5888             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5889                 return false;
5890             }
5891             ConnectivityManager connectivityManager = (ConnectivityManager)
5892                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5893             if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5894                 throw new UnsupportedOperationException();
5895             }
5896         } finally {
5897             mInjector.binderRestoreCallingIdentity(token);
5898         }
5899         return true;
5900     }
5901 
5902     @Override
getAlwaysOnVpnPackage(ComponentName admin)5903     public String getAlwaysOnVpnPackage(ComponentName admin)
5904             throws SecurityException {
5905         enforceProfileOrDeviceOwner(admin);
5906 
5907         final int userId = mInjector.userHandleGetCallingUserId();
5908         final long token = mInjector.binderClearCallingIdentity();
5909         try{
5910             ConnectivityManager connectivityManager = (ConnectivityManager)
5911                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5912             return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5913         } finally {
5914             mInjector.binderRestoreCallingIdentity(token);
5915         }
5916     }
5917 
forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc)5918     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5919         wtfIfInLock();
5920         boolean success = false;
5921         try {
5922             if (wipeExtRequested) {
5923                 StorageManager sm = (StorageManager) mContext.getSystemService(
5924                     Context.STORAGE_SERVICE);
5925                 sm.wipeAdoptableDisks();
5926             }
5927             mInjector.recoverySystemRebootWipeUserData(
5928                 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5929             success = true;
5930         } catch (IOException | SecurityException e) {
5931             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5932         } finally {
5933             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
5934         }
5935     }
5936 
forceWipeUser(int userId, String wipeReasonForUser)5937     private void forceWipeUser(int userId, String wipeReasonForUser) {
5938         boolean success = false;
5939         try {
5940             IActivityManager am = mInjector.getIActivityManager();
5941             if (am.getCurrentUser().id == userId) {
5942                 am.switchUser(UserHandle.USER_SYSTEM);
5943             }
5944 
5945             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5946             if (!success) {
5947                 Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5948             } else if (isManagedProfile(userId)) {
5949                 sendWipeProfileNotification(wipeReasonForUser);
5950             }
5951         } catch (RemoteException re) {
5952             // Shouldn't happen
5953         } finally {
5954             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
5955         }
5956     }
5957 
5958     @Override
wipeDataWithReason(int flags, String wipeReasonForUser)5959     public void wipeDataWithReason(int flags, String wipeReasonForUser) {
5960         if (!mHasFeature) {
5961             return;
5962         }
5963         Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty");
5964         enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5965 
5966         final ActiveAdmin admin;
5967         synchronized (getLockObject()) {
5968             admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5969         }
5970         String internalReason = "DevicePolicyManager.wipeDataWithReason() from "
5971                 + admin.info.getComponent().flattenToShortString();
5972         wipeDataNoLock(
5973                 admin.info.getComponent(), flags, internalReason, wipeReasonForUser,
5974                 admin.getUserHandle().getIdentifier());
5975     }
5976 
wipeDataNoLock(ComponentName admin, int flags, String internalReason, String wipeReasonForUser, int userId)5977     private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
5978                                 String wipeReasonForUser, int userId) {
5979         wtfIfInLock();
5980 
5981         long ident = mInjector.binderClearCallingIdentity();
5982         try {
5983             // First check whether the admin is allowed to wipe the device/user/profile.
5984             final String restriction;
5985             if (userId == UserHandle.USER_SYSTEM) {
5986                 restriction = UserManager.DISALLOW_FACTORY_RESET;
5987             } else if (isManagedProfile(userId)) {
5988                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5989             } else {
5990                 restriction = UserManager.DISALLOW_REMOVE_USER;
5991             }
5992             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5993                 throw new SecurityException("Cannot wipe data. " + restriction
5994                         + " restriction is set for user " + userId);
5995             }
5996 
5997             if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5998                 if (!isDeviceOwner(admin, userId)) {
5999                     throw new SecurityException(
6000                             "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
6001                 }
6002                 PersistentDataBlockManager manager = (PersistentDataBlockManager)
6003                         mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
6004                 if (manager != null) {
6005                     manager.wipe();
6006                 }
6007             }
6008 
6009             // TODO If split user is enabled and the device owner is set in the primary user
6010             // (rather than system), we should probably trigger factory reset. Current code just
6011             // removes that user (but still clears FRP...)
6012             if (userId == UserHandle.USER_SYSTEM) {
6013                 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (
6014                         flags & WIPE_EXTERNAL_STORAGE) != 0,
6015                         internalReason,
6016                         /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
6017             } else {
6018                 forceWipeUser(userId, wipeReasonForUser);
6019             }
6020         } finally {
6021             mInjector.binderRestoreCallingIdentity(ident);
6022         }
6023     }
6024 
sendWipeProfileNotification(String wipeReasonForUser)6025     private void sendWipeProfileNotification(String wipeReasonForUser) {
6026         Notification notification =
6027                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
6028                         .setSmallIcon(android.R.drawable.stat_sys_warning)
6029                         .setContentTitle(mContext.getString(R.string.work_profile_deleted))
6030                         .setContentText(wipeReasonForUser)
6031                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
6032                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
6033                         .build();
6034         mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
6035     }
6036 
clearWipeProfileNotification()6037     private void clearWipeProfileNotification() {
6038         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
6039     }
6040 
6041     @Override
getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle)6042     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
6043         if (!mHasFeature) {
6044             return;
6045         }
6046         enforceFullCrossUsersPermission(userHandle);
6047         mContext.enforceCallingOrSelfPermission(
6048                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6049 
6050         synchronized (getLockObject()) {
6051             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
6052             if (admin == null) {
6053                 result.sendResult(null);
6054                 return;
6055             }
6056             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
6057             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6058             intent.setComponent(admin.info.getComponent());
6059             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
6060                     null, new BroadcastReceiver() {
6061                 @Override
6062                 public void onReceive(Context context, Intent intent) {
6063                     result.sendResult(getResultExtras(false));
6064                 }
6065             }, null, Activity.RESULT_OK, null, null);
6066         }
6067     }
6068 
6069     /**
6070      * Notify DPMS regarding the metric of the current password. This happens when the user changes
6071      * the password, but also when the user just unlocks the keyguard. In comparison,
6072      * reportPasswordChanged() is only called when the user changes the password.
6073      */
6074     @Override
setActivePasswordState(PasswordMetrics metrics, int userHandle)6075     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
6076         if (!mHasFeature) {
6077             return;
6078         }
6079         enforceFullCrossUsersPermission(userHandle);
6080         mContext.enforceCallingOrSelfPermission(
6081                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6082 
6083         // If the managed profile doesn't have a separate password, set the metrics to default
6084         if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6085             metrics = new PasswordMetrics();
6086         }
6087 
6088         validateQualityConstant(metrics.quality);
6089         synchronized (getLockObject()) {
6090             mUserPasswordMetrics.put(userHandle, metrics);
6091         }
6092     }
6093 
6094     @Override
reportPasswordChanged(@serIdInt int userId)6095     public void reportPasswordChanged(@UserIdInt int userId) {
6096         if (!mHasFeature) {
6097             return;
6098         }
6099         enforceFullCrossUsersPermission(userId);
6100 
6101         // Managed Profile password can only be changed when it has a separate challenge.
6102         if (!isSeparateProfileChallengeEnabled(userId)) {
6103             enforceNotManagedProfile(userId, "set the active password");
6104         }
6105 
6106         mContext.enforceCallingOrSelfPermission(
6107                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6108 
6109         DevicePolicyData policy = getUserData(userId);
6110 
6111         long ident = mInjector.binderClearCallingIdentity();
6112         try {
6113             synchronized (getLockObject()) {
6114                 policy.mFailedPasswordAttempts = 0;
6115                 updatePasswordValidityCheckpointLocked(userId, /* parent */ false);
6116                 saveSettingsLocked(userId);
6117                 updatePasswordExpirationsLocked(userId);
6118                 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
6119 
6120                 // Send a broadcast to each profile using this password as its primary unlock.
6121                 sendAdminCommandForLockscreenPoliciesLocked(
6122                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
6123                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
6124             }
6125             removeCaApprovalsIfNeeded(userId);
6126         } finally {
6127             mInjector.binderRestoreCallingIdentity(ident);
6128         }
6129     }
6130 
6131     /**
6132      * Called any time the device password is updated. Resets all password expiration clocks.
6133      */
updatePasswordExpirationsLocked(int userHandle)6134     private void updatePasswordExpirationsLocked(int userHandle) {
6135         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
6136         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6137                 userHandle, /* parent */ false);
6138         final int N = admins.size();
6139         for (int i = 0; i < N; i++) {
6140             ActiveAdmin admin = admins.get(i);
6141             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
6142                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
6143                 long timeout = admin.passwordExpirationTimeout;
6144                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
6145                 admin.passwordExpirationDate = expiration;
6146             }
6147         }
6148         for (int affectedUserId : affectedUserIds) {
6149             saveSettingsLocked(affectedUserId);
6150         }
6151     }
6152 
6153     @Override
reportFailedPasswordAttempt(int userHandle)6154     public void reportFailedPasswordAttempt(int userHandle) {
6155         enforceFullCrossUsersPermission(userHandle);
6156         if (!isSeparateProfileChallengeEnabled(userHandle)) {
6157             enforceNotManagedProfile(userHandle,
6158                     "report failed password attempt if separate profile challenge is not in place");
6159         }
6160         mContext.enforceCallingOrSelfPermission(
6161                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6162 
6163         boolean wipeData = false;
6164         ActiveAdmin strictestAdmin = null;
6165         final long ident = mInjector.binderClearCallingIdentity();
6166         try {
6167             synchronized (getLockObject()) {
6168                 DevicePolicyData policy = getUserData(userHandle);
6169                 policy.mFailedPasswordAttempts++;
6170                 saveSettingsLocked(userHandle);
6171                 if (mHasFeature) {
6172                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
6173                             userHandle, /* parent */ false);
6174                     int max = strictestAdmin != null
6175                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
6176                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
6177                         wipeData = true;
6178                     }
6179 
6180                     sendAdminCommandForLockscreenPoliciesLocked(
6181                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
6182                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6183                 }
6184             }
6185         } finally {
6186             mInjector.binderRestoreCallingIdentity(ident);
6187         }
6188 
6189         if (wipeData && strictestAdmin != null) {
6190             final int userId = strictestAdmin.getUserHandle().getIdentifier();
6191             Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
6192                     + strictestAdmin.info.getComponent().flattenToShortString()
6193                     + ". Calling wipeData for user " + userId);
6194 
6195             // Attempt to wipe the device/user/profile associated with the admin, as if the
6196             // admin had called wipeData(). That way we can check whether the admin is actually
6197             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
6198             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
6199             // able to do so).
6200             // IMPORTANT: Call without holding the lock to prevent deadlock.
6201             try {
6202                 String wipeReasonForUser = mContext.getString(
6203                         R.string.work_profile_deleted_reason_maximum_password_failure);
6204                 wipeDataNoLock(strictestAdmin.info.getComponent(),
6205                         /*flags=*/ 0,
6206                         /*reason=*/ "reportFailedPasswordAttempt()",
6207                         wipeReasonForUser,
6208                         userId);
6209             } catch (SecurityException e) {
6210                 Slog.w(LOG_TAG, "Failed to wipe user " + userId
6211                         + " after max failed password attempts reached.", e);
6212             }
6213         }
6214 
6215         if (mInjector.securityLogIsLoggingEnabled()) {
6216             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
6217                     /*result*/ 0, /*method strength*/ 1);
6218         }
6219     }
6220 
6221     @Override
reportSuccessfulPasswordAttempt(int userHandle)6222     public void reportSuccessfulPasswordAttempt(int userHandle) {
6223         enforceFullCrossUsersPermission(userHandle);
6224         mContext.enforceCallingOrSelfPermission(
6225                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6226 
6227         synchronized (getLockObject()) {
6228             DevicePolicyData policy = getUserData(userHandle);
6229             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
6230                 long ident = mInjector.binderClearCallingIdentity();
6231                 try {
6232                     policy.mFailedPasswordAttempts = 0;
6233                     policy.mPasswordOwner = -1;
6234                     saveSettingsLocked(userHandle);
6235                     if (mHasFeature) {
6236                         sendAdminCommandForLockscreenPoliciesLocked(
6237                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
6238                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6239                     }
6240                 } finally {
6241                     mInjector.binderRestoreCallingIdentity(ident);
6242                 }
6243             }
6244         }
6245 
6246         if (mInjector.securityLogIsLoggingEnabled()) {
6247             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6248                     /*method strength*/ 1);
6249         }
6250     }
6251 
6252     @Override
reportFailedFingerprintAttempt(int userHandle)6253     public void reportFailedFingerprintAttempt(int userHandle) {
6254         enforceFullCrossUsersPermission(userHandle);
6255         mContext.enforceCallingOrSelfPermission(
6256                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6257         if (mInjector.securityLogIsLoggingEnabled()) {
6258             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
6259                     /*method strength*/ 0);
6260         }
6261     }
6262 
6263     @Override
reportSuccessfulFingerprintAttempt(int userHandle)6264     public void reportSuccessfulFingerprintAttempt(int userHandle) {
6265         enforceFullCrossUsersPermission(userHandle);
6266         mContext.enforceCallingOrSelfPermission(
6267                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6268         if (mInjector.securityLogIsLoggingEnabled()) {
6269             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6270                     /*method strength*/ 0);
6271         }
6272     }
6273 
6274     @Override
reportKeyguardDismissed(int userHandle)6275     public void reportKeyguardDismissed(int userHandle) {
6276         enforceFullCrossUsersPermission(userHandle);
6277         mContext.enforceCallingOrSelfPermission(
6278                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6279 
6280         if (mInjector.securityLogIsLoggingEnabled()) {
6281             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
6282         }
6283     }
6284 
6285     @Override
reportKeyguardSecured(int userHandle)6286     public void reportKeyguardSecured(int userHandle) {
6287         enforceFullCrossUsersPermission(userHandle);
6288         mContext.enforceCallingOrSelfPermission(
6289                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6290 
6291         if (mInjector.securityLogIsLoggingEnabled()) {
6292             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
6293         }
6294     }
6295 
6296     @Override
setGlobalProxy(ComponentName who, String proxySpec, String exclusionList)6297     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
6298             String exclusionList) {
6299         if (!mHasFeature) {
6300             return null;
6301         }
6302         synchronized (getLockObject()) {
6303             Preconditions.checkNotNull(who, "ComponentName is null");
6304 
6305             // Only check if system user has set global proxy. We don't allow other users to set it.
6306             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6307             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6308                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
6309 
6310             // Scan through active admins and find if anyone has already
6311             // set the global proxy.
6312             Set<ComponentName> compSet = policy.mAdminMap.keySet();
6313             for (ComponentName component : compSet) {
6314                 ActiveAdmin ap = policy.mAdminMap.get(component);
6315                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
6316                     // Another admin already sets the global proxy
6317                     // Return it to the caller.
6318                     return component;
6319                 }
6320             }
6321 
6322             // If the user is not system, don't set the global proxy. Fail silently.
6323             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
6324                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
6325                         + UserHandle.getCallingUserId() + " is not permitted.");
6326                 return null;
6327             }
6328             if (proxySpec == null) {
6329                 admin.specifiesGlobalProxy = false;
6330                 admin.globalProxySpec = null;
6331                 admin.globalProxyExclusionList = null;
6332             } else {
6333 
6334                 admin.specifiesGlobalProxy = true;
6335                 admin.globalProxySpec = proxySpec;
6336                 admin.globalProxyExclusionList = exclusionList;
6337             }
6338 
6339             // Reset the global proxy accordingly
6340             // Do this using system permissions, as apps cannot write to secure settings
6341             long origId = mInjector.binderClearCallingIdentity();
6342             try {
6343                 resetGlobalProxyLocked(policy);
6344             } finally {
6345                 mInjector.binderRestoreCallingIdentity(origId);
6346             }
6347             return null;
6348         }
6349     }
6350 
6351     @Override
getGlobalProxyAdmin(int userHandle)6352     public ComponentName getGlobalProxyAdmin(int userHandle) {
6353         if (!mHasFeature) {
6354             return null;
6355         }
6356         enforceFullCrossUsersPermission(userHandle);
6357         synchronized (getLockObject()) {
6358             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6359             // Scan through active admins and find if anyone has already
6360             // set the global proxy.
6361             final int N = policy.mAdminList.size();
6362             for (int i = 0; i < N; i++) {
6363                 ActiveAdmin ap = policy.mAdminList.get(i);
6364                 if (ap.specifiesGlobalProxy) {
6365                     // Device admin sets the global proxy
6366                     // Return it to the caller.
6367                     return ap.info.getComponent();
6368                 }
6369             }
6370         }
6371         // No device admin sets the global proxy.
6372         return null;
6373     }
6374 
6375     @Override
setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo)6376     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
6377         synchronized (getLockObject()) {
6378             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6379         }
6380         long token = mInjector.binderClearCallingIdentity();
6381         try {
6382             ConnectivityManager connectivityManager = (ConnectivityManager)
6383                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
6384             connectivityManager.setGlobalProxy(proxyInfo);
6385         } finally {
6386             mInjector.binderRestoreCallingIdentity(token);
6387         }
6388     }
6389 
resetGlobalProxyLocked(DevicePolicyData policy)6390     private void resetGlobalProxyLocked(DevicePolicyData policy) {
6391         final int N = policy.mAdminList.size();
6392         for (int i = 0; i < N; i++) {
6393             ActiveAdmin ap = policy.mAdminList.get(i);
6394             if (ap.specifiesGlobalProxy) {
6395                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
6396                 return;
6397             }
6398         }
6399         // No device admins defining global proxies - reset global proxy settings to none
6400         saveGlobalProxyLocked(null, null);
6401     }
6402 
saveGlobalProxyLocked(String proxySpec, String exclusionList)6403     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
6404         if (exclusionList == null) {
6405             exclusionList = "";
6406         }
6407         if (proxySpec == null) {
6408             proxySpec = "";
6409         }
6410         // Remove white spaces
6411         proxySpec = proxySpec.trim();
6412         String data[] = proxySpec.split(":");
6413         int proxyPort = 8080;
6414         if (data.length > 1) {
6415             try {
6416                 proxyPort = Integer.parseInt(data[1]);
6417             } catch (NumberFormatException e) {}
6418         }
6419         exclusionList = exclusionList.trim();
6420 
6421         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
6422         if (!proxyProperties.isValid()) {
6423             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
6424             return;
6425         }
6426         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
6427         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
6428         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
6429                 exclusionList);
6430     }
6431 
6432     /**
6433      * Called by an application that is administering the device to request that the storage system
6434      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
6435      *
6436      * @return the new total request status (for all admins), or {@link
6437      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
6438      */
6439     @Override
setStorageEncryption(ComponentName who, boolean encrypt)6440     public int setStorageEncryption(ComponentName who, boolean encrypt) {
6441         if (!mHasFeature) {
6442             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6443         }
6444         Preconditions.checkNotNull(who, "ComponentName is null");
6445         final int userHandle = UserHandle.getCallingUserId();
6446         synchronized (getLockObject()) {
6447             // Check for permissions
6448             // Only system user can set storage encryption
6449             if (userHandle != UserHandle.USER_SYSTEM) {
6450                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
6451                         + UserHandle.getCallingUserId() + " is not permitted.");
6452                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6453             }
6454 
6455             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6456                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
6457 
6458             // Quick exit:  If the filesystem does not support encryption, we can exit early.
6459             if (!isEncryptionSupported()) {
6460                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6461             }
6462 
6463             // (1) Record the value for the admin so it's sticky
6464             if (ap.encryptionRequested != encrypt) {
6465                 ap.encryptionRequested = encrypt;
6466                 saveSettingsLocked(userHandle);
6467             }
6468 
6469             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6470             // (2) Compute "max" for all admins
6471             boolean newRequested = false;
6472             final int N = policy.mAdminList.size();
6473             for (int i = 0; i < N; i++) {
6474                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
6475             }
6476 
6477             // Notify OS of new request
6478             setEncryptionRequested(newRequested);
6479 
6480             // Return the new global request status
6481             return newRequested
6482                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
6483                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6484         }
6485     }
6486 
6487     /**
6488      * Get the current storage encryption request status for a given admin, or aggregate of all
6489      * active admins.
6490      */
6491     @Override
getStorageEncryption(ComponentName who, int userHandle)6492     public boolean getStorageEncryption(ComponentName who, int userHandle) {
6493         if (!mHasFeature) {
6494             return false;
6495         }
6496         enforceFullCrossUsersPermission(userHandle);
6497         synchronized (getLockObject()) {
6498             // Check for permissions if a particular caller is specified
6499             if (who != null) {
6500                 // When checking for a single caller, status is based on caller's request
6501                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
6502                 return ap != null ? ap.encryptionRequested : false;
6503             }
6504 
6505             // If no particular caller is specified, return the aggregate set of requests.
6506             // This is short circuited by returning true on the first hit.
6507             DevicePolicyData policy = getUserData(userHandle);
6508             final int N = policy.mAdminList.size();
6509             for (int i = 0; i < N; i++) {
6510                 if (policy.mAdminList.get(i).encryptionRequested) {
6511                     return true;
6512                 }
6513             }
6514             return false;
6515         }
6516     }
6517 
6518     /**
6519      * Get the current encryption status of the device.
6520      */
6521     @Override
getStorageEncryptionStatus(@ullable String callerPackage, int userHandle)6522     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
6523         if (!mHasFeature) {
6524             // Ok to return current status.
6525         }
6526         enforceFullCrossUsersPermission(userHandle);
6527 
6528         // It's not critical here, but let's make sure the package name is correct, in case
6529         // we start using it for different purposes.
6530         ensureCallerPackage(callerPackage);
6531 
6532         final ApplicationInfo ai;
6533         try {
6534             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
6535         } catch (RemoteException e) {
6536             throw new SecurityException(e);
6537         }
6538 
6539         boolean legacyApp = false;
6540         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
6541             legacyApp = true;
6542         }
6543 
6544         final int rawStatus = getEncryptionStatus();
6545         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
6546             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6547         }
6548         return rawStatus;
6549     }
6550 
6551     /**
6552      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
6553      */
isEncryptionSupported()6554     private boolean isEncryptionSupported() {
6555         // Note, this can be implemented as
6556         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6557         // But is provided as a separate internal method if there's a faster way to do a
6558         // simple check for supported-or-not.
6559         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6560     }
6561 
6562     /**
6563      * Hook to low-levels:  Reporting the current status of encryption.
6564      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
6565      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
6566      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
6567      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
6568      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
6569      */
getEncryptionStatus()6570     private int getEncryptionStatus() {
6571         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
6572             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
6573         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
6574             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6575         } else if (mInjector.storageManagerIsEncrypted()) {
6576             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
6577         } else if (mInjector.storageManagerIsEncryptable()) {
6578             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6579         } else {
6580             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6581         }
6582     }
6583 
6584     /**
6585      * Hook to low-levels:  If needed, record the new admin setting for encryption.
6586      */
setEncryptionRequested(boolean encrypt)6587     private void setEncryptionRequested(boolean encrypt) {
6588     }
6589 
6590     /**
6591      * Set whether the screen capture is disabled for the user managed by the specified admin.
6592      */
6593     @Override
setScreenCaptureDisabled(ComponentName who, boolean disabled)6594     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
6595         if (!mHasFeature) {
6596             return;
6597         }
6598         Preconditions.checkNotNull(who, "ComponentName is null");
6599         final int userHandle = UserHandle.getCallingUserId();
6600         synchronized (getLockObject()) {
6601             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6602                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6603             if (ap.disableScreenCapture != disabled) {
6604                 ap.disableScreenCapture = disabled;
6605                 saveSettingsLocked(userHandle);
6606                 updateScreenCaptureDisabled(userHandle, disabled);
6607             }
6608         }
6609     }
6610 
6611     /**
6612      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
6613      * active admin (if given admin is null).
6614      */
6615     @Override
getScreenCaptureDisabled(ComponentName who, int userHandle)6616     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
6617         if (!mHasFeature) {
6618             return false;
6619         }
6620         synchronized (getLockObject()) {
6621             if (who != null) {
6622                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6623                 return (admin != null) ? admin.disableScreenCapture : false;
6624             }
6625 
6626             DevicePolicyData policy = getUserData(userHandle);
6627             final int N = policy.mAdminList.size();
6628             for (int i = 0; i < N; i++) {
6629                 ActiveAdmin admin = policy.mAdminList.get(i);
6630                 if (admin.disableScreenCapture) {
6631                     return true;
6632                 }
6633             }
6634             return false;
6635         }
6636     }
6637 
updateScreenCaptureDisabled(int userHandle, boolean disabled)6638     private void updateScreenCaptureDisabled(int userHandle, boolean disabled) {
6639         mPolicyCache.setScreenCaptureDisabled(userHandle, disabled);
6640         mHandler.post(new Runnable() {
6641             @Override
6642             public void run() {
6643                 try {
6644                     mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle);
6645                 } catch (RemoteException e) {
6646                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6647                 }
6648             }
6649         });
6650     }
6651 
6652     /**
6653      * Set whether auto time is required by the specified admin (must be device or profile owner).
6654      */
6655     @Override
setAutoTimeRequired(ComponentName who, boolean required)6656     public void setAutoTimeRequired(ComponentName who, boolean required) {
6657         if (!mHasFeature) {
6658             return;
6659         }
6660         Preconditions.checkNotNull(who, "ComponentName is null");
6661         final int userHandle = UserHandle.getCallingUserId();
6662         synchronized (getLockObject()) {
6663             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6664                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6665             if (admin.requireAutoTime != required) {
6666                 admin.requireAutoTime = required;
6667                 saveSettingsLocked(userHandle);
6668             }
6669         }
6670 
6671         // Turn AUTO_TIME on in settings if it is required
6672         if (required) {
6673             long ident = mInjector.binderClearCallingIdentity();
6674             try {
6675                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6676             } finally {
6677                 mInjector.binderRestoreCallingIdentity(ident);
6678             }
6679         }
6680     }
6681 
6682     /**
6683      * Returns whether or not auto time is required by the device owner or any profile owner.
6684      */
6685     @Override
getAutoTimeRequired()6686     public boolean getAutoTimeRequired() {
6687         if (!mHasFeature) {
6688             return false;
6689         }
6690         synchronized (getLockObject()) {
6691             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6692             if (deviceOwner != null && deviceOwner.requireAutoTime) {
6693                 // If the device owner enforces auto time, we don't need to check the PO's
6694                 return true;
6695             }
6696 
6697             // Now check to see if any profile owner on any user enforces auto time
6698             for (Integer userId : mOwners.getProfileOwnerKeys()) {
6699                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6700                 if (profileOwner != null && profileOwner.requireAutoTime) {
6701                     return true;
6702                 }
6703             }
6704 
6705             return false;
6706         }
6707     }
6708 
6709     @Override
setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers)6710     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6711         if (!mHasFeature) {
6712             return;
6713         }
6714         Preconditions.checkNotNull(who, "ComponentName is null");
6715         // Allow setting this policy to true only if there is a split system user.
6716         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6717             throw new UnsupportedOperationException(
6718                     "Cannot force ephemeral users on systems without split system user.");
6719         }
6720         boolean removeAllUsers = false;
6721         synchronized (getLockObject()) {
6722             final ActiveAdmin deviceOwner =
6723                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6724             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6725                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6726                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6727                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6728                 removeAllUsers = forceEphemeralUsers;
6729             }
6730         }
6731         if (removeAllUsers) {
6732             long identitity = mInjector.binderClearCallingIdentity();
6733             try {
6734                 mUserManagerInternal.removeAllUsers();
6735             } finally {
6736                 mInjector.binderRestoreCallingIdentity(identitity);
6737             }
6738         }
6739     }
6740 
6741     @Override
getForceEphemeralUsers(ComponentName who)6742     public boolean getForceEphemeralUsers(ComponentName who) {
6743         if (!mHasFeature) {
6744             return false;
6745         }
6746         Preconditions.checkNotNull(who, "ComponentName is null");
6747         synchronized (getLockObject()) {
6748             final ActiveAdmin deviceOwner =
6749                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6750             return deviceOwner.forceEphemeralUsers;
6751         }
6752     }
6753 
ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who)6754     private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6755         synchronized (getLockObject()) {
6756             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6757             if (!areAllUsersAffiliatedWithDeviceLocked()) {
6758                 throw new SecurityException("Not all users are affiliated.");
6759             }
6760         }
6761     }
6762 
6763     @Override
requestBugreport(ComponentName who)6764     public boolean requestBugreport(ComponentName who) {
6765         if (!mHasFeature) {
6766             return false;
6767         }
6768         Preconditions.checkNotNull(who, "ComponentName is null");
6769 
6770         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6771         // which could still contain data related to that user. Should we disallow that, e.g. until
6772         // next boot? Might not be needed given that this still requires user consent.
6773         ensureDeviceOwnerAndAllUsersAffiliated(who);
6774 
6775         if (mRemoteBugreportServiceIsActive.get()
6776                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
6777             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6778             return false;
6779         }
6780 
6781         final long currentTime = System.currentTimeMillis();
6782         synchronized (getLockObject()) {
6783             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6784             if (currentTime > policyData.mLastBugReportRequestTime) {
6785                 policyData.mLastBugReportRequestTime = currentTime;
6786                 saveSettingsLocked(UserHandle.USER_SYSTEM);
6787             }
6788         }
6789 
6790         final long callingIdentity = mInjector.binderClearCallingIdentity();
6791         try {
6792             mInjector.getIActivityManager().requestBugReport(
6793                     ActivityManager.BUGREPORT_OPTION_REMOTE);
6794 
6795             mRemoteBugreportServiceIsActive.set(true);
6796             mRemoteBugreportSharingAccepted.set(false);
6797             registerRemoteBugreportReceivers();
6798             mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6799                     RemoteBugreportUtils.NOTIFICATION_ID,
6800                     RemoteBugreportUtils.buildNotification(mContext,
6801                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6802             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6803                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6804             return true;
6805         } catch (RemoteException re) {
6806             // should never happen
6807             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6808             return false;
6809         } finally {
6810             mInjector.binderRestoreCallingIdentity(callingIdentity);
6811         }
6812     }
6813 
sendDeviceOwnerCommand(String action, Bundle extras)6814     void sendDeviceOwnerCommand(String action, Bundle extras) {
6815         int deviceOwnerUserId;
6816         ComponentName deviceOwnerComponent;
6817         synchronized (getLockObject()) {
6818             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6819             deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6820         }
6821         sendActiveAdminCommand(action, extras, deviceOwnerUserId,
6822                 deviceOwnerComponent);
6823     }
6824 
sendProfileOwnerCommand(String action, Bundle extras, int userHandle)6825     private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) {
6826         sendActiveAdminCommand(action, extras, userHandle,
6827                 mOwners.getProfileOwnerComponent(userHandle));
6828     }
6829 
sendActiveAdminCommand(String action, Bundle extras, int userHandle, ComponentName receiverComponent)6830     private void sendActiveAdminCommand(String action, Bundle extras,
6831             int userHandle, ComponentName receiverComponent) {
6832         final Intent intent = new Intent(action);
6833         intent.setComponent(receiverComponent);
6834         if (extras != null) {
6835             intent.putExtras(extras);
6836         }
6837         mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle));
6838     }
6839 
sendOwnerChangedBroadcast(String broadcast, int userId)6840     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
6841         final Intent intent = new Intent(broadcast)
6842                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6843         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6844     }
6845 
getDeviceOwnerRemoteBugreportUri()6846     private String getDeviceOwnerRemoteBugreportUri() {
6847         synchronized (getLockObject()) {
6848             return mOwners.getDeviceOwnerRemoteBugreportUri();
6849         }
6850     }
6851 
setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash)6852     private void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6853             String bugreportHash) {
6854         synchronized (getLockObject()) {
6855             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6856         }
6857     }
6858 
registerRemoteBugreportReceivers()6859     private void registerRemoteBugreportReceivers() {
6860         try {
6861             IntentFilter filterFinished = new IntentFilter(
6862                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6863                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6864             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6865         } catch (IntentFilter.MalformedMimeTypeException e) {
6866             // should never happen, as setting a constant
6867             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6868         }
6869         IntentFilter filterConsent = new IntentFilter();
6870         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6871         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6872         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6873     }
6874 
onBugreportFinished(Intent intent)6875     private void onBugreportFinished(Intent intent) {
6876         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6877         mRemoteBugreportServiceIsActive.set(false);
6878         Uri bugreportUri = intent.getData();
6879         String bugreportUriString = null;
6880         if (bugreportUri != null) {
6881             bugreportUriString = bugreportUri.toString();
6882         }
6883         String bugreportHash = intent.getStringExtra(
6884                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6885         if (mRemoteBugreportSharingAccepted.get()) {
6886             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6887             mInjector.getNotificationManager().cancel(LOG_TAG,
6888                     RemoteBugreportUtils.NOTIFICATION_ID);
6889         } else {
6890             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6891             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6892                     RemoteBugreportUtils.buildNotification(mContext,
6893                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6894                             UserHandle.ALL);
6895         }
6896         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6897     }
6898 
onBugreportFailed()6899     private void onBugreportFailed() {
6900         mRemoteBugreportServiceIsActive.set(false);
6901         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6902                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6903         mRemoteBugreportSharingAccepted.set(false);
6904         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6905         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6906         Bundle extras = new Bundle();
6907         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6908                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6909         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6910         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6911         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6912     }
6913 
onBugreportSharingAccepted()6914     private void onBugreportSharingAccepted() {
6915         mRemoteBugreportSharingAccepted.set(true);
6916         String bugreportUriString = null;
6917         String bugreportHash = null;
6918         synchronized (getLockObject()) {
6919             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6920             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6921         }
6922         if (bugreportUriString != null) {
6923             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6924         } else if (mRemoteBugreportServiceIsActive.get()) {
6925             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6926                     RemoteBugreportUtils.buildNotification(mContext,
6927                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6928                             UserHandle.ALL);
6929         }
6930     }
6931 
onBugreportSharingDeclined()6932     private void onBugreportSharingDeclined() {
6933         if (mRemoteBugreportServiceIsActive.get()) {
6934             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6935                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6936             mRemoteBugreportServiceIsActive.set(false);
6937             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6938             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6939         }
6940         mRemoteBugreportSharingAccepted.set(false);
6941         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6942         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6943     }
6944 
shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, String bugreportHash)6945     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6946             String bugreportHash) {
6947         ParcelFileDescriptor pfd = null;
6948         try {
6949             if (bugreportUriString == null) {
6950                 throw new FileNotFoundException();
6951             }
6952             Uri bugreportUri = Uri.parse(bugreportUriString);
6953             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6954 
6955             synchronized (getLockObject()) {
6956                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6957                 intent.setComponent(mOwners.getDeviceOwnerComponent());
6958                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6959                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6960                 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6961 
6962                 LocalServices.getService(ActivityManagerInternal.class)
6963                         .grantUriPermissionFromIntent(Process.SHELL_UID,
6964                                 mOwners.getDeviceOwnerComponent().getPackageName(),
6965                                 intent, mOwners.getDeviceOwnerUserId());
6966                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6967             }
6968         } catch (FileNotFoundException e) {
6969             Bundle extras = new Bundle();
6970             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6971                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6972             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6973         } finally {
6974             try {
6975                 if (pfd != null) {
6976                     pfd.close();
6977                 }
6978             } catch (IOException ex) {
6979                 // Ignore
6980             }
6981             mRemoteBugreportSharingAccepted.set(false);
6982             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6983         }
6984     }
6985 
6986     /**
6987      * Disables all device cameras according to the specified admin.
6988      */
6989     @Override
setCameraDisabled(ComponentName who, boolean disabled)6990     public void setCameraDisabled(ComponentName who, boolean disabled) {
6991         if (!mHasFeature) {
6992             return;
6993         }
6994         Preconditions.checkNotNull(who, "ComponentName is null");
6995         final int userHandle = mInjector.userHandleGetCallingUserId();
6996         synchronized (getLockObject()) {
6997             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6998                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6999             if (ap.disableCamera != disabled) {
7000                 ap.disableCamera = disabled;
7001                 saveSettingsLocked(userHandle);
7002             }
7003         }
7004         // Tell the user manager that the restrictions have changed.
7005         pushUserRestrictions(userHandle);
7006     }
7007 
7008     /**
7009      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
7010      * active admins.
7011      */
7012     @Override
getCameraDisabled(ComponentName who, int userHandle)7013     public boolean getCameraDisabled(ComponentName who, int userHandle) {
7014         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
7015     }
7016 
getCameraDisabled(ComponentName who, int userHandle, boolean mergeDeviceOwnerRestriction)7017     private boolean getCameraDisabled(ComponentName who, int userHandle,
7018             boolean mergeDeviceOwnerRestriction) {
7019         if (!mHasFeature) {
7020             return false;
7021         }
7022         synchronized (getLockObject()) {
7023             if (who != null) {
7024                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7025                 return (admin != null) ? admin.disableCamera : false;
7026             }
7027             // First, see if DO has set it.  If so, it's device-wide.
7028             if (mergeDeviceOwnerRestriction) {
7029                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7030                 if (deviceOwner != null && deviceOwner.disableCamera) {
7031                     return true;
7032                 }
7033             }
7034 
7035             // Then check each device admin on the user.
7036             DevicePolicyData policy = getUserData(userHandle);
7037             // Determine whether or not the device camera is disabled for any active admins.
7038             final int N = policy.mAdminList.size();
7039             for (int i = 0; i < N; i++) {
7040                 ActiveAdmin admin = policy.mAdminList.get(i);
7041                 if (admin.disableCamera) {
7042                     return true;
7043                 }
7044             }
7045             return false;
7046         }
7047     }
7048 
7049     @Override
setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent)7050     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
7051         if (!mHasFeature) {
7052             return;
7053         }
7054         Preconditions.checkNotNull(who, "ComponentName is null");
7055         final int userHandle = mInjector.userHandleGetCallingUserId();
7056         if (isManagedProfile(userHandle)) {
7057             if (parent) {
7058                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
7059             } else {
7060                 which = which & PROFILE_KEYGUARD_FEATURES;
7061             }
7062         }
7063         synchronized (getLockObject()) {
7064             ActiveAdmin ap = getActiveAdminForCallerLocked(
7065                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7066             if (ap.disabledKeyguardFeatures != which) {
7067                 ap.disabledKeyguardFeatures = which;
7068                 saveSettingsLocked(userHandle);
7069             }
7070         }
7071         if (SecurityLog.isLoggingEnabled()) {
7072             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
7073             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
7074                     who.getPackageName(), userHandle, affectedUserId, which);
7075         }
7076     }
7077 
7078     /**
7079      * Gets the disabled state for features in keyguard for the given admin,
7080      * or the aggregate of all active admins if who is null.
7081      */
7082     @Override
getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent)7083     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
7084         if (!mHasFeature) {
7085             return 0;
7086         }
7087         enforceFullCrossUsersPermission(userHandle);
7088         final long ident = mInjector.binderClearCallingIdentity();
7089         try {
7090             synchronized (getLockObject()) {
7091                 if (who != null) {
7092                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
7093                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
7094                 }
7095 
7096                 final List<ActiveAdmin> admins;
7097                 if (!parent && isManagedProfile(userHandle)) {
7098                     // If we are being asked about a managed profile, just return keyguard features
7099                     // disabled by admins in the profile.
7100                     admins = getUserDataUnchecked(userHandle).mAdminList;
7101                 } else {
7102                     // Otherwise return those set by admins in the user and its profiles.
7103                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7104                 }
7105 
7106                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
7107                 final int N = admins.size();
7108                 for (int i = 0; i < N; i++) {
7109                     ActiveAdmin admin = admins.get(i);
7110                     int userId = admin.getUserHandle().getIdentifier();
7111                     boolean isRequestedUser = !parent && (userId == userHandle);
7112                     if (isRequestedUser || !isManagedProfile(userId)) {
7113                         // If we are being asked explicitly about this user
7114                         // return all disabled features even if its a managed profile.
7115                         which |= admin.disabledKeyguardFeatures;
7116                     } else {
7117                         // Otherwise a managed profile is only allowed to disable
7118                         // some features on the parent user.
7119                         which |= (admin.disabledKeyguardFeatures
7120                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
7121                     }
7122                 }
7123                 return which;
7124             }
7125         } finally {
7126             mInjector.binderRestoreCallingIdentity(ident);
7127         }
7128     }
7129 
7130     @Override
setKeepUninstalledPackages(ComponentName who, String callerPackage, List<String> packageList)7131     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
7132             List<String> packageList) {
7133         if (!mHasFeature) {
7134             return;
7135         }
7136         Preconditions.checkNotNull(packageList, "packageList is null");
7137         final int userHandle = UserHandle.getCallingUserId();
7138         synchronized (getLockObject()) {
7139             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7140             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7141                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7142             // Get the device owner
7143             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7144             // Set list of packages to be kept even if uninstalled.
7145             deviceOwner.keepUninstalledPackages = packageList;
7146             // Save settings.
7147             saveSettingsLocked(userHandle);
7148             // Notify package manager.
7149             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
7150         }
7151     }
7152 
7153     @Override
getKeepUninstalledPackages(ComponentName who, String callerPackage)7154     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
7155         if (!mHasFeature) {
7156             return null;
7157         }
7158         // TODO In split system user mode, allow apps on user 0 to query the list
7159         synchronized (getLockObject()) {
7160             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7161             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7162                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7163             return getKeepUninstalledPackagesLocked();
7164         }
7165     }
7166 
getKeepUninstalledPackagesLocked()7167     private List<String> getKeepUninstalledPackagesLocked() {
7168         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7169         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
7170     }
7171 
7172     @Override
setDeviceOwner(ComponentName admin, String ownerName, int userId)7173     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
7174         if (!mHasFeature) {
7175             return false;
7176         }
7177         if (admin == null
7178                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
7179             throw new IllegalArgumentException("Invalid component " + admin
7180                     + " for device owner");
7181         }
7182         final boolean hasIncompatibleAccountsOrNonAdb =
7183                 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
7184         synchronized (getLockObject()) {
7185             enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
7186             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
7187             if (activeAdmin == null
7188                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
7189                 throw new IllegalArgumentException("Not active admin: " + admin);
7190             }
7191 
7192             // Shutting down backup manager service permanently.
7193             long ident = mInjector.binderClearCallingIdentity();
7194             try {
7195                 if (mInjector.getIBackupManager() != null) {
7196                     mInjector.getIBackupManager()
7197                             .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
7198                 }
7199             } catch (RemoteException e) {
7200                 throw new IllegalStateException("Failed deactivating backup service.", e);
7201             } finally {
7202                 mInjector.binderRestoreCallingIdentity(ident);
7203             }
7204 
7205             if (isAdb()) {
7206                 // Log device owner provisioning was started using adb.
7207                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
7208             }
7209 
7210             mOwners.setDeviceOwner(admin, ownerName, userId);
7211             mOwners.writeDeviceOwner();
7212             updateDeviceOwnerLocked();
7213             setDeviceOwnerSystemPropertyLocked();
7214 
7215             final Set<String> restrictions =
7216                     UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
7217             if (!restrictions.isEmpty()) {
7218                 for (String restriction : restrictions) {
7219                     activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
7220                 }
7221                 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
7222                 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
7223 
7224                 saveUserRestrictionsLocked(userId);
7225             }
7226 
7227             ident = mInjector.binderClearCallingIdentity();
7228             try {
7229                 // TODO Send to system too?
7230                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
7231             } finally {
7232                 mInjector.binderRestoreCallingIdentity(ident);
7233             }
7234             mDeviceAdminServiceController.startServiceForOwner(
7235                     admin.getPackageName(), userId, "set-device-owner");
7236 
7237             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
7238             return true;
7239         }
7240     }
7241 
7242     @Override
hasDeviceOwner()7243     public boolean hasDeviceOwner() {
7244         enforceDeviceOwnerOrManageUsers();
7245         return mOwners.hasDeviceOwner();
7246     }
7247 
isDeviceOwner(ActiveAdmin admin)7248     boolean isDeviceOwner(ActiveAdmin admin) {
7249         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
7250     }
7251 
isDeviceOwner(ComponentName who, int userId)7252     public boolean isDeviceOwner(ComponentName who, int userId) {
7253         synchronized (getLockObject()) {
7254             return mOwners.hasDeviceOwner()
7255                     && mOwners.getDeviceOwnerUserId() == userId
7256                     && mOwners.getDeviceOwnerComponent().equals(who);
7257         }
7258     }
7259 
isDeviceOwnerPackage(String packageName, int userId)7260     private boolean isDeviceOwnerPackage(String packageName, int userId) {
7261         synchronized (getLockObject()) {
7262             return mOwners.hasDeviceOwner()
7263                     && mOwners.getDeviceOwnerUserId() == userId
7264                     && mOwners.getDeviceOwnerPackageName().equals(packageName);
7265         }
7266     }
7267 
isProfileOwnerPackage(String packageName, int userId)7268     private boolean isProfileOwnerPackage(String packageName, int userId) {
7269         synchronized (getLockObject()) {
7270             return mOwners.hasProfileOwner(userId)
7271                     && mOwners.getProfileOwnerPackage(userId).equals(packageName);
7272         }
7273     }
7274 
isProfileOwner(ComponentName who, int userId)7275     public boolean isProfileOwner(ComponentName who, int userId) {
7276         final ComponentName profileOwner = getProfileOwner(userId);
7277         return who != null && who.equals(profileOwner);
7278     }
7279 
7280     @Override
getDeviceOwnerComponent(boolean callingUserOnly)7281     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
7282         if (!mHasFeature) {
7283             return null;
7284         }
7285         if (!callingUserOnly) {
7286             enforceManageUsers();
7287         }
7288         synchronized (getLockObject()) {
7289             if (!mOwners.hasDeviceOwner()) {
7290                 return null;
7291             }
7292             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
7293                     mOwners.getDeviceOwnerUserId()) {
7294                 return null;
7295             }
7296             return mOwners.getDeviceOwnerComponent();
7297         }
7298     }
7299 
7300     @Override
getDeviceOwnerUserId()7301     public int getDeviceOwnerUserId() {
7302         if (!mHasFeature) {
7303             return UserHandle.USER_NULL;
7304         }
7305         enforceManageUsers();
7306         synchronized (getLockObject()) {
7307             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
7308         }
7309     }
7310 
7311     /**
7312      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
7313      * MANAGE_USERS.
7314      */
7315     @Override
getDeviceOwnerName()7316     public String getDeviceOwnerName() {
7317         if (!mHasFeature) {
7318             return null;
7319         }
7320         enforceManageUsers();
7321         synchronized (getLockObject()) {
7322             if (!mOwners.hasDeviceOwner()) {
7323                 return null;
7324             }
7325             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
7326             // Should setDeviceOwner/ProfileOwner still take a name?
7327             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
7328             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
7329         }
7330     }
7331 
7332     /** Returns the active device owner or {@code null} if there is no device owner. */
7333     @VisibleForTesting
getDeviceOwnerAdminLocked()7334     ActiveAdmin getDeviceOwnerAdminLocked() {
7335         ensureLocked();
7336         ComponentName component = mOwners.getDeviceOwnerComponent();
7337         if (component == null) {
7338             return null;
7339         }
7340 
7341         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
7342         final int n = policy.mAdminList.size();
7343         for (int i = 0; i < n; i++) {
7344             ActiveAdmin admin = policy.mAdminList.get(i);
7345             if (component.equals(admin.info.getComponent())) {
7346                 return admin;
7347             }
7348         }
7349         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
7350         return null;
7351     }
7352 
7353     @Override
clearDeviceOwner(String packageName)7354     public void clearDeviceOwner(String packageName) {
7355         Preconditions.checkNotNull(packageName, "packageName is null");
7356         final int callingUid = mInjector.binderGetCallingUid();
7357         try {
7358             int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
7359                     UserHandle.getUserId(callingUid));
7360             if (uid != callingUid) {
7361                 throw new SecurityException("Invalid packageName");
7362             }
7363         } catch (NameNotFoundException e) {
7364             throw new SecurityException(e);
7365         }
7366         synchronized (getLockObject()) {
7367             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
7368             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
7369             if (!mOwners.hasDeviceOwner()
7370                     || !deviceOwnerComponent.getPackageName().equals(packageName)
7371                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
7372                 throw new SecurityException(
7373                         "clearDeviceOwner can only be called by the device owner");
7374             }
7375             enforceUserUnlocked(deviceOwnerUserId);
7376 
7377             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
7378             long ident = mInjector.binderClearCallingIdentity();
7379             try {
7380                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
7381                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
7382                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
7383                         deviceOwnerUserId);
7384             } finally {
7385                 mInjector.binderRestoreCallingIdentity(ident);
7386             }
7387             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
7388         }
7389     }
7390 
clearOverrideApnUnchecked()7391     private void clearOverrideApnUnchecked() {
7392         // Disable Override APNs and remove them from database.
7393         setOverrideApnsEnabledUnchecked(false);
7394         final List<ApnSetting> apns = getOverrideApnsUnchecked();
7395         for (int i = 0; i < apns.size(); i ++) {
7396             removeOverrideApnUnchecked(apns.get(i).getId());
7397         }
7398     }
7399 
clearDeviceOwnerLocked(ActiveAdmin admin, int userId)7400     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
7401         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
7402 
7403         if (admin != null) {
7404             admin.disableCamera = false;
7405             admin.userRestrictions = null;
7406             admin.defaultEnabledRestrictionsAlreadySet.clear();
7407             admin.forceEphemeralUsers = false;
7408             admin.isNetworkLoggingEnabled = false;
7409             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
7410         }
7411         final DevicePolicyData policyData = getUserData(userId);
7412         policyData.mCurrentInputMethodSet = false;
7413         saveSettingsLocked(userId);
7414         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
7415         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
7416         systemPolicyData.mLastBugReportRequestTime = -1;
7417         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
7418         saveSettingsLocked(UserHandle.USER_SYSTEM);
7419         clearUserPoliciesLocked(userId);
7420         clearOverrideApnUnchecked();
7421 
7422         mOwners.clearDeviceOwner();
7423         mOwners.writeDeviceOwner();
7424         updateDeviceOwnerLocked();
7425 
7426         clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
7427         mInjector.securityLogSetLoggingEnabledProperty(false);
7428         mSecurityLogMonitor.stop();
7429         setNetworkLoggingActiveInternal(false);
7430         deleteTransferOwnershipBundleLocked(userId);
7431 
7432         try {
7433             if (mInjector.getIBackupManager() != null) {
7434                 // Reactivate backup service.
7435                 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
7436             }
7437         } catch (RemoteException e) {
7438             throw new IllegalStateException("Failed reactivating backup service.", e);
7439         }
7440     }
7441 
7442     @Override
setProfileOwner(ComponentName who, String ownerName, int userHandle)7443     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
7444         if (!mHasFeature) {
7445             return false;
7446         }
7447         if (who == null
7448                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
7449             throw new IllegalArgumentException("Component " + who
7450                     + " not installed for userId:" + userHandle);
7451         }
7452         final boolean hasIncompatibleAccountsOrNonAdb =
7453                 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
7454         synchronized (getLockObject()) {
7455             enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
7456 
7457             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7458             if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
7459                 throw new IllegalArgumentException("Not active admin: " + who);
7460             }
7461 
7462             if (isAdb()) {
7463                 // Log profile owner provisioning was started using adb.
7464                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
7465             }
7466 
7467             mOwners.setProfileOwner(who, ownerName, userHandle);
7468             mOwners.writeProfileOwner(userHandle);
7469             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
7470 
7471             final long id = mInjector.binderClearCallingIdentity();
7472             try {
7473                 if (mUserManager.isManagedProfile(userHandle)) {
7474                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
7475                             UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
7476                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
7477                             true /* newOwner */);
7478                 }
7479                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7480                         userHandle);
7481             } finally {
7482                 mInjector.binderRestoreCallingIdentity(id);
7483             }
7484             mDeviceAdminServiceController.startServiceForOwner(
7485                     who.getPackageName(), userHandle, "set-profile-owner");
7486             return true;
7487         }
7488     }
7489 
7490     @Override
clearProfileOwner(ComponentName who)7491     public void clearProfileOwner(ComponentName who) {
7492         if (!mHasFeature) {
7493             return;
7494         }
7495         Preconditions.checkNotNull(who, "ComponentName is null");
7496 
7497         final int userId = mInjector.userHandleGetCallingUserId();
7498         enforceNotManagedProfile(userId, "clear profile owner");
7499         enforceUserUnlocked(userId);
7500         synchronized (getLockObject()) {
7501             // Check if this is the profile owner who is calling
7502             final ActiveAdmin admin =
7503                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7504 
7505             final long ident = mInjector.binderClearCallingIdentity();
7506             try {
7507                 clearProfileOwnerLocked(admin, userId);
7508                 removeActiveAdminLocked(who, userId);
7509                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7510                         userId);
7511             } finally {
7512                 mInjector.binderRestoreCallingIdentity(ident);
7513             }
7514             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
7515         }
7516     }
7517 
clearProfileOwnerLocked(ActiveAdmin admin, int userId)7518     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
7519         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
7520 
7521         if (admin != null) {
7522             admin.disableCamera = false;
7523             admin.userRestrictions = null;
7524             admin.defaultEnabledRestrictionsAlreadySet.clear();
7525         }
7526         final DevicePolicyData policyData = getUserData(userId);
7527         policyData.mCurrentInputMethodSet = false;
7528         policyData.mOwnerInstalledCaCerts.clear();
7529         saveSettingsLocked(userId);
7530         clearUserPoliciesLocked(userId);
7531         mOwners.removeProfileOwner(userId);
7532         mOwners.writeProfileOwner(userId);
7533         deleteTransferOwnershipBundleLocked(userId);
7534     }
7535 
7536     @Override
setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info)7537     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
7538         Preconditions.checkNotNull(who, "ComponentName is null");
7539         if (!mHasFeature) {
7540             return;
7541         }
7542 
7543         synchronized (getLockObject()) {
7544             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7545             long token = mInjector.binderClearCallingIdentity();
7546             try {
7547                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
7548             } finally {
7549                 mInjector.binderRestoreCallingIdentity(token);
7550             }
7551         }
7552     }
7553 
7554     @Override
getDeviceOwnerLockScreenInfo()7555     public CharSequence getDeviceOwnerLockScreenInfo() {
7556         return mLockPatternUtils.getDeviceOwnerInfo();
7557     }
7558 
clearUserPoliciesLocked(int userId)7559     private void clearUserPoliciesLocked(int userId) {
7560         // Reset some of the user-specific policies.
7561         final DevicePolicyData policy = getUserData(userId);
7562         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
7563         // Clear delegations.
7564         policy.mDelegationMap.clear();
7565         policy.mStatusBarDisabled = false;
7566         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
7567         policy.mAffiliationIds.clear();
7568         policy.mLockTaskPackages.clear();
7569         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
7570         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
7571         saveSettingsLocked(userId);
7572 
7573         try {
7574             mIPackageManager.updatePermissionFlagsForAllApps(
7575                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7576                     0  /* flagValues */, userId);
7577             pushUserRestrictions(userId);
7578         } catch (RemoteException re) {
7579             // Shouldn't happen.
7580         }
7581     }
7582 
7583     @Override
hasUserSetupCompleted()7584     public boolean hasUserSetupCompleted() {
7585         return hasUserSetupCompleted(UserHandle.getCallingUserId());
7586     }
7587 
7588     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
7589     // completing Setup Wizard, and pairing involves transferring user data, calling
7590     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
hasUserSetupCompleted(int userHandle)7591     private boolean hasUserSetupCompleted(int userHandle) {
7592         if (!mHasFeature) {
7593             return true;
7594         }
7595         return getUserData(userHandle).mUserSetupComplete;
7596     }
7597 
hasPaired(int userHandle)7598     private boolean hasPaired(int userHandle) {
7599         if (!mHasFeature) {
7600             return true;
7601         }
7602         return getUserData(userHandle).mPaired;
7603     }
7604 
7605     @Override
getUserProvisioningState()7606     public int getUserProvisioningState() {
7607         if (!mHasFeature) {
7608             return DevicePolicyManager.STATE_USER_UNMANAGED;
7609         }
7610         enforceManageUsers();
7611         int userHandle = mInjector.userHandleGetCallingUserId();
7612         return getUserProvisioningState(userHandle);
7613     }
7614 
getUserProvisioningState(int userHandle)7615     private int getUserProvisioningState(int userHandle) {
7616         return getUserData(userHandle).mUserProvisioningState;
7617     }
7618 
7619     @Override
setUserProvisioningState(int newState, int userHandle)7620     public void setUserProvisioningState(int newState, int userHandle) {
7621         if (!mHasFeature) {
7622             return;
7623         }
7624 
7625         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
7626                 && getManagedUserId(userHandle) == -1) {
7627             // No managed device, user or profile, so setting provisioning state makes no sense.
7628             throw new IllegalStateException("Not allowed to change provisioning state unless a "
7629                       + "device or profile owner is set.");
7630         }
7631 
7632         synchronized (getLockObject()) {
7633             boolean transitionCheckNeeded = true;
7634 
7635             // Calling identity/permission checks.
7636             if (isAdb()) {
7637                 // ADB shell can only move directly from un-managed to finalized as part of directly
7638                 // setting profile-owner or device-owner.
7639                 if (getUserProvisioningState(userHandle) !=
7640                         DevicePolicyManager.STATE_USER_UNMANAGED
7641                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7642                     throw new IllegalStateException("Not allowed to change provisioning state "
7643                             + "unless current provisioning state is unmanaged, and new state is "
7644                             + "finalized.");
7645                 }
7646                 transitionCheckNeeded = false;
7647             } else {
7648                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
7649                 enforceCanManageProfileAndDeviceOwners();
7650             }
7651 
7652             final DevicePolicyData policyData = getUserData(userHandle);
7653             if (transitionCheckNeeded) {
7654                 // Optional state transition check for non-ADB case.
7655                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
7656             }
7657             policyData.mUserProvisioningState = newState;
7658             saveSettingsLocked(userHandle);
7659         }
7660     }
7661 
checkUserProvisioningStateTransition(int currentState, int newState)7662     private void checkUserProvisioningStateTransition(int currentState, int newState) {
7663         // Valid transitions for normal use-cases.
7664         switch (currentState) {
7665             case DevicePolicyManager.STATE_USER_UNMANAGED:
7666                 // Can move to any state from unmanaged (except itself as an edge case)..
7667                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
7668                     return;
7669                 }
7670                 break;
7671             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
7672             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7673                 // Can only move to finalized from these states.
7674                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7675                     return;
7676                 }
7677                 break;
7678             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7679                 // Current user has a managed-profile, but current user is not managed, so
7680                 // rather than moving to finalized state, go back to unmanaged once
7681                 // profile provisioning is complete.
7682                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7683                     return;
7684                 }
7685                 break;
7686             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7687                 // Cannot transition out of finalized.
7688                 break;
7689         }
7690 
7691         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7692         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7693                 + "from state [" + currentState + "]");
7694     }
7695 
7696     @Override
setProfileEnabled(ComponentName who)7697     public void setProfileEnabled(ComponentName who) {
7698         if (!mHasFeature) {
7699             return;
7700         }
7701         Preconditions.checkNotNull(who, "ComponentName is null");
7702         synchronized (getLockObject()) {
7703             // Check if this is the profile owner who is calling
7704             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7705             final int userId = UserHandle.getCallingUserId();
7706             enforceManagedProfile(userId, "enable the profile");
7707             // Check if the profile is already enabled.
7708             UserInfo managedProfile = getUserInfo(userId);
7709             if (managedProfile.isEnabled()) {
7710                 Slog.e(LOG_TAG,
7711                         "setProfileEnabled is called when the profile is already enabled");
7712                 return;
7713             }
7714             long id = mInjector.binderClearCallingIdentity();
7715             try {
7716                 mUserManager.setUserEnabled(userId);
7717                 UserInfo parent = mUserManager.getProfileParent(userId);
7718                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7719                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7720                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7721                         Intent.FLAG_RECEIVER_FOREGROUND);
7722                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7723             } finally {
7724                 mInjector.binderRestoreCallingIdentity(id);
7725             }
7726         }
7727     }
7728 
7729     @Override
setProfileName(ComponentName who, String profileName)7730     public void setProfileName(ComponentName who, String profileName) {
7731         Preconditions.checkNotNull(who, "ComponentName is null");
7732         int userId = UserHandle.getCallingUserId();
7733         // Check if this is the profile owner (includes device owner).
7734         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7735 
7736         long id = mInjector.binderClearCallingIdentity();
7737         try {
7738             mUserManager.setUserName(userId, profileName);
7739         } finally {
7740             mInjector.binderRestoreCallingIdentity(id);
7741         }
7742     }
7743 
7744     @Override
getProfileOwner(int userHandle)7745     public ComponentName getProfileOwner(int userHandle) {
7746         if (!mHasFeature) {
7747             return null;
7748         }
7749 
7750         synchronized (getLockObject()) {
7751             return mOwners.getProfileOwnerComponent(userHandle);
7752         }
7753     }
7754 
7755     // Returns the active profile owner for this user or null if the current user has no
7756     // profile owner.
7757     @VisibleForTesting
getProfileOwnerAdminLocked(int userHandle)7758     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7759         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7760         if (profileOwner == null) {
7761             return null;
7762         }
7763         DevicePolicyData policy = getUserData(userHandle);
7764         final int n = policy.mAdminList.size();
7765         for (int i = 0; i < n; i++) {
7766             ActiveAdmin admin = policy.mAdminList.get(i);
7767             if (profileOwner.equals(admin.info.getComponent())) {
7768                 return admin;
7769             }
7770         }
7771         return null;
7772     }
7773 
7774     @Override
getProfileOwnerName(int userHandle)7775     public String getProfileOwnerName(int userHandle) {
7776         if (!mHasFeature) {
7777             return null;
7778         }
7779         enforceManageUsers();
7780         ComponentName profileOwner = getProfileOwner(userHandle);
7781         if (profileOwner == null) {
7782             return null;
7783         }
7784         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7785     }
7786 
7787     /**
7788      * Canonical name for a given package.
7789      */
getApplicationLabel(String packageName, int userHandle)7790     private String getApplicationLabel(String packageName, int userHandle) {
7791         long token = mInjector.binderClearCallingIdentity();
7792         try {
7793             final Context userContext;
7794             try {
7795                 UserHandle handle = new UserHandle(userHandle);
7796                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7797             } catch (PackageManager.NameNotFoundException nnfe) {
7798                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7799                 return null;
7800             }
7801             ApplicationInfo appInfo = userContext.getApplicationInfo();
7802             CharSequence result = null;
7803             if (appInfo != null) {
7804                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
7805             }
7806             return result != null ? result.toString() : null;
7807         } finally {
7808             mInjector.binderRestoreCallingIdentity(token);
7809         }
7810     }
7811 
7812     /**
7813      * Calls wtfStack() if called with the DPMS lock held.
7814      */
wtfIfInLock()7815     private void wtfIfInLock() {
7816         if (Thread.holdsLock(this)) {
7817             Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7818         }
7819     }
7820 
7821     /**
7822      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7823      * permission.
7824      * The profile owner can only be set before the user setup phase has completed,
7825      * except for:
7826      * - SYSTEM_UID
7827      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7828      */
enforceCanSetProfileOwnerLocked(@ullable ComponentName owner, int userHandle, boolean hasIncompatibleAccountsOrNonAdb)7829     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7830             boolean hasIncompatibleAccountsOrNonAdb) {
7831         UserInfo info = getUserInfo(userHandle);
7832         if (info == null) {
7833             // User doesn't exist.
7834             throw new IllegalArgumentException(
7835                     "Attempted to set profile owner for invalid userId: " + userHandle);
7836         }
7837         if (info.isGuest()) {
7838             throw new IllegalStateException("Cannot set a profile owner on a guest");
7839         }
7840         if (mOwners.hasProfileOwner(userHandle)) {
7841             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7842                     + "is already set.");
7843         }
7844         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7845             throw new IllegalStateException("Trying to set the profile owner, but the user "
7846                     + "already has a device owner.");
7847         }
7848         if (isAdb()) {
7849             if ((mIsWatch || hasUserSetupCompleted(userHandle))
7850                     && hasIncompatibleAccountsOrNonAdb) {
7851                 throw new IllegalStateException("Not allowed to set the profile owner because "
7852                         + "there are already some accounts on the profile");
7853             }
7854             return;
7855         }
7856         enforceCanManageProfileAndDeviceOwners();
7857         if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7858             throw new IllegalStateException("Cannot set the profile owner on a user which is "
7859                     + "already set-up");
7860         }
7861     }
7862 
7863     /**
7864      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7865      * permission.
7866      */
enforceCanSetDeviceOwnerLocked(@ullable ComponentName owner, int userId, boolean hasIncompatibleAccountsOrNonAdb)7867     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7868             boolean hasIncompatibleAccountsOrNonAdb) {
7869         if (!isAdb()) {
7870             enforceCanManageProfileAndDeviceOwners();
7871         }
7872 
7873         final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7874                 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7875         switch (code) {
7876             case CODE_OK:
7877                 return;
7878             case CODE_HAS_DEVICE_OWNER:
7879                 throw new IllegalStateException(
7880                         "Trying to set the device owner, but device owner is already set.");
7881             case CODE_USER_HAS_PROFILE_OWNER:
7882                 throw new IllegalStateException("Trying to set the device owner, but the user "
7883                         + "already has a profile owner.");
7884             case CODE_USER_NOT_RUNNING:
7885                 throw new IllegalStateException("User not running: " + userId);
7886             case CODE_NOT_SYSTEM_USER:
7887                 throw new IllegalStateException("User is not system user");
7888             case CODE_USER_SETUP_COMPLETED:
7889                 throw new IllegalStateException(
7890                         "Cannot set the device owner if the device is already set-up");
7891             case CODE_NONSYSTEM_USER_EXISTS:
7892                 throw new IllegalStateException("Not allowed to set the device owner because there "
7893                         + "are already several users on the device");
7894             case CODE_ACCOUNTS_NOT_EMPTY:
7895                 throw new IllegalStateException("Not allowed to set the device owner because there "
7896                         + "are already some accounts on the device");
7897             case CODE_HAS_PAIRED:
7898                 throw new IllegalStateException("Not allowed to set the device owner because this "
7899                         + "device has already paired");
7900             default:
7901                 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7902         }
7903     }
7904 
enforceUserUnlocked(int userId)7905     private void enforceUserUnlocked(int userId) {
7906         // Since we're doing this operation on behalf of an app, we only
7907         // want to use the actual "unlocked" state.
7908         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7909                 "User must be running and unlocked");
7910     }
7911 
enforceUserUnlocked(@serIdInt int userId, boolean parent)7912     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7913         if (parent) {
7914             enforceUserUnlocked(getProfileParentId(userId));
7915         } else {
7916             enforceUserUnlocked(userId);
7917         }
7918     }
7919 
enforceManageUsers()7920     private void enforceManageUsers() {
7921         final int callingUid = mInjector.binderGetCallingUid();
7922         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7923             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7924         }
7925     }
7926 
enforceFullCrossUsersPermission(int userHandle)7927     private void enforceFullCrossUsersPermission(int userHandle) {
7928         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7929                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7930     }
7931 
enforceCrossUsersPermission(int userHandle)7932     private void enforceCrossUsersPermission(int userHandle) {
7933         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7934                 android.Manifest.permission.INTERACT_ACROSS_USERS);
7935     }
7936 
enforceSystemUserOrPermission(String permission)7937     private void enforceSystemUserOrPermission(String permission) {
7938         if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7939             mContext.enforceCallingOrSelfPermission(permission,
7940                     "Must be system or have " + permission + " permission");
7941         }
7942     }
7943 
enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission)7944     private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7945         if (userHandle < 0) {
7946             throw new IllegalArgumentException("Invalid userId " + userHandle);
7947         }
7948         if (userHandle == mInjector.userHandleGetCallingUserId()) {
7949             return;
7950         }
7951         enforceSystemUserOrPermission(permission);
7952     }
7953 
enforceManagedProfile(int userHandle, String message)7954     private void enforceManagedProfile(int userHandle, String message) {
7955         if(!isManagedProfile(userHandle)) {
7956             throw new SecurityException("You can not " + message + " outside a managed profile.");
7957         }
7958     }
7959 
enforceNotManagedProfile(int userHandle, String message)7960     private void enforceNotManagedProfile(int userHandle, String message) {
7961         if(isManagedProfile(userHandle)) {
7962             throw new SecurityException("You can not " + message + " for a managed profile.");
7963         }
7964     }
7965 
enforceDeviceOwnerOrManageUsers()7966     private void enforceDeviceOwnerOrManageUsers() {
7967         synchronized (getLockObject()) {
7968             if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7969                     mInjector.binderGetCallingUid()) != null) {
7970                 return;
7971             }
7972         }
7973         enforceManageUsers();
7974     }
7975 
enforceProfileOwnerOrSystemUser()7976     private void enforceProfileOwnerOrSystemUser() {
7977         synchronized (getLockObject()) {
7978             if (getActiveAdminWithPolicyForUidLocked(null,
7979                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7980                             != null) {
7981                 return;
7982             }
7983         }
7984         Preconditions.checkState(isCallerWithSystemUid(),
7985                 "Only profile owner, device owner and system may call this method.");
7986     }
7987 
enforceProfileOwnerOrFullCrossUsersPermission(int userId)7988     private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7989         if (userId == mInjector.userHandleGetCallingUserId()) {
7990             synchronized (getLockObject()) {
7991                 if (getActiveAdminWithPolicyForUidLocked(null,
7992                         DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7993                                 != null) {
7994                     // Device Owner/Profile Owner may access the user it runs on.
7995                     return;
7996                 }
7997             }
7998         }
7999         // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
8000         enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
8001     }
8002 
canUserUseLockTaskLocked(int userId)8003     private boolean canUserUseLockTaskLocked(int userId) {
8004         if (isUserAffiliatedWithDeviceLocked(userId)) {
8005             return true;
8006         }
8007 
8008         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
8009         if (mOwners.hasDeviceOwner()) {
8010             return false;
8011         }
8012 
8013         final ComponentName profileOwner = getProfileOwner(userId);
8014         if (profileOwner == null) {
8015             return false;
8016         }
8017 
8018         // Managed profiles are not allowed to use lock task
8019         if (isManagedProfile(userId)) {
8020             return false;
8021         }
8022 
8023         return true;
8024     }
8025 
enforceCanCallLockTaskLocked(ComponentName who)8026     private void enforceCanCallLockTaskLocked(ComponentName who) {
8027         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8028         final int userId =  mInjector.userHandleGetCallingUserId();
8029         if (!canUserUseLockTaskLocked(userId)) {
8030             throw new SecurityException("User " + userId + " is not allowed to use lock task");
8031         }
8032     }
8033 
ensureCallerPackage(@ullable String packageName)8034     private void ensureCallerPackage(@Nullable String packageName) {
8035         if (packageName == null) {
8036             Preconditions.checkState(isCallerWithSystemUid(),
8037                     "Only caller can omit package name");
8038         } else {
8039             final int callingUid = mInjector.binderGetCallingUid();
8040             final int userId = mInjector.userHandleGetCallingUserId();
8041             try {
8042                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
8043                         packageName, 0, userId);
8044                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
8045             } catch (RemoteException e) {
8046                 // Shouldn't happen
8047             }
8048         }
8049     }
8050 
isCallerWithSystemUid()8051     private boolean isCallerWithSystemUid() {
8052         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
8053     }
8054 
getProfileParentId(int userHandle)8055     protected int getProfileParentId(int userHandle) {
8056         final long ident = mInjector.binderClearCallingIdentity();
8057         try {
8058             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
8059             return parentUser != null ? parentUser.id : userHandle;
8060         } finally {
8061             mInjector.binderRestoreCallingIdentity(ident);
8062         }
8063     }
8064 
getCredentialOwner(int userHandle, boolean parent)8065     private int getCredentialOwner(int userHandle, boolean parent) {
8066         final long ident = mInjector.binderClearCallingIdentity();
8067         try {
8068             if (parent) {
8069                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
8070                 if (parentProfile != null) {
8071                     userHandle = parentProfile.id;
8072                 }
8073             }
8074             return mUserManager.getCredentialOwnerProfile(userHandle);
8075         } finally {
8076             mInjector.binderRestoreCallingIdentity(ident);
8077         }
8078     }
8079 
isManagedProfile(int userHandle)8080     private boolean isManagedProfile(int userHandle) {
8081         final UserInfo user = getUserInfo(userHandle);
8082         return user != null && user.isManagedProfile();
8083     }
8084 
enableIfNecessary(String packageName, int userId)8085     private void enableIfNecessary(String packageName, int userId) {
8086         try {
8087             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
8088                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
8089             if (ai.enabledSetting
8090                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
8091                 mIPackageManager.setApplicationEnabledSetting(packageName,
8092                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
8093                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8094             }
8095         } catch (RemoteException e) {
8096         }
8097     }
8098 
8099     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)8100     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8101         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
8102 
8103         synchronized (getLockObject()) {
8104             pw.println("Current Device Policy Manager state:");
8105 
8106             mOwners.dump("  ", pw);
8107             mDeviceAdminServiceController.dump("  ", pw);
8108             int userCount = mUserData.size();
8109             for (int u = 0; u < userCount; u++) {
8110                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
8111                 pw.println();
8112                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
8113                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
8114                 final int N = policy.mAdminList.size();
8115                 for (int i=0; i<N; i++) {
8116                     ActiveAdmin ap = policy.mAdminList.get(i);
8117                     if (ap != null) {
8118                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
8119                                 pw.println(":");
8120                         ap.dump("      ", pw);
8121                     }
8122                 }
8123                 if (!policy.mRemovingAdmins.isEmpty()) {
8124                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
8125                             + policy.mRemovingAdmins);
8126                 }
8127 
8128                 pw.println(" ");
8129                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
8130             }
8131             pw.println();
8132             mConstants.dump("  ", pw);
8133             pw.println();
8134             mStatLogger.dump(pw, "  ");
8135             pw.println();
8136             pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
8137         }
8138     }
8139 
getEncryptionStatusName(int encryptionStatus)8140     private String getEncryptionStatusName(int encryptionStatus) {
8141         switch (encryptionStatus) {
8142             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
8143                 return "inactive";
8144             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
8145                 return "block default key";
8146             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
8147                 return "block";
8148             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
8149                 return "per-user";
8150             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
8151                 return "unsupported";
8152             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
8153                 return "activating";
8154             default:
8155                 return "unknown";
8156         }
8157     }
8158 
8159     @Override
addPersistentPreferredActivity(ComponentName who, IntentFilter filter, ComponentName activity)8160     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
8161             ComponentName activity) {
8162         Preconditions.checkNotNull(who, "ComponentName is null");
8163         final int userHandle = UserHandle.getCallingUserId();
8164         synchronized (getLockObject()) {
8165             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8166 
8167             long id = mInjector.binderClearCallingIdentity();
8168             try {
8169                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
8170                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8171             } catch (RemoteException re) {
8172                 // Shouldn't happen
8173             } finally {
8174                 mInjector.binderRestoreCallingIdentity(id);
8175             }
8176         }
8177     }
8178 
8179     @Override
clearPackagePersistentPreferredActivities(ComponentName who, String packageName)8180     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
8181         Preconditions.checkNotNull(who, "ComponentName is null");
8182         final int userHandle = UserHandle.getCallingUserId();
8183         synchronized (getLockObject()) {
8184             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8185 
8186             long id = mInjector.binderClearCallingIdentity();
8187             try {
8188                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
8189                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8190             } catch (RemoteException re) {
8191                 // Shouldn't happen
8192             } finally {
8193                 mInjector.binderRestoreCallingIdentity(id);
8194             }
8195         }
8196     }
8197 
8198     @Override
setDefaultSmsApplication(ComponentName admin, String packageName)8199     public void setDefaultSmsApplication(ComponentName admin, String packageName) {
8200         Preconditions.checkNotNull(admin, "ComponentName is null");
8201         synchronized (getLockObject()) {
8202             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8203         }
8204         mInjector.binderWithCleanCallingIdentity(() ->
8205                 SmsApplication.setDefaultApplication(packageName, mContext));
8206     }
8207 
8208     @Override
setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName)8209     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
8210             String packageName) {
8211         try {
8212             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
8213         } catch (IllegalArgumentException e) {
8214             return false;
8215         }
8216         return true;
8217     }
8218 
8219     @Override
getApplicationRestrictionsManagingPackage(ComponentName admin)8220     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
8221         final List<String> delegatePackages = getDelegatePackages(admin,
8222                 DELEGATION_APP_RESTRICTIONS);
8223         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
8224     }
8225 
8226     @Override
isCallerApplicationRestrictionsManagingPackage(String callerPackage)8227     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
8228         return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
8229     }
8230 
8231     @Override
setApplicationRestrictions(ComponentName who, String callerPackage, String packageName, Bundle settings)8232     public void setApplicationRestrictions(ComponentName who, String callerPackage,
8233             String packageName, Bundle settings) {
8234         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8235                 DELEGATION_APP_RESTRICTIONS);
8236 
8237         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8238         final long id = mInjector.binderClearCallingIdentity();
8239         try {
8240             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
8241         } finally {
8242             mInjector.binderRestoreCallingIdentity(id);
8243         }
8244     }
8245 
8246     @Override
setTrustAgentConfiguration(ComponentName admin, ComponentName agent, PersistableBundle args, boolean parent)8247     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
8248             PersistableBundle args, boolean parent) {
8249         if (!mHasFeature) {
8250             return;
8251         }
8252         Preconditions.checkNotNull(admin, "admin is null");
8253         Preconditions.checkNotNull(agent, "agent is null");
8254         final int userHandle = UserHandle.getCallingUserId();
8255         synchronized (getLockObject()) {
8256             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
8257                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
8258             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
8259             saveSettingsLocked(userHandle);
8260         }
8261     }
8262 
8263     @Override
getTrustAgentConfiguration(ComponentName admin, ComponentName agent, int userHandle, boolean parent)8264     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
8265             ComponentName agent, int userHandle, boolean parent) {
8266         if (!mHasFeature) {
8267             return null;
8268         }
8269         Preconditions.checkNotNull(agent, "agent null");
8270         enforceFullCrossUsersPermission(userHandle);
8271 
8272         synchronized (getLockObject()) {
8273             final String componentName = agent.flattenToString();
8274             if (admin != null) {
8275                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
8276                 if (ap == null) return null;
8277                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
8278                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
8279                 List<PersistableBundle> result = new ArrayList<>();
8280                 result.add(trustAgentInfo.options);
8281                 return result;
8282             }
8283 
8284             // Return strictest policy for this user and profiles that are visible from this user.
8285             List<PersistableBundle> result = null;
8286             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
8287             // of the options. If any admin doesn't have options, discard options for the rest
8288             // and return null.
8289             List<ActiveAdmin> admins =
8290                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
8291             boolean allAdminsHaveOptions = true;
8292             final int N = admins.size();
8293             for (int i = 0; i < N; i++) {
8294                 final ActiveAdmin active = admins.get(i);
8295 
8296                 final boolean disablesTrust = (active.disabledKeyguardFeatures
8297                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
8298                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
8299                 if (info != null && info.options != null && !info.options.isEmpty()) {
8300                     if (disablesTrust) {
8301                         if (result == null) {
8302                             result = new ArrayList<>();
8303                         }
8304                         result.add(info.options);
8305                     } else {
8306                         Log.w(LOG_TAG, "Ignoring admin " + active.info
8307                                 + " because it has trust options but doesn't declare "
8308                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
8309                     }
8310                 } else if (disablesTrust) {
8311                     allAdminsHaveOptions = false;
8312                     break;
8313                 }
8314             }
8315             return allAdminsHaveOptions ? result : null;
8316         }
8317     }
8318 
8319     @Override
setRestrictionsProvider(ComponentName who, ComponentName permissionProvider)8320     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
8321         Preconditions.checkNotNull(who, "ComponentName is null");
8322         synchronized (getLockObject()) {
8323             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8324 
8325             int userHandle = UserHandle.getCallingUserId();
8326             DevicePolicyData userData = getUserData(userHandle);
8327             userData.mRestrictionsProvider = permissionProvider;
8328             saveSettingsLocked(userHandle);
8329         }
8330     }
8331 
8332     @Override
getRestrictionsProvider(int userHandle)8333     public ComponentName getRestrictionsProvider(int userHandle) {
8334         synchronized (getLockObject()) {
8335             if (!isCallerWithSystemUid()) {
8336                 throw new SecurityException("Only the system can query the permission provider");
8337             }
8338             DevicePolicyData userData = getUserData(userHandle);
8339             return userData != null ? userData.mRestrictionsProvider : null;
8340         }
8341     }
8342 
8343     @Override
addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags)8344     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
8345         Preconditions.checkNotNull(who, "ComponentName is null");
8346         int callingUserId = UserHandle.getCallingUserId();
8347         synchronized (getLockObject()) {
8348             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8349 
8350             long id = mInjector.binderClearCallingIdentity();
8351             try {
8352                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
8353                 if (parent == null) {
8354                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
8355                             + "parent");
8356                     return;
8357                 }
8358                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
8359                     mIPackageManager.addCrossProfileIntentFilter(
8360                             filter, who.getPackageName(), callingUserId, parent.id, 0);
8361                 }
8362                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
8363                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
8364                             parent.id, callingUserId, 0);
8365                 }
8366             } catch (RemoteException re) {
8367                 // Shouldn't happen
8368             } finally {
8369                 mInjector.binderRestoreCallingIdentity(id);
8370             }
8371         }
8372     }
8373 
8374     @Override
clearCrossProfileIntentFilters(ComponentName who)8375     public void clearCrossProfileIntentFilters(ComponentName who) {
8376         Preconditions.checkNotNull(who, "ComponentName is null");
8377         int callingUserId = UserHandle.getCallingUserId();
8378         synchronized (getLockObject()) {
8379             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8380             long id = mInjector.binderClearCallingIdentity();
8381             try {
8382                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
8383                 if (parent == null) {
8384                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
8385                             + "parent");
8386                     return;
8387                 }
8388                 // Removing those that go from the managed profile to the parent.
8389                 mIPackageManager.clearCrossProfileIntentFilters(
8390                         callingUserId, who.getPackageName());
8391                 // And those that go from the parent to the managed profile.
8392                 // If we want to support multiple managed profiles, we will have to only remove
8393                 // those that have callingUserId as their target.
8394                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
8395             } catch (RemoteException re) {
8396                 // Shouldn't happen
8397             } finally {
8398                 mInjector.binderRestoreCallingIdentity(id);
8399             }
8400         }
8401     }
8402 
8403     /**
8404      * @return true if all packages in enabledPackages are either in the list
8405      * permittedList or are a system app.
8406      */
checkPackagesInPermittedListOrSystem(List<String> enabledPackages, List<String> permittedList, int userIdToCheck)8407     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
8408             List<String> permittedList, int userIdToCheck) {
8409         long id = mInjector.binderClearCallingIdentity();
8410         try {
8411             // If we have an enabled packages list for a managed profile the packages
8412             // we should check are installed for the parent user.
8413             UserInfo user = getUserInfo(userIdToCheck);
8414             if (user.isManagedProfile()) {
8415                 userIdToCheck = user.profileGroupId;
8416             }
8417 
8418             for (String enabledPackage : enabledPackages) {
8419                 boolean systemService = false;
8420                 try {
8421                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
8422                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
8423                             userIdToCheck);
8424                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8425                 } catch (RemoteException e) {
8426                     Log.i(LOG_TAG, "Can't talk to package managed", e);
8427                 }
8428                 if (!systemService && !permittedList.contains(enabledPackage)) {
8429                     return false;
8430                 }
8431             }
8432         } finally {
8433             mInjector.binderRestoreCallingIdentity(id);
8434         }
8435         return true;
8436     }
8437 
getAccessibilityManagerForUser(int userId)8438     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
8439         // Not using AccessibilityManager.getInstance because that guesses
8440         // at the user you require based on callingUid and caches for a given
8441         // process.
8442         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
8443         IAccessibilityManager service = iBinder == null
8444                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
8445         return new AccessibilityManager(mContext, service, userId);
8446     }
8447 
8448     @Override
setPermittedAccessibilityServices(ComponentName who, List packageList)8449     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
8450         if (!mHasFeature) {
8451             return false;
8452         }
8453         Preconditions.checkNotNull(who, "ComponentName is null");
8454 
8455         if (packageList != null) {
8456             int userId = UserHandle.getCallingUserId();
8457             List<AccessibilityServiceInfo> enabledServices = null;
8458             long id = mInjector.binderClearCallingIdentity();
8459             try {
8460                 UserInfo user = getUserInfo(userId);
8461                 if (user.isManagedProfile()) {
8462                     userId = user.profileGroupId;
8463                 }
8464                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
8465                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
8466                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
8467             } finally {
8468                 mInjector.binderRestoreCallingIdentity(id);
8469             }
8470 
8471             if (enabledServices != null) {
8472                 List<String> enabledPackages = new ArrayList<String>();
8473                 for (AccessibilityServiceInfo service : enabledServices) {
8474                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
8475                 }
8476                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8477                         userId)) {
8478                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
8479                             + "because it contains already enabled accesibility services.");
8480                     return false;
8481                 }
8482             }
8483         }
8484 
8485         synchronized (getLockObject()) {
8486             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8487                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8488             admin.permittedAccessiblityServices = packageList;
8489             saveSettingsLocked(UserHandle.getCallingUserId());
8490         }
8491         return true;
8492     }
8493 
8494     @Override
getPermittedAccessibilityServices(ComponentName who)8495     public List getPermittedAccessibilityServices(ComponentName who) {
8496         if (!mHasFeature) {
8497             return null;
8498         }
8499         Preconditions.checkNotNull(who, "ComponentName is null");
8500 
8501         synchronized (getLockObject()) {
8502             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8503                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8504             return admin.permittedAccessiblityServices;
8505         }
8506     }
8507 
8508     @Override
getPermittedAccessibilityServicesForUser(int userId)8509     public List getPermittedAccessibilityServicesForUser(int userId) {
8510         if (!mHasFeature) {
8511             return null;
8512         }
8513         enforceManageUsers();
8514         synchronized (getLockObject()) {
8515             List<String> result = null;
8516             // If we have multiple profiles we return the intersection of the
8517             // permitted lists. This can happen in cases where we have a device
8518             // and profile owner.
8519             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8520             for (int profileId : profileIds) {
8521                 // Just loop though all admins, only device or profiles
8522                 // owners can have permitted lists set.
8523                 DevicePolicyData policy = getUserDataUnchecked(profileId);
8524                 final int N = policy.mAdminList.size();
8525                 for (int j = 0; j < N; j++) {
8526                     ActiveAdmin admin = policy.mAdminList.get(j);
8527                     List<String> fromAdmin = admin.permittedAccessiblityServices;
8528                     if (fromAdmin != null) {
8529                         if (result == null) {
8530                             result = new ArrayList<>(fromAdmin);
8531                         } else {
8532                             result.retainAll(fromAdmin);
8533                         }
8534                     }
8535                 }
8536             }
8537 
8538             // If we have a permitted list add all system accessibility services.
8539             if (result != null) {
8540                 long id = mInjector.binderClearCallingIdentity();
8541                 try {
8542                     UserInfo user = getUserInfo(userId);
8543                     if (user.isManagedProfile()) {
8544                         userId = user.profileGroupId;
8545                     }
8546                     AccessibilityManager accessibilityManager =
8547                             getAccessibilityManagerForUser(userId);
8548                     List<AccessibilityServiceInfo> installedServices =
8549                             accessibilityManager.getInstalledAccessibilityServiceList();
8550 
8551                     if (installedServices != null) {
8552                         for (AccessibilityServiceInfo service : installedServices) {
8553                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
8554                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8555                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8556                                 result.add(serviceInfo.packageName);
8557                             }
8558                         }
8559                     }
8560                 } finally {
8561                     mInjector.binderRestoreCallingIdentity(id);
8562                 }
8563             }
8564 
8565             return result;
8566         }
8567     }
8568 
8569     @Override
isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, int userHandle)8570     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
8571             int userHandle) {
8572         if (!mHasFeature) {
8573             return true;
8574         }
8575         Preconditions.checkNotNull(who, "ComponentName is null");
8576         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8577         if (!isCallerWithSystemUid()){
8578             throw new SecurityException(
8579                     "Only the system can query if an accessibility service is disabled by admin");
8580         }
8581         synchronized (getLockObject()) {
8582             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8583             if (admin == null) {
8584                 return false;
8585             }
8586             if (admin.permittedAccessiblityServices == null) {
8587                 return true;
8588             }
8589             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8590                     admin.permittedAccessiblityServices, userHandle);
8591         }
8592     }
8593 
checkCallerIsCurrentUserOrProfile()8594     private boolean checkCallerIsCurrentUserOrProfile() {
8595         final int callingUserId = UserHandle.getCallingUserId();
8596         final long token = mInjector.binderClearCallingIdentity();
8597         try {
8598             UserInfo currentUser;
8599             UserInfo callingUser = getUserInfo(callingUserId);
8600             try {
8601                 currentUser = mInjector.getIActivityManager().getCurrentUser();
8602             } catch (RemoteException e) {
8603                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
8604                 return false;
8605             }
8606 
8607             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
8608                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
8609                         + "of a user that isn't the foreground user.");
8610                 return false;
8611             }
8612             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
8613                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
8614                         + "of a user that isn't the foreground user.");
8615                 return false;
8616             }
8617         } finally {
8618             mInjector.binderRestoreCallingIdentity(token);
8619         }
8620         return true;
8621     }
8622 
8623     @Override
setPermittedInputMethods(ComponentName who, List packageList)8624     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
8625         if (!mHasFeature) {
8626             return false;
8627         }
8628         Preconditions.checkNotNull(who, "ComponentName is null");
8629 
8630         // TODO When InputMethodManager supports per user calls remove
8631         //      this restriction.
8632         if (!checkCallerIsCurrentUserOrProfile()) {
8633             return false;
8634         }
8635 
8636         final int callingUserId = mInjector.userHandleGetCallingUserId();
8637         if (packageList != null) {
8638             // InputMethodManager fetches input methods for current user.
8639             // So this can only be set when calling user is the current user
8640             // or parent is current user in case of managed profiles.
8641             InputMethodManager inputMethodManager =
8642                     mContext.getSystemService(InputMethodManager.class);
8643             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
8644 
8645             if (enabledImes != null) {
8646                 List<String> enabledPackages = new ArrayList<String>();
8647                 for (InputMethodInfo ime : enabledImes) {
8648                     enabledPackages.add(ime.getPackageName());
8649                 }
8650                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8651                         callingUserId)) {
8652                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
8653                             + "because it contains already enabled input method.");
8654                     return false;
8655                 }
8656             }
8657         }
8658 
8659         synchronized (getLockObject()) {
8660             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8661                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8662             admin.permittedInputMethods = packageList;
8663             saveSettingsLocked(callingUserId);
8664         }
8665         return true;
8666     }
8667 
8668     @Override
getPermittedInputMethods(ComponentName who)8669     public List getPermittedInputMethods(ComponentName who) {
8670         if (!mHasFeature) {
8671             return null;
8672         }
8673         Preconditions.checkNotNull(who, "ComponentName is null");
8674 
8675         synchronized (getLockObject()) {
8676             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8677                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8678             return admin.permittedInputMethods;
8679         }
8680     }
8681 
8682     @Override
getPermittedInputMethodsForCurrentUser()8683     public List getPermittedInputMethodsForCurrentUser() {
8684         enforceManageUsers();
8685         UserInfo currentUser;
8686         try {
8687             currentUser = mInjector.getIActivityManager().getCurrentUser();
8688         } catch (RemoteException e) {
8689             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
8690             // Activity managed is dead, just allow all IMEs
8691             return null;
8692         }
8693 
8694         int userId = currentUser.id;
8695         synchronized (getLockObject()) {
8696             List<String> result = null;
8697             // If we have multiple profiles we return the intersection of the
8698             // permitted lists. This can happen in cases where we have a device
8699             // and profile owner.
8700             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8701             for (int profileId : profileIds) {
8702                 // Just loop though all admins, only device or profiles
8703                 // owners can have permitted lists set.
8704                 DevicePolicyData policy = getUserDataUnchecked(profileId);
8705                 final int N = policy.mAdminList.size();
8706                 for (int j = 0; j < N; j++) {
8707                     ActiveAdmin admin = policy.mAdminList.get(j);
8708                     List<String> fromAdmin = admin.permittedInputMethods;
8709                     if (fromAdmin != null) {
8710                         if (result == null) {
8711                             result = new ArrayList<String>(fromAdmin);
8712                         } else {
8713                             result.retainAll(fromAdmin);
8714                         }
8715                     }
8716                 }
8717             }
8718 
8719             // If we have a permitted list add all system input methods.
8720             if (result != null) {
8721                 InputMethodManager inputMethodManager =
8722                         mContext.getSystemService(InputMethodManager.class);
8723                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8724                 long id = mInjector.binderClearCallingIdentity();
8725                 try {
8726                     if (imes != null) {
8727                         for (InputMethodInfo ime : imes) {
8728                             ServiceInfo serviceInfo = ime.getServiceInfo();
8729                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8730                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8731                                 result.add(serviceInfo.packageName);
8732                             }
8733                         }
8734                     }
8735                 } finally {
8736                     mInjector.binderRestoreCallingIdentity(id);
8737                 }
8738             }
8739             return result;
8740         }
8741     }
8742 
8743     @Override
isInputMethodPermittedByAdmin(ComponentName who, String packageName, int userHandle)8744     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8745             int userHandle) {
8746         if (!mHasFeature) {
8747             return true;
8748         }
8749         Preconditions.checkNotNull(who, "ComponentName is null");
8750         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8751         if (!isCallerWithSystemUid()) {
8752             throw new SecurityException(
8753                     "Only the system can query if an input method is disabled by admin");
8754         }
8755         synchronized (getLockObject()) {
8756             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8757             if (admin == null) {
8758                 return false;
8759             }
8760             if (admin.permittedInputMethods == null) {
8761                 return true;
8762             }
8763             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8764                     admin.permittedInputMethods, userHandle);
8765         }
8766     }
8767 
8768     @Override
setPermittedCrossProfileNotificationListeners( ComponentName who, List<String> packageList)8769     public boolean setPermittedCrossProfileNotificationListeners(
8770             ComponentName who, List<String> packageList) {
8771         if (!mHasFeature) {
8772             return false;
8773         }
8774         Preconditions.checkNotNull(who, "ComponentName is null");
8775 
8776         final int callingUserId = mInjector.userHandleGetCallingUserId();
8777         if (!isManagedProfile(callingUserId)) {
8778             return false;
8779         }
8780 
8781         synchronized (getLockObject()) {
8782             ActiveAdmin admin = getActiveAdminForCallerLocked(
8783                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8784             admin.permittedNotificationListeners = packageList;
8785             saveSettingsLocked(callingUserId);
8786         }
8787         return true;
8788     }
8789 
8790     @Override
getPermittedCrossProfileNotificationListeners(ComponentName who)8791     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8792         if (!mHasFeature) {
8793             return null;
8794         }
8795         Preconditions.checkNotNull(who, "ComponentName is null");
8796 
8797         synchronized (getLockObject()) {
8798             ActiveAdmin admin = getActiveAdminForCallerLocked(
8799                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8800             return admin.permittedNotificationListeners;
8801         }
8802     }
8803 
8804     @Override
isNotificationListenerServicePermitted(String packageName, int userId)8805     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8806         if (!mHasFeature) {
8807             return true;
8808         }
8809 
8810         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8811         if (!isCallerWithSystemUid()) {
8812             throw new SecurityException(
8813                     "Only the system can query if a notification listener service is permitted");
8814         }
8815         synchronized (getLockObject()) {
8816             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8817             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8818                 return true;
8819             }
8820             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8821                     profileOwner.permittedNotificationListeners, userId);
8822 
8823         }
8824     }
8825 
maybeSendAdminEnabledBroadcastLocked(int userHandle)8826     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
8827         DevicePolicyData policyData = getUserData(userHandle);
8828         if (policyData.mAdminBroadcastPending) {
8829             // Send the initialization data to profile owner and delete the data
8830             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8831             boolean clearInitBundle = true;
8832             if (admin != null) {
8833                 PersistableBundle initBundle = policyData.mInitBundle;
8834                 clearInitBundle = sendAdminCommandLocked(admin,
8835                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8836                         initBundle == null ? null : new Bundle(initBundle),
8837                         null /* result receiver */,
8838                         true /* send in foreground */);
8839             }
8840             if (clearInitBundle) {
8841                 // If there's no admin or we've successfully called the admin, clear the init bundle
8842                 // otherwise, keep it around
8843                 policyData.mInitBundle = null;
8844                 policyData.mAdminBroadcastPending = false;
8845                 saveSettingsLocked(userHandle);
8846             }
8847         }
8848     }
8849 
8850     @Override
createAndManageUser(ComponentName admin, String name, ComponentName profileOwner, PersistableBundle adminExtras, int flags)8851     public UserHandle createAndManageUser(ComponentName admin, String name,
8852             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8853         Preconditions.checkNotNull(admin, "admin is null");
8854         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8855         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8856             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8857                     + admin + " are not in the same package");
8858         }
8859         // Only allow the system user to use this method
8860         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8861             throw new SecurityException("createAndManageUser was called from non-system user");
8862         }
8863         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8864         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8865                 && UserManager.isDeviceInDemoMode(mContext);
8866         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
8867         final int targetSdkVersion;
8868 
8869         // Create user.
8870         UserHandle user = null;
8871         synchronized (getLockObject()) {
8872             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8873 
8874             final int callingUid = mInjector.binderGetCallingUid();
8875             final long id = mInjector.binderClearCallingIdentity();
8876             try {
8877                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
8878                         callingUid);
8879 
8880                 // Return detail error code for checks inside
8881                 // UserManagerService.createUserInternalUnchecked.
8882                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
8883                         LocalServices.getService(DeviceStorageMonitorInternal.class);
8884                 if (deviceStorageMonitorInternal.isMemoryLow()) {
8885                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
8886                         throw new ServiceSpecificException(
8887                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
8888                     } else {
8889                         return null;
8890                     }
8891                 }
8892                 if (!mUserManager.canAddMoreUsers()) {
8893                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
8894                         throw new ServiceSpecificException(
8895                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
8896                     } else {
8897                         return null;
8898                     }
8899                 }
8900 
8901                 int userInfoFlags = 0;
8902                 if (ephemeral) {
8903                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8904                 }
8905                 if (demo) {
8906                     userInfoFlags |= UserInfo.FLAG_DEMO;
8907                 }
8908                 String[] disallowedPackages = null;
8909                 if (!leaveAllSystemAppsEnabled) {
8910                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
8911                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
8912                             new String[0]);
8913                 }
8914                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8915                         userInfoFlags, disallowedPackages);
8916                 if (userInfo != null) {
8917                     user = userInfo.getUserHandle();
8918                 }
8919             } finally {
8920                 mInjector.binderRestoreCallingIdentity(id);
8921             }
8922         }
8923         if (user == null) {
8924             if (targetSdkVersion >= Build.VERSION_CODES.P) {
8925                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
8926                         "failed to create user");
8927             } else {
8928                 return null;
8929             }
8930         }
8931 
8932         final int userHandle = user.getIdentifier();
8933         final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
8934                 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
8935                 .putExtra(
8936                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
8937                         leaveAllSystemAppsEnabled)
8938                 .setPackage(getManagedProvisioningPackage(mContext))
8939                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8940         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
8941 
8942         final long id = mInjector.binderClearCallingIdentity();
8943         try {
8944             final String adminPkg = admin.getPackageName();
8945             try {
8946                 // Install the profile owner if not present.
8947                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8948                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8949                             0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8950                 }
8951             } catch (RemoteException e) {
8952                 // Does not happen, same process
8953             }
8954 
8955             // Set admin.
8956             setActiveAdmin(profileOwner, true, userHandle);
8957             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8958             setProfileOwner(profileOwner, ownerName, userHandle);
8959 
8960             synchronized (getLockObject()) {
8961                 DevicePolicyData policyData = getUserData(userHandle);
8962                 policyData.mInitBundle = adminExtras;
8963                 policyData.mAdminBroadcastPending = true;
8964                 saveSettingsLocked(userHandle);
8965             }
8966 
8967             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8968                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
8969                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8970             }
8971 
8972             return user;
8973         } catch (Throwable re) {
8974             mUserManager.removeUser(userHandle);
8975             if (targetSdkVersion >= Build.VERSION_CODES.P) {
8976                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
8977                         re.getMessage());
8978             } else {
8979                 return null;
8980             }
8981         } finally {
8982             mInjector.binderRestoreCallingIdentity(id);
8983         }
8984     }
8985 
8986     @Override
removeUser(ComponentName who, UserHandle userHandle)8987     public boolean removeUser(ComponentName who, UserHandle userHandle) {
8988         Preconditions.checkNotNull(who, "ComponentName is null");
8989         Preconditions.checkNotNull(userHandle, "UserHandle is null");
8990 
8991         synchronized (getLockObject()) {
8992             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8993         }
8994 
8995         final int callingUserId = mInjector.userHandleGetCallingUserId();
8996         final long id = mInjector.binderClearCallingIdentity();
8997         try {
8998             String restriction = isManagedProfile(userHandle.getIdentifier())
8999                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
9000                     : UserManager.DISALLOW_REMOVE_USER;
9001             if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
9002                 Log.w(LOG_TAG, "The device owner cannot remove a user because "
9003                         + restriction + " is enabled, and was not set by the device owner");
9004                 return false;
9005             }
9006             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
9007         } finally {
9008             mInjector.binderRestoreCallingIdentity(id);
9009         }
9010     }
9011 
isAdminAffectedByRestriction( ComponentName admin, String userRestriction, int userId)9012     private boolean isAdminAffectedByRestriction(
9013             ComponentName admin, String userRestriction, int userId) {
9014         switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
9015             case UserManager.RESTRICTION_NOT_SET:
9016                 return false;
9017             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
9018                 return !isDeviceOwner(admin, userId);
9019             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
9020                 return !isProfileOwner(admin, userId);
9021             default:
9022                 return true;
9023         }
9024     }
9025 
9026     @Override
switchUser(ComponentName who, UserHandle userHandle)9027     public boolean switchUser(ComponentName who, UserHandle userHandle) {
9028         Preconditions.checkNotNull(who, "ComponentName is null");
9029 
9030         synchronized (getLockObject()) {
9031             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9032 
9033             long id = mInjector.binderClearCallingIdentity();
9034             try {
9035                 int userId = UserHandle.USER_SYSTEM;
9036                 if (userHandle != null) {
9037                     userId = userHandle.getIdentifier();
9038                 }
9039                 return mInjector.getIActivityManager().switchUser(userId);
9040             } catch (RemoteException e) {
9041                 Log.e(LOG_TAG, "Couldn't switch user", e);
9042                 return false;
9043             } finally {
9044                 mInjector.binderRestoreCallingIdentity(id);
9045             }
9046         }
9047     }
9048 
9049     @Override
startUserInBackground(ComponentName who, UserHandle userHandle)9050     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
9051         Preconditions.checkNotNull(who, "ComponentName is null");
9052         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9053 
9054         synchronized (getLockObject()) {
9055             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9056         }
9057 
9058         final int userId = userHandle.getIdentifier();
9059         if (isManagedProfile(userId)) {
9060             Log.w(LOG_TAG, "Managed profile cannot be started in background");
9061             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9062         }
9063 
9064         final long id = mInjector.binderClearCallingIdentity();
9065         try {
9066             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
9067                 Log.w(LOG_TAG, "Cannot start more users in background");
9068                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
9069             }
9070 
9071             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
9072                 return UserManager.USER_OPERATION_SUCCESS;
9073             } else {
9074                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9075             }
9076         } catch (RemoteException e) {
9077             // Same process, should not happen.
9078             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9079         } finally {
9080             mInjector.binderRestoreCallingIdentity(id);
9081         }
9082     }
9083 
9084     @Override
stopUser(ComponentName who, UserHandle userHandle)9085     public int stopUser(ComponentName who, UserHandle userHandle) {
9086         Preconditions.checkNotNull(who, "ComponentName is null");
9087         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9088 
9089         synchronized (getLockObject()) {
9090             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9091         }
9092 
9093         final int userId = userHandle.getIdentifier();
9094         if (isManagedProfile(userId)) {
9095             Log.w(LOG_TAG, "Managed profile cannot be stopped");
9096             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9097         }
9098 
9099         return stopUserUnchecked(userId);
9100     }
9101 
9102     @Override
logoutUser(ComponentName who)9103     public int logoutUser(ComponentName who) {
9104         Preconditions.checkNotNull(who, "ComponentName is null");
9105 
9106         final int callingUserId = mInjector.userHandleGetCallingUserId();
9107         synchronized (getLockObject()) {
9108             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9109             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9110                 throw new SecurityException("Admin " + who +
9111                         " is neither the device owner or affiliated user's profile owner.");
9112             }
9113         }
9114 
9115         if (isManagedProfile(callingUserId)) {
9116             Log.w(LOG_TAG, "Managed profile cannot be logout");
9117             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9118         }
9119 
9120         final long id = mInjector.binderClearCallingIdentity();
9121         try {
9122             if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) {
9123                 Log.w(LOG_TAG, "Failed to switch to primary user");
9124                 // This should never happen as target user is UserHandle.USER_SYSTEM
9125                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9126             }
9127         } catch (RemoteException e) {
9128             // Same process, should not happen.
9129             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9130         } finally {
9131             mInjector.binderRestoreCallingIdentity(id);
9132         }
9133 
9134         return stopUserUnchecked(callingUserId);
9135     }
9136 
stopUserUnchecked(int userId)9137     private int stopUserUnchecked(int userId) {
9138         final long id = mInjector.binderClearCallingIdentity();
9139         try {
9140             switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
9141                 case ActivityManager.USER_OP_SUCCESS:
9142                     return UserManager.USER_OPERATION_SUCCESS;
9143                 case ActivityManager.USER_OP_IS_CURRENT:
9144                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
9145                 default:
9146                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9147             }
9148         } catch (RemoteException e) {
9149             // Same process, should not happen.
9150             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9151         } finally {
9152             mInjector.binderRestoreCallingIdentity(id);
9153         }
9154     }
9155 
9156     @Override
getSecondaryUsers(ComponentName who)9157     public List<UserHandle> getSecondaryUsers(ComponentName who) {
9158         Preconditions.checkNotNull(who, "ComponentName is null");
9159         synchronized (getLockObject()) {
9160             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9161         }
9162 
9163         final long id = mInjector.binderClearCallingIdentity();
9164         try {
9165             final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true
9166                     /*excludeDying*/);
9167             final List<UserHandle> userHandles = new ArrayList<>();
9168             for (UserInfo userInfo : userInfos) {
9169                 UserHandle userHandle = userInfo.getUserHandle();
9170                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
9171                     userHandles.add(userInfo.getUserHandle());
9172                 }
9173             }
9174             return userHandles;
9175         } finally {
9176             mInjector.binderRestoreCallingIdentity(id);
9177         }
9178     }
9179 
9180     @Override
isEphemeralUser(ComponentName who)9181     public boolean isEphemeralUser(ComponentName who) {
9182         Preconditions.checkNotNull(who, "ComponentName is null");
9183         synchronized (getLockObject()) {
9184             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9185         }
9186 
9187         final int callingUserId = mInjector.userHandleGetCallingUserId();
9188         final long id = mInjector.binderClearCallingIdentity();
9189         try {
9190             return mInjector.getUserManager().isUserEphemeral(callingUserId);
9191         } finally {
9192             mInjector.binderRestoreCallingIdentity(id);
9193         }
9194     }
9195 
9196     @Override
getApplicationRestrictions(ComponentName who, String callerPackage, String packageName)9197     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
9198             String packageName) {
9199         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9200                 DELEGATION_APP_RESTRICTIONS);
9201 
9202         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
9203         final long id = mInjector.binderClearCallingIdentity();
9204         try {
9205            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
9206            // if no restrictions were saved, mUserManager.getApplicationRestrictions
9207            // returns null, but DPM method should return an empty Bundle as per JavaDoc
9208            return bundle != null ? bundle : Bundle.EMPTY;
9209         } finally {
9210             mInjector.binderRestoreCallingIdentity(id);
9211         }
9212     }
9213 
9214     @Override
setPackagesSuspended(ComponentName who, String callerPackage, String[] packageNames, boolean suspended)9215     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
9216             String[] packageNames, boolean suspended) {
9217         int callingUserId = UserHandle.getCallingUserId();
9218         synchronized (getLockObject()) {
9219             // Ensure the caller is a DO/PO or a package access delegate.
9220             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9221                     DELEGATION_PACKAGE_ACCESS);
9222 
9223             long id = mInjector.binderClearCallingIdentity();
9224             try {
9225                 return mIPackageManager.setPackagesSuspendedAsUser(packageNames, suspended,
9226                         null, null, null, PLATFORM_PACKAGE_NAME, callingUserId);
9227             } catch (RemoteException re) {
9228                 // Shouldn't happen.
9229                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9230             } finally {
9231                 mInjector.binderRestoreCallingIdentity(id);
9232             }
9233             return packageNames;
9234         }
9235     }
9236 
9237     @Override
isPackageSuspended(ComponentName who, String callerPackage, String packageName)9238     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
9239         int callingUserId = UserHandle.getCallingUserId();
9240         synchronized (getLockObject()) {
9241             // Ensure the caller is a DO/PO or a package access delegate.
9242             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9243                     DELEGATION_PACKAGE_ACCESS);
9244 
9245             long id = mInjector.binderClearCallingIdentity();
9246             try {
9247                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
9248             } catch (RemoteException re) {
9249                 // Shouldn't happen.
9250                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9251             } finally {
9252                 mInjector.binderRestoreCallingIdentity(id);
9253             }
9254             return false;
9255         }
9256     }
9257 
9258     @Override
setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner)9259     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
9260         Preconditions.checkNotNull(who, "ComponentName is null");
9261         if (!UserRestrictionsUtils.isValidRestriction(key)) {
9262             return;
9263         }
9264 
9265         final int userHandle = mInjector.userHandleGetCallingUserId();
9266         synchronized (getLockObject()) {
9267             final ActiveAdmin activeAdmin =
9268                     getActiveAdminForCallerLocked(who,
9269                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9270             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
9271             if (isDeviceOwner) {
9272                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
9273                     throw new SecurityException("Device owner cannot set user restriction " + key);
9274                 }
9275             } else { // profile owner
9276                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
9277                     throw new SecurityException("Profile owner cannot set user restriction " + key);
9278                 }
9279             }
9280 
9281             // Save the restriction to ActiveAdmin.
9282             final Bundle restrictions = activeAdmin.ensureUserRestrictions();
9283             if (enabledFromThisOwner) {
9284                 restrictions.putBoolean(key, true);
9285             } else {
9286                 restrictions.remove(key);
9287             }
9288             saveUserRestrictionsLocked(userHandle);
9289         }
9290         if (SecurityLog.isLoggingEnabled()) {
9291             final int eventTag = enabledFromThisOwner
9292                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
9293                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
9294             SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key);
9295         }
9296     }
9297 
saveUserRestrictionsLocked(int userId)9298     private void saveUserRestrictionsLocked(int userId) {
9299         saveSettingsLocked(userId);
9300         pushUserRestrictions(userId);
9301         sendChangedNotification(userId);
9302     }
9303 
pushUserRestrictions(int userId)9304     private void pushUserRestrictions(int userId) {
9305         synchronized (getLockObject()) {
9306             final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
9307             final Bundle userRestrictions;
9308             // Whether device owner enforces camera restriction.
9309             boolean disallowCameraGlobally = false;
9310 
9311             if (isDeviceOwner) {
9312                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9313                 if (deviceOwner == null) {
9314                     return; // Shouldn't happen.
9315                 }
9316                 userRestrictions = deviceOwner.userRestrictions;
9317                 // DO can disable camera globally.
9318                 disallowCameraGlobally = deviceOwner.disableCamera;
9319             } else {
9320                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
9321                 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
9322             }
9323 
9324             // Whether any admin enforces camera restriction.
9325             final int cameraRestrictionScope =
9326                     getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
9327 
9328             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
9329                     isDeviceOwner, cameraRestrictionScope);
9330         }
9331     }
9332 
9333     /**
9334      * Get the scope of camera restriction for a given user if any.
9335      */
getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally)9336     private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
9337         if (disallowCameraGlobally) {
9338             return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
9339         } else if (getCameraDisabled(
9340                 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
9341             return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
9342         }
9343         return UserManagerInternal.CAMERA_NOT_DISABLED;
9344     }
9345 
9346     @Override
getUserRestrictions(ComponentName who)9347     public Bundle getUserRestrictions(ComponentName who) {
9348         if (!mHasFeature) {
9349             return null;
9350         }
9351         Preconditions.checkNotNull(who, "ComponentName is null");
9352         synchronized (getLockObject()) {
9353             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
9354                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9355             return activeAdmin.userRestrictions;
9356         }
9357     }
9358 
9359     @Override
setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden)9360     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
9361             boolean hidden) {
9362         int callingUserId = UserHandle.getCallingUserId();
9363         synchronized (getLockObject()) {
9364             // Ensure the caller is a DO/PO or a package access delegate.
9365             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9366                     DELEGATION_PACKAGE_ACCESS);
9367 
9368             long id = mInjector.binderClearCallingIdentity();
9369             try {
9370                 return mIPackageManager.setApplicationHiddenSettingAsUser(
9371                         packageName, hidden, callingUserId);
9372             } catch (RemoteException re) {
9373                 // shouldn't happen
9374                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
9375             } finally {
9376                 mInjector.binderRestoreCallingIdentity(id);
9377             }
9378             return false;
9379         }
9380     }
9381 
9382     @Override
isApplicationHidden(ComponentName who, String callerPackage, String packageName)9383     public boolean isApplicationHidden(ComponentName who, String callerPackage,
9384             String packageName) {
9385         int callingUserId = UserHandle.getCallingUserId();
9386         synchronized (getLockObject()) {
9387             // Ensure the caller is a DO/PO or a package access delegate.
9388             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9389                     DELEGATION_PACKAGE_ACCESS);
9390 
9391             long id = mInjector.binderClearCallingIdentity();
9392             try {
9393                 return mIPackageManager.getApplicationHiddenSettingAsUser(
9394                         packageName, callingUserId);
9395             } catch (RemoteException re) {
9396                 // shouldn't happen
9397                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
9398             } finally {
9399                 mInjector.binderRestoreCallingIdentity(id);
9400             }
9401             return false;
9402         }
9403     }
9404 
9405     @Override
enableSystemApp(ComponentName who, String callerPackage, String packageName)9406     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
9407         synchronized (getLockObject()) {
9408             // Ensure the caller is a DO/PO or an enable system app delegate.
9409             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9410                     DELEGATION_ENABLE_SYSTEM_APP);
9411 
9412             final boolean isDemo = isCurrentUserDemo();
9413 
9414             int userId = UserHandle.getCallingUserId();
9415             long id = mInjector.binderClearCallingIdentity();
9416 
9417             try {
9418                 if (VERBOSE_LOG) {
9419                     Slog.v(LOG_TAG, "installing " + packageName + " for "
9420                             + userId);
9421                 }
9422 
9423                 int parentUserId = getProfileParentId(userId);
9424                 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
9425                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
9426                 }
9427 
9428                 // Install the app.
9429                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
9430                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9431                 if (isDemo) {
9432                     // Ensure the app is also ENABLED for demo users.
9433                     mIPackageManager.setApplicationEnabledSetting(packageName,
9434                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
9435                             PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
9436                 }
9437             } catch (RemoteException re) {
9438                 // shouldn't happen
9439                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
9440             } finally {
9441                 mInjector.binderRestoreCallingIdentity(id);
9442             }
9443         }
9444     }
9445 
9446     @Override
enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)9447     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
9448         synchronized (getLockObject()) {
9449             // Ensure the caller is a DO/PO or an enable system app delegate.
9450             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9451                     DELEGATION_ENABLE_SYSTEM_APP);
9452 
9453             int userId = UserHandle.getCallingUserId();
9454             long id = mInjector.binderClearCallingIdentity();
9455 
9456             try {
9457                 int parentUserId = getProfileParentId(userId);
9458                 List<ResolveInfo> activitiesToEnable = mIPackageManager
9459                         .queryIntentActivities(intent,
9460                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
9461                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
9462                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
9463                                 parentUserId)
9464                         .getList();
9465 
9466                 if (VERBOSE_LOG) {
9467                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
9468                 }
9469                 int numberOfAppsInstalled = 0;
9470                 if (activitiesToEnable != null) {
9471                     for (ResolveInfo info : activitiesToEnable) {
9472                         if (info.activityInfo != null) {
9473                             String packageName = info.activityInfo.packageName;
9474                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
9475                                 numberOfAppsInstalled++;
9476                                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
9477                                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9478                             } else {
9479                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
9480                                         + " system app");
9481                             }
9482                         }
9483                     }
9484                 }
9485                 return numberOfAppsInstalled;
9486             } catch (RemoteException e) {
9487                 // shouldn't happen
9488                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
9489                 return 0;
9490             } finally {
9491                 mInjector.binderRestoreCallingIdentity(id);
9492             }
9493         }
9494     }
9495 
isSystemApp(IPackageManager pm, String packageName, int userId)9496     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
9497             throws RemoteException {
9498         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
9499                 userId);
9500         if (appInfo == null) {
9501             throw new IllegalArgumentException("The application " + packageName +
9502                     " is not present on this device");
9503         }
9504         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9505     }
9506 
9507     @Override
installExistingPackage(ComponentName who, String callerPackage, String packageName)9508     public boolean installExistingPackage(ComponentName who, String callerPackage,
9509             String packageName) {
9510         synchronized (getLockObject()) {
9511             // Ensure the caller is a PO or an install existing package delegate
9512             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9513                     DELEGATION_INSTALL_EXISTING_PACKAGE);
9514             final int callingUserId = mInjector.userHandleGetCallingUserId();
9515             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9516                 throw new SecurityException("Admin " + who +
9517                         " is neither the device owner or affiliated user's profile owner.");
9518             }
9519 
9520             final long id = mInjector.binderClearCallingIdentity();
9521             try {
9522                 if (VERBOSE_LOG) {
9523                     Slog.v(LOG_TAG, "installing " + packageName + " for "
9524                             + callingUserId);
9525                 }
9526 
9527                 // Install the package.
9528                 return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId,
9529                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY)
9530                         == PackageManager.INSTALL_SUCCEEDED;
9531             } catch (RemoteException re) {
9532                 // shouldn't happen
9533                 return false;
9534             } finally {
9535                 mInjector.binderRestoreCallingIdentity(id);
9536             }
9537         }
9538     }
9539 
9540     @Override
setAccountManagementDisabled(ComponentName who, String accountType, boolean disabled)9541     public void setAccountManagementDisabled(ComponentName who, String accountType,
9542             boolean disabled) {
9543         if (!mHasFeature) {
9544             return;
9545         }
9546         Preconditions.checkNotNull(who, "ComponentName is null");
9547         synchronized (getLockObject()) {
9548             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
9549                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9550             if (disabled) {
9551                 ap.accountTypesWithManagementDisabled.add(accountType);
9552             } else {
9553                 ap.accountTypesWithManagementDisabled.remove(accountType);
9554             }
9555             saveSettingsLocked(UserHandle.getCallingUserId());
9556         }
9557     }
9558 
9559     @Override
getAccountTypesWithManagementDisabled()9560     public String[] getAccountTypesWithManagementDisabled() {
9561         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
9562     }
9563 
9564     @Override
getAccountTypesWithManagementDisabledAsUser(int userId)9565     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
9566         enforceFullCrossUsersPermission(userId);
9567         if (!mHasFeature) {
9568             return null;
9569         }
9570         synchronized (getLockObject()) {
9571             DevicePolicyData policy = getUserData(userId);
9572             final int N = policy.mAdminList.size();
9573             ArraySet<String> resultSet = new ArraySet<>();
9574             for (int i = 0; i < N; i++) {
9575                 ActiveAdmin admin = policy.mAdminList.get(i);
9576                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
9577             }
9578             return resultSet.toArray(new String[resultSet.size()]);
9579         }
9580     }
9581 
9582     @Override
setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)9583     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
9584             boolean uninstallBlocked) {
9585         final int userId = UserHandle.getCallingUserId();
9586         synchronized (getLockObject()) {
9587             // Ensure the caller is a DO/PO or a block uninstall delegate
9588             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9589                     DELEGATION_BLOCK_UNINSTALL);
9590 
9591             long id = mInjector.binderClearCallingIdentity();
9592             try {
9593                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
9594             } catch (RemoteException re) {
9595                 // Shouldn't happen.
9596                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
9597             } finally {
9598                 mInjector.binderRestoreCallingIdentity(id);
9599             }
9600         }
9601     }
9602 
9603     @Override
isUninstallBlocked(ComponentName who, String packageName)9604     public boolean isUninstallBlocked(ComponentName who, String packageName) {
9605         // This function should return true if and only if the package is blocked by
9606         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
9607         // when the package is a system app, or when it is an active device admin.
9608         final int userId = UserHandle.getCallingUserId();
9609 
9610         synchronized (getLockObject()) {
9611             if (who != null) {
9612                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9613             }
9614 
9615             long id = mInjector.binderClearCallingIdentity();
9616             try {
9617                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
9618             } catch (RemoteException re) {
9619                 // Shouldn't happen.
9620                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
9621             } finally {
9622                 mInjector.binderRestoreCallingIdentity(id);
9623             }
9624         }
9625         return false;
9626     }
9627 
9628     @Override
setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)9629     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
9630         if (!mHasFeature) {
9631             return;
9632         }
9633         Preconditions.checkNotNull(who, "ComponentName is null");
9634         synchronized (getLockObject()) {
9635             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9636                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9637             if (admin.disableCallerId != disabled) {
9638                 admin.disableCallerId = disabled;
9639                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9640             }
9641         }
9642     }
9643 
9644     @Override
getCrossProfileCallerIdDisabled(ComponentName who)9645     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
9646         if (!mHasFeature) {
9647             return false;
9648         }
9649         Preconditions.checkNotNull(who, "ComponentName is null");
9650         synchronized (getLockObject()) {
9651             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9652                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9653             return admin.disableCallerId;
9654         }
9655     }
9656 
9657     @Override
getCrossProfileCallerIdDisabledForUser(int userId)9658     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
9659         enforceCrossUsersPermission(userId);
9660         synchronized (getLockObject()) {
9661             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9662             return (admin != null) ? admin.disableCallerId : false;
9663         }
9664     }
9665 
9666     @Override
setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)9667     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
9668         if (!mHasFeature) {
9669             return;
9670         }
9671         Preconditions.checkNotNull(who, "ComponentName is null");
9672         synchronized (getLockObject()) {
9673             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9674                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9675             if (admin.disableContactsSearch != disabled) {
9676                 admin.disableContactsSearch = disabled;
9677                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9678             }
9679         }
9680     }
9681 
9682     @Override
getCrossProfileContactsSearchDisabled(ComponentName who)9683     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
9684         if (!mHasFeature) {
9685             return false;
9686         }
9687         Preconditions.checkNotNull(who, "ComponentName is null");
9688         synchronized (getLockObject()) {
9689             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9690                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9691             return admin.disableContactsSearch;
9692         }
9693     }
9694 
9695     @Override
getCrossProfileContactsSearchDisabledForUser(int userId)9696     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
9697         enforceCrossUsersPermission(userId);
9698         synchronized (getLockObject()) {
9699             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9700             return (admin != null) ? admin.disableContactsSearch : false;
9701         }
9702     }
9703 
9704     @Override
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)9705     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9706             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
9707         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
9708                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
9709         final int callingUserId = UserHandle.getCallingUserId();
9710 
9711         final long ident = mInjector.binderClearCallingIdentity();
9712         try {
9713             synchronized (getLockObject()) {
9714                 final int managedUserId = getManagedUserId(callingUserId);
9715                 if (managedUserId < 0) {
9716                     return;
9717                 }
9718                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
9719                     if (VERBOSE_LOG) {
9720                         Log.v(LOG_TAG,
9721                                 "Cross-profile contacts access disabled for user " + managedUserId);
9722                     }
9723                     return;
9724                 }
9725                 ContactsInternal.startQuickContactWithErrorToastForUser(
9726                         mContext, intent, new UserHandle(managedUserId));
9727             }
9728         } finally {
9729             mInjector.binderRestoreCallingIdentity(ident);
9730         }
9731     }
9732 
9733     /**
9734      * @return true if cross-profile QuickContact is disabled
9735      */
isCrossProfileQuickContactDisabled(int userId)9736     private boolean isCrossProfileQuickContactDisabled(int userId) {
9737         return getCrossProfileCallerIdDisabledForUser(userId)
9738                 && getCrossProfileContactsSearchDisabledForUser(userId);
9739     }
9740 
9741     /**
9742      * @return the user ID of the managed user that is linked to the current user, if any.
9743      * Otherwise -1.
9744      */
getManagedUserId(int callingUserId)9745     public int getManagedUserId(int callingUserId) {
9746         if (VERBOSE_LOG) {
9747             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
9748         }
9749 
9750         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
9751             if (ui.id == callingUserId || !ui.isManagedProfile()) {
9752                 continue; // Caller user self, or not a managed profile.  Skip.
9753             }
9754             if (VERBOSE_LOG) {
9755                 Log.v(LOG_TAG, "Managed user=" + ui.id);
9756             }
9757             return ui.id;
9758         }
9759         if (VERBOSE_LOG) {
9760             Log.v(LOG_TAG, "Managed user not found.");
9761         }
9762         return -1;
9763     }
9764 
9765     @Override
setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)9766     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
9767         if (!mHasFeature) {
9768             return;
9769         }
9770         Preconditions.checkNotNull(who, "ComponentName is null");
9771         synchronized (getLockObject()) {
9772             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9773                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9774             if (admin.disableBluetoothContactSharing != disabled) {
9775                 admin.disableBluetoothContactSharing = disabled;
9776                 saveSettingsLocked(UserHandle.getCallingUserId());
9777             }
9778         }
9779     }
9780 
9781     @Override
getBluetoothContactSharingDisabled(ComponentName who)9782     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
9783         if (!mHasFeature) {
9784             return false;
9785         }
9786         Preconditions.checkNotNull(who, "ComponentName is null");
9787         synchronized (getLockObject()) {
9788             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9789                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9790             return admin.disableBluetoothContactSharing;
9791         }
9792     }
9793 
9794     @Override
getBluetoothContactSharingDisabledForUser(int userId)9795     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
9796         // TODO: Should there be a check to make sure this relationship is
9797         // within a profile group?
9798         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
9799         synchronized (getLockObject()) {
9800             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9801             return (admin != null) ? admin.disableBluetoothContactSharing : false;
9802         }
9803     }
9804 
9805     @Override
setLockTaskPackages(ComponentName who, String[] packages)9806     public void setLockTaskPackages(ComponentName who, String[] packages)
9807             throws SecurityException {
9808         Preconditions.checkNotNull(who, "ComponentName is null");
9809         Preconditions.checkNotNull(packages, "packages is null");
9810 
9811         synchronized (getLockObject()) {
9812             enforceCanCallLockTaskLocked(who);
9813             final int userHandle = mInjector.userHandleGetCallingUserId();
9814             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
9815         }
9816     }
9817 
setLockTaskPackagesLocked(int userHandle, List<String> packages)9818     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
9819         DevicePolicyData policy = getUserData(userHandle);
9820         policy.mLockTaskPackages = packages;
9821 
9822         // Store the settings persistently.
9823         saveSettingsLocked(userHandle);
9824         updateLockTaskPackagesLocked(packages, userHandle);
9825     }
9826 
9827     @Override
getLockTaskPackages(ComponentName who)9828     public String[] getLockTaskPackages(ComponentName who) {
9829         Preconditions.checkNotNull(who, "ComponentName is null");
9830 
9831         final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
9832         synchronized (getLockObject()) {
9833             enforceCanCallLockTaskLocked(who);
9834             final List<String> packages = getUserData(userHandle).mLockTaskPackages;
9835             return packages.toArray(new String[packages.size()]);
9836         }
9837     }
9838 
9839     @Override
isLockTaskPermitted(String pkg)9840     public boolean isLockTaskPermitted(String pkg) {
9841         final int userHandle = mInjector.userHandleGetCallingUserId();
9842         synchronized (getLockObject()) {
9843             return getUserData(userHandle).mLockTaskPackages.contains(pkg);
9844         }
9845     }
9846 
9847     @Override
setLockTaskFeatures(ComponentName who, int flags)9848     public void setLockTaskFeatures(ComponentName who, int flags) {
9849         Preconditions.checkNotNull(who, "ComponentName is null");
9850 
9851         // Throw if Overview is used without Home.
9852         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
9853         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
9854         Preconditions.checkArgument(hasHome || !hasOverview,
9855                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
9856         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
9857         Preconditions.checkArgument(hasHome || !hasNotification,
9858             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
9859 
9860         final int userHandle = mInjector.userHandleGetCallingUserId();
9861         synchronized (getLockObject()) {
9862             enforceCanCallLockTaskLocked(who);
9863             setLockTaskFeaturesLocked(userHandle, flags);
9864         }
9865     }
9866 
setLockTaskFeaturesLocked(int userHandle, int flags)9867     private void setLockTaskFeaturesLocked(int userHandle, int flags) {
9868         DevicePolicyData policy = getUserData(userHandle);
9869         policy.mLockTaskFeatures = flags;
9870         saveSettingsLocked(userHandle);
9871         updateLockTaskFeaturesLocked(flags, userHandle);
9872     }
9873 
9874     @Override
getLockTaskFeatures(ComponentName who)9875     public int getLockTaskFeatures(ComponentName who) {
9876         Preconditions.checkNotNull(who, "ComponentName is null");
9877         final int userHandle = mInjector.userHandleGetCallingUserId();
9878         synchronized (getLockObject()) {
9879             enforceCanCallLockTaskLocked(who);
9880             return getUserData(userHandle).mLockTaskFeatures;
9881         }
9882     }
9883 
maybeClearLockTaskPolicyLocked()9884     private void maybeClearLockTaskPolicyLocked() {
9885         final long ident = mInjector.binderClearCallingIdentity();
9886         try {
9887             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
9888             for (int i = userInfos.size() - 1; i >= 0; i--) {
9889                 int userId = userInfos.get(i).id;
9890                 if (canUserUseLockTaskLocked(userId)) {
9891                     continue;
9892                 }
9893 
9894                 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
9895                 if (!lockTaskPackages.isEmpty()) {
9896                     Slog.d(LOG_TAG,
9897                             "User id " + userId + " not affiliated. Clearing lock task packages");
9898                     setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
9899                 }
9900                 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
9901                 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
9902                     Slog.d(LOG_TAG,
9903                             "User id " + userId + " not affiliated. Clearing lock task features");
9904                     setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
9905                 }
9906             }
9907         } finally {
9908             mInjector.binderRestoreCallingIdentity(ident);
9909         }
9910     }
9911 
9912     @Override
notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)9913     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
9914         if (!isCallerWithSystemUid()) {
9915             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
9916         }
9917         synchronized (getLockObject()) {
9918             final DevicePolicyData policy = getUserData(userHandle);
9919 
9920             if (policy.mStatusBarDisabled) {
9921                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
9922                 // policy when LockTask starts, and reapply it when LockTask ends
9923                 setStatusBarDisabledInternal(!isEnabled, userHandle);
9924             }
9925 
9926             Bundle adminExtras = new Bundle();
9927             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
9928             for (ActiveAdmin admin : policy.mAdminList) {
9929                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
9930                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
9931                 if (ownsDevice || ownsProfile) {
9932                     if (isEnabled) {
9933                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
9934                                 adminExtras, null);
9935                     } else {
9936                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
9937                     }
9938                 }
9939             }
9940         }
9941     }
9942 
9943     @Override
setGlobalSetting(ComponentName who, String setting, String value)9944     public void setGlobalSetting(ComponentName who, String setting, String value) {
9945         Preconditions.checkNotNull(who, "ComponentName is null");
9946 
9947         synchronized (getLockObject()) {
9948             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9949 
9950             // Some settings are no supported any more. However we do not want to throw a
9951             // SecurityException to avoid breaking apps.
9952             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
9953                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
9954                 return;
9955             }
9956 
9957             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
9958                     && !UserManager.isDeviceInDemoMode(mContext)) {
9959                 throw new SecurityException(String.format(
9960                         "Permission denial: device owners cannot update %1$s", setting));
9961             }
9962 
9963             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
9964                 // ignore if it contradicts an existing policy
9965                 long timeMs = getMaximumTimeToLock(
9966                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
9967                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
9968                     return;
9969                 }
9970             }
9971 
9972             long id = mInjector.binderClearCallingIdentity();
9973             try {
9974                 mInjector.settingsGlobalPutString(setting, value);
9975             } finally {
9976                 mInjector.binderRestoreCallingIdentity(id);
9977             }
9978         }
9979     }
9980 
9981     @Override
setSystemSetting(ComponentName who, String setting, String value)9982     public void setSystemSetting(ComponentName who, String setting, String value) {
9983         Preconditions.checkNotNull(who, "ComponentName is null");
9984         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
9985 
9986         synchronized (getLockObject()) {
9987             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9988 
9989             if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) {
9990                 throw new SecurityException(String.format(
9991                         "Permission denial: device owners cannot update %1$s", setting));
9992             }
9993 
9994             final int callingUserId = mInjector.userHandleGetCallingUserId();
9995 
9996             mInjector.binderWithCleanCallingIdentity(() ->
9997                 mInjector.settingsSystemPutStringForUser(setting, value, callingUserId));
9998         }
9999     }
10000 
10001     @Override
setTime(ComponentName who, long millis)10002     public boolean setTime(ComponentName who, long millis) {
10003         Preconditions.checkNotNull(who, "ComponentName is null in setTime");
10004         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10005         // Don't allow set time when auto time is on.
10006         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
10007             return false;
10008         }
10009         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
10010         return true;
10011     }
10012 
10013     @Override
setTimeZone(ComponentName who, String timeZone)10014     public boolean setTimeZone(ComponentName who, String timeZone) {
10015         Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
10016         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10017         // Don't allow set timezone when auto timezone is on.
10018         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
10019             return false;
10020         }
10021         mInjector.binderWithCleanCallingIdentity(() ->
10022             mInjector.getAlarmManager().setTimeZone(timeZone));
10023         return true;
10024     }
10025 
10026     @Override
setSecureSetting(ComponentName who, String setting, String value)10027     public void setSecureSetting(ComponentName who, String setting, String value) {
10028         Preconditions.checkNotNull(who, "ComponentName is null");
10029         int callingUserId = mInjector.userHandleGetCallingUserId();
10030 
10031         synchronized (getLockObject()) {
10032             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10033 
10034             if (isDeviceOwner(who, callingUserId)) {
10035                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
10036                         && !isCurrentUserDemo()) {
10037                     throw new SecurityException(String.format(
10038                             "Permission denial: Device owners cannot update %1$s", setting));
10039                 }
10040             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
10041                 throw new SecurityException(String.format(
10042                         "Permission denial: Profile owners cannot update %1$s", setting));
10043             }
10044             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
10045                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
10046                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
10047                             + " is deprecated. Please use the user restriction "
10048                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
10049                 }
10050                 if (!mUserManager.isManagedProfile(callingUserId)) {
10051                     Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
10052                             + setting + ". User restriction "
10053                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
10054                             + " should be used instead.");
10055                 } else {
10056                     try {
10057                         setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
10058                                 (Integer.parseInt(value) == 0) ? true : false);
10059                     } catch (NumberFormatException exc) {
10060                         Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
10061                     }
10062                 }
10063                 return;
10064             }
10065             long id = mInjector.binderClearCallingIdentity();
10066             try {
10067                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
10068                     final String currentValue = mInjector.settingsSecureGetStringForUser(
10069                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
10070                     if (!TextUtils.equals(currentValue, value)) {
10071                         // Tell the content observer that the next change will be due to the owner
10072                         // changing the value. There is a small race condition here that we cannot
10073                         // avoid: Change notifications are sent asynchronously, so it is possible
10074                         // that there are prior notifications queued up before the one we are about
10075                         // to trigger. This is a corner case that will have no impact in practice.
10076                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
10077                     }
10078                     getUserData(callingUserId).mCurrentInputMethodSet = true;
10079                     saveSettingsLocked(callingUserId);
10080                 }
10081                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
10082             } finally {
10083                 mInjector.binderRestoreCallingIdentity(id);
10084             }
10085         }
10086     }
10087 
10088     @Override
setMasterVolumeMuted(ComponentName who, boolean on)10089     public void setMasterVolumeMuted(ComponentName who, boolean on) {
10090         Preconditions.checkNotNull(who, "ComponentName is null");
10091         synchronized (getLockObject()) {
10092             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10093             setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
10094         }
10095     }
10096 
10097     @Override
isMasterVolumeMuted(ComponentName who)10098     public boolean isMasterVolumeMuted(ComponentName who) {
10099         Preconditions.checkNotNull(who, "ComponentName is null");
10100         synchronized (getLockObject()) {
10101             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10102 
10103             AudioManager audioManager =
10104                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
10105             return audioManager.isMasterMute();
10106         }
10107     }
10108 
10109     @Override
setUserIcon(ComponentName who, Bitmap icon)10110     public void setUserIcon(ComponentName who, Bitmap icon) {
10111         synchronized (getLockObject()) {
10112             Preconditions.checkNotNull(who, "ComponentName is null");
10113             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10114 
10115             int userId = UserHandle.getCallingUserId();
10116             long id = mInjector.binderClearCallingIdentity();
10117             try {
10118                 mUserManagerInternal.setUserIcon(userId, icon);
10119             } finally {
10120                 mInjector.binderRestoreCallingIdentity(id);
10121             }
10122         }
10123     }
10124 
10125     @Override
setKeyguardDisabled(ComponentName who, boolean disabled)10126     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
10127         Preconditions.checkNotNull(who, "ComponentName is null");
10128         final int userId = mInjector.userHandleGetCallingUserId();
10129         synchronized (getLockObject()) {
10130             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10131             if (!isUserAffiliatedWithDeviceLocked(userId)) {
10132                 throw new SecurityException("Admin " + who +
10133                         " is neither the device owner or affiliated user's profile owner.");
10134             }
10135         }
10136         if (isManagedProfile(userId)) {
10137             throw new SecurityException("Managed profile cannot disable keyguard");
10138         }
10139 
10140         long ident = mInjector.binderClearCallingIdentity();
10141         try {
10142             // disallow disabling the keyguard if a password is currently set
10143             if (disabled && mLockPatternUtils.isSecure(userId)) {
10144                 return false;
10145             }
10146             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
10147             mInjector.getIWindowManager().dismissKeyguard(null /* callback */, null /* message */);
10148         } catch (RemoteException e) {
10149             // Same process, does not happen.
10150         } finally {
10151             mInjector.binderRestoreCallingIdentity(ident);
10152         }
10153         return true;
10154     }
10155 
10156     @Override
setStatusBarDisabled(ComponentName who, boolean disabled)10157     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
10158         int userId = UserHandle.getCallingUserId();
10159         synchronized (getLockObject()) {
10160             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10161             if (!isUserAffiliatedWithDeviceLocked(userId)) {
10162                 throw new SecurityException("Admin " + who +
10163                         " is neither the device owner or affiliated user's profile owner.");
10164             }
10165             if (isManagedProfile(userId)) {
10166                 throw new SecurityException("Managed profile cannot disable status bar");
10167             }
10168             DevicePolicyData policy = getUserData(userId);
10169             if (policy.mStatusBarDisabled != disabled) {
10170                 boolean isLockTaskMode = false;
10171                 try {
10172                     isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState()
10173                             != LOCK_TASK_MODE_NONE;
10174                 } catch (RemoteException e) {
10175                     Slog.e(LOG_TAG, "Failed to get LockTask mode");
10176                 }
10177                 if (!isLockTaskMode) {
10178                     if (!setStatusBarDisabledInternal(disabled, userId)) {
10179                         return false;
10180                     }
10181                 }
10182                 policy.mStatusBarDisabled = disabled;
10183                 saveSettingsLocked(userId);
10184             }
10185         }
10186         return true;
10187     }
10188 
setStatusBarDisabledInternal(boolean disabled, int userId)10189     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
10190         long ident = mInjector.binderClearCallingIdentity();
10191         try {
10192             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
10193                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
10194             if (statusBarService != null) {
10195                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
10196                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
10197                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
10198                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
10199                 return true;
10200             }
10201         } catch (RemoteException e) {
10202             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
10203         } finally {
10204             mInjector.binderRestoreCallingIdentity(ident);
10205         }
10206         return false;
10207     }
10208 
10209     /**
10210      * We need to update the internal state of whether a user has completed setup or a
10211      * device has paired once. After that, we ignore any changes that reset the
10212      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
10213      * as we don't trust any apps that might try to reset them.
10214      * <p>
10215      * Unfortunately, we don't know which user's setup state was changed, so we write all of
10216      * them.
10217      */
updateUserSetupCompleteAndPaired()10218     void updateUserSetupCompleteAndPaired() {
10219         List<UserInfo> users = mUserManager.getUsers(true);
10220         final int N = users.size();
10221         for (int i = 0; i < N; i++) {
10222             int userHandle = users.get(i).id;
10223             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
10224                     userHandle) != 0) {
10225                 DevicePolicyData policy = getUserData(userHandle);
10226                 if (!policy.mUserSetupComplete) {
10227                     policy.mUserSetupComplete = true;
10228                     synchronized (getLockObject()) {
10229                         saveSettingsLocked(userHandle);
10230                     }
10231                 }
10232             }
10233             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
10234                     userHandle) != 0) {
10235                 DevicePolicyData policy = getUserData(userHandle);
10236                 if (!policy.mPaired) {
10237                     policy.mPaired = true;
10238                     synchronized (getLockObject()) {
10239                         saveSettingsLocked(userHandle);
10240                     }
10241                 }
10242             }
10243         }
10244     }
10245 
10246     private class SetupContentObserver extends ContentObserver {
10247         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
10248                 Settings.Secure.USER_SETUP_COMPLETE);
10249         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
10250                 Settings.Global.DEVICE_PROVISIONED);
10251         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
10252         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
10253                 Settings.Secure.DEFAULT_INPUT_METHOD);
10254 
10255         @GuardedBy("getLockObject()")
10256         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
10257 
SetupContentObserver(Handler handler)10258         public SetupContentObserver(Handler handler) {
10259             super(handler);
10260         }
10261 
register()10262         void register() {
10263             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
10264             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
10265             if (mIsWatch) {
10266                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
10267             }
10268             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
10269         }
10270 
10271         @GuardedBy("getLockObject()")
addPendingChangeByOwnerLocked(int userId)10272         private void addPendingChangeByOwnerLocked(int userId) {
10273             mUserIdsWithPendingChangesByOwner.add(userId);
10274         }
10275 
10276         @Override
onChange(boolean selfChange, Uri uri, int userId)10277         public void onChange(boolean selfChange, Uri uri, int userId) {
10278             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
10279                 updateUserSetupCompleteAndPaired();
10280             } else if (mDeviceProvisioned.equals(uri)) {
10281                 synchronized (getLockObject()) {
10282                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
10283                     // is delayed until device is marked as provisioned.
10284                     setDeviceOwnerSystemPropertyLocked();
10285                 }
10286             } else if (mDefaultImeChanged.equals(uri)) {
10287                 synchronized (getLockObject()) {
10288                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
10289                         // This change notification was triggered by the owner changing the current
10290                         // IME. Ignore it.
10291                         mUserIdsWithPendingChangesByOwner.remove(userId);
10292                     } else {
10293                         // This change notification was triggered by the user manually changing the
10294                         // current IME.
10295                         getUserData(userId).mCurrentInputMethodSet = false;
10296                         saveSettingsLocked(userId);
10297                     }
10298                 }
10299             }
10300         }
10301     }
10302 
10303     @VisibleForTesting
10304     final class LocalService extends DevicePolicyManagerInternal {
10305         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
10306 
10307         @Override
getCrossProfileWidgetProviders(int profileId)10308         public List<String> getCrossProfileWidgetProviders(int profileId) {
10309             synchronized (getLockObject()) {
10310                 if (mOwners == null) {
10311                     return Collections.emptyList();
10312                 }
10313                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
10314                 if (ownerComponent == null) {
10315                     return Collections.emptyList();
10316                 }
10317 
10318                 DevicePolicyData policy = getUserDataUnchecked(profileId);
10319                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
10320 
10321                 if (admin == null || admin.crossProfileWidgetProviders == null
10322                         || admin.crossProfileWidgetProviders.isEmpty()) {
10323                     return Collections.emptyList();
10324                 }
10325 
10326                 return admin.crossProfileWidgetProviders;
10327             }
10328         }
10329 
10330         @Override
addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)10331         public void addOnCrossProfileWidgetProvidersChangeListener(
10332                 OnCrossProfileWidgetProvidersChangeListener listener) {
10333             synchronized (getLockObject()) {
10334                 if (mWidgetProviderListeners == null) {
10335                     mWidgetProviderListeners = new ArrayList<>();
10336                 }
10337                 if (!mWidgetProviderListeners.contains(listener)) {
10338                     mWidgetProviderListeners.add(listener);
10339                 }
10340             }
10341         }
10342 
10343         @Override
isActiveAdminWithPolicy(int uid, int reqPolicy)10344         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
10345             synchronized (getLockObject()) {
10346                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
10347             }
10348         }
10349 
notifyCrossProfileProvidersChanged(int userId, List<String> packages)10350         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
10351             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
10352             synchronized (getLockObject()) {
10353                 listeners = new ArrayList<>(mWidgetProviderListeners);
10354             }
10355             final int listenerCount = listeners.size();
10356             for (int i = 0; i < listenerCount; i++) {
10357                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
10358                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
10359             }
10360         }
10361 
10362         @Override
createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)10363         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
10364             // This method is called from AM with its lock held, so don't take the DPMS lock.
10365             // b/29242568
10366 
10367             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10368             if (profileOwner != null) {
10369                 return DevicePolicyManagerService.this
10370                         .createShowAdminSupportIntent(profileOwner, userId);
10371             }
10372 
10373             final Pair<Integer, ComponentName> deviceOwner =
10374                     mOwners.getDeviceOwnerUserIdAndComponent();
10375             if (deviceOwner != null && deviceOwner.first == userId) {
10376                 return DevicePolicyManagerService.this
10377                         .createShowAdminSupportIntent(deviceOwner.second, userId);
10378             }
10379 
10380             // We're not specifying the device admin because there isn't one.
10381             if (useDefaultIfNoAdmin) {
10382                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10383             }
10384             return null;
10385         }
10386 
10387         @Override
createUserRestrictionSupportIntent(int userId, String userRestriction)10388         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
10389             int source;
10390             long ident = mInjector.binderClearCallingIdentity();
10391             try {
10392                 source = mUserManager.getUserRestrictionSource(userRestriction,
10393                         UserHandle.of(userId));
10394             } finally {
10395                 mInjector.binderRestoreCallingIdentity(ident);
10396             }
10397             if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
10398                 /*
10399                  * In this case, the user restriction is enforced by the system.
10400                  * So we won't show an admin support intent, even if it is also
10401                  * enforced by a profile/device owner.
10402                  */
10403                 return null;
10404             }
10405             boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
10406             boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
10407             if (enforcedByDo && enforcedByPo) {
10408                 // In this case, we'll show an admin support dialog that does not
10409                 // specify the admin.
10410                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10411             } else if (enforcedByPo) {
10412                 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10413                 if (profileOwner != null) {
10414                     return DevicePolicyManagerService.this
10415                             .createShowAdminSupportIntent(profileOwner, userId);
10416                 }
10417                 // This could happen if another thread has changed the profile owner since we called
10418                 // getUserRestrictionSource
10419                 return null;
10420             } else if (enforcedByDo) {
10421                 final Pair<Integer, ComponentName> deviceOwner
10422                         = mOwners.getDeviceOwnerUserIdAndComponent();
10423                 if (deviceOwner != null) {
10424                     return DevicePolicyManagerService.this
10425                             .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
10426                 }
10427                 // This could happen if another thread has changed the device owner since we called
10428                 // getUserRestrictionSource
10429                 return null;
10430             }
10431             return null;
10432         }
10433 
10434         @Override
isUserAffiliatedWithDevice(int userId)10435         public boolean isUserAffiliatedWithDevice(int userId) {
10436             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
10437         }
10438 
10439         @Override
reportSeparateProfileChallengeChanged(@serIdInt int userId)10440         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
10441             synchronized (getLockObject()) {
10442                 updateMaximumTimeToLockLocked(userId);
10443             }
10444         }
10445 
10446         @Override
canUserHaveUntrustedCredentialReset(@serIdInt int userId)10447         public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
10448             return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId);
10449         }
10450 
10451         @Override
getPrintingDisabledReasonForUser(@serIdInt int userId)10452         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
10453             synchronized (getLockObject()) {
10454                 DevicePolicyData policy = getUserData(userId);
10455                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
10456                         UserHandle.of(userId))) {
10457                     Log.e(LOG_TAG, "printing is enabled");
10458                     return null;
10459                 }
10460                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
10461                 if (ownerPackage == null) {
10462                     ownerPackage = mOwners.getDeviceOwnerPackageName();
10463                 }
10464                 PackageManager pm = mInjector.getPackageManager();
10465                 PackageInfo packageInfo;
10466                 try {
10467                     packageInfo = pm.getPackageInfo(ownerPackage, 0);
10468                 } catch (NameNotFoundException e) {
10469                     Log.e(LOG_TAG, "getPackageInfo error", e);
10470                     return null;
10471                 }
10472                 if (packageInfo == null) {
10473                     Log.e(LOG_TAG, "packageInfo is inexplicably null");
10474                     return null;
10475                 }
10476                 ApplicationInfo appInfo = packageInfo.applicationInfo;
10477                 if (appInfo == null) {
10478                     Log.e(LOG_TAG, "appInfo is inexplicably null");
10479                     return null;
10480                 }
10481                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
10482                 if (appLabel == null) {
10483                     Log.e(LOG_TAG, "appLabel is inexplicably null");
10484                     return null;
10485                 }
10486                 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext())
10487                         .getResources().getString(R.string.printing_disabled_by, appLabel);
10488             }
10489         }
10490 
10491         @Override
getDevicePolicyCache()10492         protected DevicePolicyCache getDevicePolicyCache() {
10493             return mPolicyCache;
10494         }
10495     }
10496 
createShowAdminSupportIntent(ComponentName admin, int userId)10497     private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
10498         // This method is called with AMS lock held, so don't take DPMS lock
10499         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
10500         intent.putExtra(Intent.EXTRA_USER_ID, userId);
10501         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
10502         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10503         return intent;
10504     }
10505 
10506     @Override
createAdminSupportIntent(String restriction)10507     public Intent createAdminSupportIntent(String restriction) {
10508         Preconditions.checkNotNull(restriction);
10509         final int uid = mInjector.binderGetCallingUid();
10510         final int userId = UserHandle.getUserId(uid);
10511         Intent intent = null;
10512         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
10513                 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction) ||
10514                 DevicePolicyManager.POLICY_MANDATORY_BACKUPS.equals(restriction)) {
10515             synchronized (getLockObject()) {
10516                 final DevicePolicyData policy = getUserData(userId);
10517                 final int N = policy.mAdminList.size();
10518                 for (int i = 0; i < N; i++) {
10519                     final ActiveAdmin admin = policy.mAdminList.get(i);
10520                     if ((admin.disableCamera &&
10521                                 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
10522                         (admin.disableScreenCapture && DevicePolicyManager
10523                                 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) ||
10524                         (admin.mandatoryBackupTransport != null && DevicePolicyManager
10525                                 .POLICY_MANDATORY_BACKUPS.equals(restriction))) {
10526                         intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
10527                         break;
10528                     }
10529                 }
10530                 // For the camera, a device owner on a different user can disable it globally,
10531                 // so we need an additional check.
10532                 if (intent == null
10533                         && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
10534                     final ActiveAdmin admin = getDeviceOwnerAdminLocked();
10535                     if (admin != null && admin.disableCamera) {
10536                         intent = createShowAdminSupportIntent(admin.info.getComponent(),
10537                                 mOwners.getDeviceOwnerUserId());
10538                     }
10539                 }
10540             }
10541         } else {
10542             // if valid, |restriction| can only be a user restriction
10543             intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
10544         }
10545         if (intent != null) {
10546             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
10547         }
10548         return intent;
10549     }
10550 
10551     /**
10552      * Returns true if specified admin is allowed to limit passwords and has a
10553      * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
10554      */
isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)10555     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
10556         if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
10557             return false;
10558         }
10559         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
10560     }
10561 
10562     @Override
setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy)10563     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
10564         if (policy != null) {
10565             // throws exception if policy type is invalid
10566             policy.validateType();
10567             // throws exception if freeze period is invalid
10568             policy.validateFreezePeriods();
10569             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
10570             // throws exception if freeze period is incompatible with previous freeze period record
10571             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
10572                     LocalDate.now());
10573         }
10574         synchronized (getLockObject()) {
10575             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10576             if (policy == null) {
10577                 mOwners.clearSystemUpdatePolicy();
10578             } else {
10579                 mOwners.setSystemUpdatePolicy(policy);
10580                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
10581             }
10582             mOwners.writeDeviceOwner();
10583         }
10584         mContext.sendBroadcastAsUser(
10585                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
10586                 UserHandle.SYSTEM);
10587     }
10588 
10589     @Override
getSystemUpdatePolicy()10590     public SystemUpdatePolicy getSystemUpdatePolicy() {
10591         synchronized (getLockObject()) {
10592             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
10593             if (policy != null && !policy.isValid()) {
10594                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
10595                 return null;
10596             }
10597             return policy;
10598         }
10599     }
10600 
withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)10601     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
10602         return (!date.isBefore(range.first) && !date.isAfter(range.second));
10603     }
10604 
10605     /**
10606      * keeps track of the last continuous period when the system is under OTA freeze.
10607      *
10608      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
10609      * system update policy with freeze periods in effect. This is needed to make robust
10610      * validation on new system update polices, for example to prevent the OTA from being
10611      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
10612      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
10613      * a new freeze period after a few days.
10614      *
10615      * @param saveIfChanged whether to persist the result on disk if freeze period record is
10616      *            updated. This should only be set to {@code false} if there is a guaranteed
10617      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
10618      *            disk writes. Otherwise you risk inconsistent on-disk state.
10619      *
10620      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
10621      */
updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)10622     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
10623         Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
10624         synchronized (getLockObject()) {
10625             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
10626             if (policy == null) {
10627                 return;
10628             }
10629             final LocalDate now = LocalDate.now();
10630             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
10631             if (currentPeriod == null) {
10632                 return;
10633             }
10634             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
10635             final LocalDate start = record.first;
10636             final LocalDate end = record.second;
10637             final boolean changed;
10638             if (end == null || start == null) {
10639                 // Start a new period if there is none at the moment
10640                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10641             } else if (now.equals(end.plusDays(1))) {
10642                 // Extend the existing period
10643                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
10644             } else if (now.isAfter(end.plusDays(1))) {
10645                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
10646                     // The device might be off for some period. If the past freeze record
10647                     // is within range of the current freeze period, assume the device was off
10648                     // during the period [end, now] and extend the freeze record to [start, now].
10649                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
10650                 } else {
10651                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10652                 }
10653             } else if (now.isBefore(start)) {
10654                 // Systm clock was adjusted backwards, restart record
10655                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10656             } else /* start <= now <= end */ {
10657                 changed = false;
10658             }
10659             if (changed && saveIfChanged) {
10660                 mOwners.writeDeviceOwner();
10661             }
10662         }
10663     }
10664 
10665     @Override
clearSystemUpdatePolicyFreezePeriodRecord()10666     public void clearSystemUpdatePolicyFreezePeriodRecord() {
10667         enforceShell("clearSystemUpdatePolicyFreezePeriodRecord");
10668         synchronized (getLockObject()) {
10669             // Print out current record to help diagnosed CTS failures
10670             Slog.i(LOG_TAG, "Clear freeze period record: "
10671                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
10672             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
10673                 mOwners.writeDeviceOwner();
10674             }
10675         }
10676     }
10677 
10678     /**
10679      * Checks if the caller of the method is the device owner app.
10680      *
10681      * @param callerUid UID of the caller.
10682      * @return true if the caller is the device owner app
10683      */
10684     @VisibleForTesting
isCallerDeviceOwner(int callerUid)10685     boolean isCallerDeviceOwner(int callerUid) {
10686         synchronized (getLockObject()) {
10687             if (!mOwners.hasDeviceOwner()) {
10688                 return false;
10689             }
10690             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
10691                 return false;
10692             }
10693             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
10694                     .getPackageName();
10695                 try {
10696                     String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
10697                     for (String pkg : pkgs) {
10698                         if (deviceOwnerPackageName.equals(pkg)) {
10699                             return true;
10700                         }
10701                     }
10702                 } catch (RemoteException e) {
10703                     return false;
10704                 }
10705         }
10706 
10707         return false;
10708     }
10709 
10710     @Override
notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)10711     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
10712         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
10713                 "Only the system update service can broadcast update information");
10714 
10715         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
10716             Slog.w(LOG_TAG, "Only the system update service in the system user " +
10717                     "can broadcast update information.");
10718             return;
10719         }
10720 
10721         if (!mOwners.saveSystemUpdateInfo(info)) {
10722             // Pending system update hasn't changed, don't send duplicate notification.
10723             return;
10724         }
10725 
10726         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
10727                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
10728                         info == null ? -1 : info.getReceivedTime());
10729 
10730         final long ident = mInjector.binderClearCallingIdentity();
10731         try {
10732             synchronized (getLockObject()) {
10733                 // Broadcast to device owner first if there is one.
10734                 if (mOwners.hasDeviceOwner()) {
10735                     final UserHandle deviceOwnerUser =
10736                             UserHandle.of(mOwners.getDeviceOwnerUserId());
10737                     intent.setComponent(mOwners.getDeviceOwnerComponent());
10738                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
10739                 }
10740             }
10741             // Get running users.
10742             final int runningUserIds[];
10743             try {
10744                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
10745             } catch (RemoteException e) {
10746                 // Shouldn't happen.
10747                 Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
10748                 return;
10749             }
10750             // Send broadcasts to corresponding profile owners if any.
10751             for (final int userId : runningUserIds) {
10752                 synchronized (getLockObject()) {
10753                     final ComponentName profileOwnerPackage =
10754                             mOwners.getProfileOwnerComponent(userId);
10755                     if (profileOwnerPackage != null) {
10756                         intent.setComponent(profileOwnerPackage);
10757                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
10758                     }
10759                 }
10760             }
10761         } finally {
10762             mInjector.binderRestoreCallingIdentity(ident);
10763         }
10764     }
10765 
10766     @Override
getPendingSystemUpdate(ComponentName admin)10767     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
10768         Preconditions.checkNotNull(admin, "ComponentName is null");
10769         enforceProfileOrDeviceOwner(admin);
10770 
10771         return mOwners.getSystemUpdateInfo();
10772     }
10773 
10774     @Override
setPermissionPolicy(ComponentName admin, String callerPackage, int policy)10775     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
10776             throws RemoteException {
10777         int userId = UserHandle.getCallingUserId();
10778         synchronized (getLockObject()) {
10779             // Ensure the caller is a DO/PO or a permission grant state delegate.
10780             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10781                     DELEGATION_PERMISSION_GRANT);
10782             DevicePolicyData userPolicy = getUserData(userId);
10783             if (userPolicy.mPermissionPolicy != policy) {
10784                 userPolicy.mPermissionPolicy = policy;
10785                 saveSettingsLocked(userId);
10786             }
10787         }
10788     }
10789 
10790     @Override
getPermissionPolicy(ComponentName admin)10791     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
10792         int userId = UserHandle.getCallingUserId();
10793         synchronized (getLockObject()) {
10794             DevicePolicyData userPolicy = getUserData(userId);
10795             return userPolicy.mPermissionPolicy;
10796         }
10797     }
10798 
10799     @Override
setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState)10800     public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
10801             String packageName, String permission, int grantState) throws RemoteException {
10802         UserHandle user = mInjector.binderGetCallingUserHandle();
10803         synchronized (getLockObject()) {
10804             // Ensure the caller is a DO/PO or a permission grant state delegate.
10805             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10806                     DELEGATION_PERMISSION_GRANT);
10807             long ident = mInjector.binderClearCallingIdentity();
10808             try {
10809                 if (getTargetSdk(packageName, user.getIdentifier())
10810                         < android.os.Build.VERSION_CODES.M) {
10811                     return false;
10812                 }
10813                 if (!isRuntimePermission(permission)) {
10814                     return false;
10815                 }
10816                 final PackageManager packageManager = mInjector.getPackageManager();
10817                 switch (grantState) {
10818                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
10819                         mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
10820                                 permission, user.getIdentifier(), true /* override policy */);
10821                         packageManager.updatePermissionFlags(permission, packageName,
10822                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10823                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10824                     } break;
10825 
10826                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
10827                         mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
10828                                 permission, user.getIdentifier(), true /* override policy */);
10829                         packageManager.updatePermissionFlags(permission, packageName,
10830                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10831                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10832                     } break;
10833 
10834                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
10835                         packageManager.updatePermissionFlags(permission, packageName,
10836                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
10837                     } break;
10838                 }
10839                 return true;
10840             } catch (SecurityException se) {
10841                 return false;
10842             } catch (NameNotFoundException e) {
10843                 return false;
10844             } finally {
10845                 mInjector.binderRestoreCallingIdentity(ident);
10846             }
10847         }
10848     }
10849 
10850     @Override
getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)10851     public int getPermissionGrantState(ComponentName admin, String callerPackage,
10852             String packageName, String permission) throws RemoteException {
10853         PackageManager packageManager = mInjector.getPackageManager();
10854 
10855         UserHandle user = mInjector.binderGetCallingUserHandle();
10856         if (!isCallerWithSystemUid()) {
10857             // Ensure the caller is a DO/PO or a permission grant state delegate.
10858             enforceCanManageScope(admin, callerPackage,
10859                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
10860         }
10861         synchronized (getLockObject()) {
10862             long ident = mInjector.binderClearCallingIdentity();
10863             try {
10864                 int granted = mIPackageManager.checkPermission(permission,
10865                         packageName, user.getIdentifier());
10866                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
10867                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
10868                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
10869                     // Not controlled by policy
10870                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
10871                 } else {
10872                     // Policy controlled so return result based on permission grant state
10873                     return granted == PackageManager.PERMISSION_GRANTED
10874                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
10875                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
10876                 }
10877             } finally {
10878                 mInjector.binderRestoreCallingIdentity(ident);
10879             }
10880         }
10881     }
10882 
isPackageInstalledForUser(String packageName, int userHandle)10883     boolean isPackageInstalledForUser(String packageName, int userHandle) {
10884         try {
10885             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
10886                     userHandle);
10887             return (pi != null) && (pi.applicationInfo.flags != 0);
10888         } catch (RemoteException re) {
10889             throw new RuntimeException("Package manager has died", re);
10890         }
10891     }
10892 
isRuntimePermission(String permissionName)10893     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
10894         final PackageManager packageManager = mInjector.getPackageManager();
10895         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
10896         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
10897                 == PermissionInfo.PROTECTION_DANGEROUS;
10898     }
10899 
10900     @Override
isProvisioningAllowed(String action, String packageName)10901     public boolean isProvisioningAllowed(String action, String packageName) {
10902         Preconditions.checkNotNull(packageName);
10903 
10904         final int callingUid = mInjector.binderGetCallingUid();
10905         final long ident = mInjector.binderClearCallingIdentity();
10906         try {
10907             final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
10908                     packageName, UserHandle.getUserId(callingUid));
10909             Preconditions.checkArgument(callingUid == uidForPackage,
10910                     "Caller uid doesn't match the one for the provided package.");
10911         } catch (NameNotFoundException e) {
10912             throw new IllegalArgumentException("Invalid package provided " + packageName, e);
10913         } finally {
10914             mInjector.binderRestoreCallingIdentity(ident);
10915         }
10916 
10917         return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
10918     }
10919 
10920     @Override
checkProvisioningPreCondition(String action, String packageName)10921     public int checkProvisioningPreCondition(String action, String packageName) {
10922         Preconditions.checkNotNull(packageName);
10923         enforceCanManageProfileAndDeviceOwners();
10924         return checkProvisioningPreConditionSkipPermission(action, packageName);
10925     }
10926 
checkProvisioningPreConditionSkipPermission(String action, String packageName)10927     private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
10928         if (!mHasFeature) {
10929             return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
10930         }
10931 
10932         final int callingUserId = mInjector.userHandleGetCallingUserId();
10933         if (action != null) {
10934             switch (action) {
10935                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
10936                     return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
10937                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
10938                     return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10939                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
10940                     return checkManagedUserProvisioningPreCondition(callingUserId);
10941                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
10942                     return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
10943             }
10944         }
10945         throw new IllegalArgumentException("Unknown provisioning action " + action);
10946     }
10947 
10948     /**
10949      * The device owner can only be set before the setup phase of the primary user has completed,
10950      * except for adb command if no accounts or additional users are present on the device.
10951      */
checkDeviceOwnerProvisioningPreConditionLocked(@ullable ComponentName owner, int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb)10952     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
10953             int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
10954         if (mOwners.hasDeviceOwner()) {
10955             return CODE_HAS_DEVICE_OWNER;
10956         }
10957         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
10958             return CODE_USER_HAS_PROFILE_OWNER;
10959         }
10960         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
10961             return CODE_USER_NOT_RUNNING;
10962         }
10963         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10964             return CODE_HAS_PAIRED;
10965         }
10966         if (isAdb) {
10967             // if shell command runs after user setup completed check device status. Otherwise, OK.
10968             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10969                 if (!mInjector.userManagerIsSplitSystemUser()) {
10970                     if (mUserManager.getUserCount() > 1) {
10971                         return CODE_NONSYSTEM_USER_EXISTS;
10972                     }
10973                     if (hasIncompatibleAccountsOrNonAdb) {
10974                         return CODE_ACCOUNTS_NOT_EMPTY;
10975                     }
10976                 } else {
10977                     // STOPSHIP Do proper check in split user mode
10978                 }
10979             }
10980             return CODE_OK;
10981         } else {
10982             if (!mInjector.userManagerIsSplitSystemUser()) {
10983                 // In non-split user mode, DO has to be user 0
10984                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
10985                     return CODE_NOT_SYSTEM_USER;
10986                 }
10987                 // In non-split user mode, only provision DO before setup wizard completes
10988                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10989                     return CODE_USER_SETUP_COMPLETED;
10990                 }
10991             } else {
10992                 // STOPSHIP Do proper check in split user mode
10993             }
10994             return CODE_OK;
10995         }
10996     }
10997 
checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId)10998     private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
10999         synchronized (getLockObject()) {
11000             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
11001             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
11002                     deviceOwnerUserId, /* isAdb= */ false,
11003                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
11004         }
11005     }
11006 
checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId)11007     private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
11008         if (!hasFeatureManagedUsers()) {
11009             return CODE_MANAGED_USERS_NOT_SUPPORTED;
11010         }
11011         if (callingUserId == UserHandle.USER_SYSTEM
11012                 && mInjector.userManagerIsSplitSystemUser()) {
11013             // Managed-profiles cannot be setup on the system user.
11014             return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
11015         }
11016         if (getProfileOwner(callingUserId) != null) {
11017             // Managed user cannot have a managed profile.
11018             return CODE_USER_HAS_PROFILE_OWNER;
11019         }
11020 
11021         final long ident = mInjector.binderClearCallingIdentity();
11022         try {
11023             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
11024             final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
11025             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
11026                     callingUserHandle)) {
11027                 // An admin can initiate provisioning if it has set the restriction.
11028                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
11029                         UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
11030                     return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
11031                 }
11032             }
11033             boolean canRemoveProfile = true;
11034             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
11035                     callingUserHandle)) {
11036                 // We can remove a profile if the admin itself has set the restriction.
11037                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
11038                         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
11039                         callingUserId)) {
11040                     canRemoveProfile = false;
11041                 }
11042             }
11043             if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
11044                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
11045             }
11046         } finally {
11047             mInjector.binderRestoreCallingIdentity(ident);
11048         }
11049         return CODE_OK;
11050     }
11051 
getOwnerComponent(String packageName, int userId)11052     private ComponentName getOwnerComponent(String packageName, int userId) {
11053         if (isDeviceOwnerPackage(packageName, userId)) {
11054             return mOwners.getDeviceOwnerComponent();
11055         }
11056         if (isProfileOwnerPackage(packageName, userId)) {
11057             return mOwners.getProfileOwnerComponent(userId);
11058         }
11059         return null;
11060     }
11061 
11062     /**
11063      * Return device owner or profile owner set on a given user.
11064      */
getOwnerComponent(int userId)11065     private @Nullable ComponentName getOwnerComponent(int userId) {
11066         synchronized (getLockObject()) {
11067             if (mOwners.getDeviceOwnerUserId() == userId) {
11068                 return mOwners.getDeviceOwnerComponent();
11069             }
11070             if (mOwners.hasProfileOwner(userId)) {
11071                 return mOwners.getProfileOwnerComponent(userId);
11072             }
11073         }
11074         return null;
11075     }
11076 
checkManagedUserProvisioningPreCondition(int callingUserId)11077     private int checkManagedUserProvisioningPreCondition(int callingUserId) {
11078         if (!hasFeatureManagedUsers()) {
11079             return CODE_MANAGED_USERS_NOT_SUPPORTED;
11080         }
11081         if (!mInjector.userManagerIsSplitSystemUser()) {
11082             // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
11083             return CODE_NOT_SYSTEM_USER_SPLIT;
11084         }
11085         if (callingUserId == UserHandle.USER_SYSTEM) {
11086             // System user cannot be a managed user.
11087             return CODE_SYSTEM_USER;
11088         }
11089         if (hasUserSetupCompleted(callingUserId)) {
11090             return CODE_USER_SETUP_COMPLETED;
11091         }
11092         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
11093             return CODE_HAS_PAIRED;
11094         }
11095         return CODE_OK;
11096     }
11097 
checkManagedShareableDeviceProvisioningPreCondition(int callingUserId)11098     private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
11099         if (!mInjector.userManagerIsSplitSystemUser()) {
11100             // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
11101             return CODE_NOT_SYSTEM_USER_SPLIT;
11102         }
11103         return checkDeviceOwnerProvisioningPreCondition(callingUserId);
11104     }
11105 
hasFeatureManagedUsers()11106     private boolean hasFeatureManagedUsers() {
11107         try {
11108             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
11109         } catch (RemoteException e) {
11110             return false;
11111         }
11112     }
11113 
11114     @Override
getWifiMacAddress(ComponentName admin)11115     public String getWifiMacAddress(ComponentName admin) {
11116         // Make sure caller has DO.
11117         synchronized (getLockObject()) {
11118             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11119         }
11120 
11121         final long ident = mInjector.binderClearCallingIdentity();
11122         try {
11123             final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
11124             if (wifiInfo == null) {
11125                 return null;
11126             }
11127             return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
11128         } finally {
11129             mInjector.binderRestoreCallingIdentity(ident);
11130         }
11131     }
11132 
11133     /**
11134      * Returns the target sdk version number that the given packageName was built for
11135      * in the given user.
11136      */
getTargetSdk(String packageName, int userId)11137     private int getTargetSdk(String packageName, int userId) {
11138         final ApplicationInfo ai;
11139         try {
11140             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
11141             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
11142             return targetSdkVersion;
11143         } catch (RemoteException e) {
11144             // Shouldn't happen
11145             return 0;
11146         }
11147     }
11148 
11149     @Override
isManagedProfile(ComponentName admin)11150     public boolean isManagedProfile(ComponentName admin) {
11151         enforceProfileOrDeviceOwner(admin);
11152         return isManagedProfile(mInjector.userHandleGetCallingUserId());
11153     }
11154 
11155     @Override
isSystemOnlyUser(ComponentName admin)11156     public boolean isSystemOnlyUser(ComponentName admin) {
11157         synchronized (getLockObject()) {
11158             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11159         }
11160         final int callingUserId = mInjector.userHandleGetCallingUserId();
11161         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
11162     }
11163 
11164     @Override
reboot(ComponentName admin)11165     public void reboot(ComponentName admin) {
11166         Preconditions.checkNotNull(admin);
11167         // Make sure caller has DO.
11168         synchronized (getLockObject()) {
11169             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11170         }
11171         long ident = mInjector.binderClearCallingIdentity();
11172         try {
11173             // Make sure there are no ongoing calls on the device.
11174             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
11175                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
11176             }
11177             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
11178         } finally {
11179             mInjector.binderRestoreCallingIdentity(ident);
11180         }
11181     }
11182 
11183     @Override
setShortSupportMessage(@onNull ComponentName who, CharSequence message)11184     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
11185         if (!mHasFeature) {
11186             return;
11187         }
11188         Preconditions.checkNotNull(who, "ComponentName is null");
11189         final int userHandle = mInjector.userHandleGetCallingUserId();
11190         synchronized (getLockObject()) {
11191             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11192                     mInjector.binderGetCallingUid());
11193             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
11194                 admin.shortSupportMessage = message;
11195                 saveSettingsLocked(userHandle);
11196             }
11197         }
11198     }
11199 
11200     @Override
getShortSupportMessage(@onNull ComponentName who)11201     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
11202         if (!mHasFeature) {
11203             return null;
11204         }
11205         Preconditions.checkNotNull(who, "ComponentName is null");
11206         synchronized (getLockObject()) {
11207             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11208                     mInjector.binderGetCallingUid());
11209             return admin.shortSupportMessage;
11210         }
11211     }
11212 
11213     @Override
setLongSupportMessage(@onNull ComponentName who, CharSequence message)11214     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
11215         if (!mHasFeature) {
11216             return;
11217         }
11218         Preconditions.checkNotNull(who, "ComponentName is null");
11219         final int userHandle = mInjector.userHandleGetCallingUserId();
11220         synchronized (getLockObject()) {
11221             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11222                     mInjector.binderGetCallingUid());
11223             if (!TextUtils.equals(admin.longSupportMessage, message)) {
11224                 admin.longSupportMessage = message;
11225                 saveSettingsLocked(userHandle);
11226             }
11227         }
11228     }
11229 
11230     @Override
getLongSupportMessage(@onNull ComponentName who)11231     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
11232         if (!mHasFeature) {
11233             return null;
11234         }
11235         Preconditions.checkNotNull(who, "ComponentName is null");
11236         synchronized (getLockObject()) {
11237             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11238                     mInjector.binderGetCallingUid());
11239             return admin.longSupportMessage;
11240         }
11241     }
11242 
11243     @Override
getShortSupportMessageForUser(@onNull ComponentName who, int userHandle)11244     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11245         if (!mHasFeature) {
11246             return null;
11247         }
11248         Preconditions.checkNotNull(who, "ComponentName is null");
11249         if (!isCallerWithSystemUid()) {
11250             throw new SecurityException("Only the system can query support message for user");
11251         }
11252         synchronized (getLockObject()) {
11253             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11254             if (admin != null) {
11255                 return admin.shortSupportMessage;
11256             }
11257         }
11258         return null;
11259     }
11260 
11261     @Override
getLongSupportMessageForUser(@onNull ComponentName who, int userHandle)11262     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11263         if (!mHasFeature) {
11264             return null;
11265         }
11266         Preconditions.checkNotNull(who, "ComponentName is null");
11267         if (!isCallerWithSystemUid()) {
11268             throw new SecurityException("Only the system can query support message for user");
11269         }
11270         synchronized (getLockObject()) {
11271             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11272             if (admin != null) {
11273                 return admin.longSupportMessage;
11274             }
11275         }
11276         return null;
11277     }
11278 
11279     @Override
setOrganizationColor(@onNull ComponentName who, int color)11280     public void setOrganizationColor(@NonNull ComponentName who, int color) {
11281         if (!mHasFeature) {
11282             return;
11283         }
11284         Preconditions.checkNotNull(who, "ComponentName is null");
11285         final int userHandle = mInjector.userHandleGetCallingUserId();
11286         enforceManagedProfile(userHandle, "set organization color");
11287         synchronized (getLockObject()) {
11288             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11289                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11290             admin.organizationColor = color;
11291             saveSettingsLocked(userHandle);
11292         }
11293     }
11294 
11295     @Override
setOrganizationColorForUser(int color, int userId)11296     public void setOrganizationColorForUser(int color, int userId) {
11297         if (!mHasFeature) {
11298             return;
11299         }
11300         enforceFullCrossUsersPermission(userId);
11301         enforceManageUsers();
11302         enforceManagedProfile(userId, "set organization color");
11303         synchronized (getLockObject()) {
11304             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11305             admin.organizationColor = color;
11306             saveSettingsLocked(userId);
11307         }
11308     }
11309 
11310     @Override
getOrganizationColor(@onNull ComponentName who)11311     public int getOrganizationColor(@NonNull ComponentName who) {
11312         if (!mHasFeature) {
11313             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11314         }
11315         Preconditions.checkNotNull(who, "ComponentName is null");
11316         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
11317         synchronized (getLockObject()) {
11318             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11319                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11320             return admin.organizationColor;
11321         }
11322     }
11323 
11324     @Override
getOrganizationColorForUser(int userHandle)11325     public int getOrganizationColorForUser(int userHandle) {
11326         if (!mHasFeature) {
11327             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11328         }
11329         enforceFullCrossUsersPermission(userHandle);
11330         enforceManagedProfile(userHandle, "get organization color");
11331         synchronized (getLockObject()) {
11332             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11333             return (profileOwner != null)
11334                     ? profileOwner.organizationColor
11335                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
11336         }
11337     }
11338 
11339     @Override
setOrganizationName(@onNull ComponentName who, CharSequence text)11340     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
11341         if (!mHasFeature) {
11342             return;
11343         }
11344         Preconditions.checkNotNull(who, "ComponentName is null");
11345         final int userHandle = mInjector.userHandleGetCallingUserId();
11346 
11347         synchronized (getLockObject()) {
11348             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11349                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11350             if (!TextUtils.equals(admin.organizationName, text)) {
11351                 admin.organizationName = (text == null || text.length() == 0)
11352                         ? null : text.toString();
11353                 saveSettingsLocked(userHandle);
11354             }
11355         }
11356     }
11357 
11358     @Override
getOrganizationName(@onNull ComponentName who)11359     public CharSequence getOrganizationName(@NonNull ComponentName who) {
11360         if (!mHasFeature) {
11361             return null;
11362         }
11363         Preconditions.checkNotNull(who, "ComponentName is null");
11364         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
11365         synchronized (getLockObject()) {
11366             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11367                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11368             return admin.organizationName;
11369         }
11370     }
11371 
11372     @Override
getDeviceOwnerOrganizationName()11373     public CharSequence getDeviceOwnerOrganizationName() {
11374         if (!mHasFeature) {
11375             return null;
11376         }
11377         enforceDeviceOwnerOrManageUsers();
11378         synchronized (getLockObject()) {
11379             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
11380             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
11381         }
11382     }
11383 
11384     @Override
getOrganizationNameForUser(int userHandle)11385     public CharSequence getOrganizationNameForUser(int userHandle) {
11386         if (!mHasFeature) {
11387             return null;
11388         }
11389         enforceFullCrossUsersPermission(userHandle);
11390         enforceManagedProfile(userHandle, "get organization name");
11391         synchronized (getLockObject()) {
11392             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11393             return (profileOwner != null)
11394                     ? profileOwner.organizationName
11395                     : null;
11396         }
11397     }
11398 
11399     @Override
setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames)11400     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
11401         Preconditions.checkNotNull(who);
11402         Preconditions.checkNotNull(packageNames);
11403 
11404         if (!mHasFeature) {
11405             return packageNames;
11406         }
11407         synchronized (getLockObject()) {
11408             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11409                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11410             final int callingUserId = mInjector.userHandleGetCallingUserId();
11411             final long identity = mInjector.binderClearCallingIdentity();
11412             try {
11413                 final List<String> excludedPkgs
11414                         = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames);
11415                 admin.meteredDisabledPackages = packageNames;
11416                 pushMeteredDisabledPackagesLocked(callingUserId);
11417                 saveSettingsLocked(callingUserId);
11418                 return excludedPkgs;
11419             } finally {
11420                 mInjector.binderRestoreCallingIdentity(identity);
11421             }
11422         }
11423     }
11424 
removeInvalidPkgsForMeteredDataRestriction( int userId, List<String> pkgNames)11425     private List<String> removeInvalidPkgsForMeteredDataRestriction(
11426             int userId, List<String> pkgNames) {
11427         final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
11428         final List<String> excludedPkgs = new ArrayList<>();
11429         for (int i = pkgNames.size() - 1; i >= 0; --i) {
11430             final String pkgName = pkgNames.get(i);
11431             // If the package is an active admin, don't restrict it.
11432             if (activeAdmins.contains(pkgName)) {
11433                 excludedPkgs.add(pkgName);
11434                 continue;
11435             }
11436             // If the package doesn't exist, don't restrict it.
11437             try {
11438                 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
11439                     excludedPkgs.add(pkgName);
11440                 }
11441             } catch (RemoteException e) {
11442                 // Should not happen
11443             }
11444         }
11445         pkgNames.removeAll(excludedPkgs);
11446         return excludedPkgs;
11447     }
11448 
11449     @Override
getMeteredDataDisabledPackages(ComponentName who)11450     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
11451         Preconditions.checkNotNull(who);
11452 
11453         if (!mHasFeature) {
11454             return new ArrayList<>();
11455         }
11456         synchronized (getLockObject()) {
11457             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11458                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11459             return admin.meteredDisabledPackages == null
11460                     ? new ArrayList<>() : admin.meteredDisabledPackages;
11461         }
11462     }
11463 
11464     @Override
isMeteredDataDisabledPackageForUser(ComponentName who, String packageName, int userId)11465     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
11466             String packageName, int userId) {
11467         Preconditions.checkNotNull(who);
11468 
11469         if (!mHasFeature) {
11470             return false;
11471         }
11472         if (!isCallerWithSystemUid()) {
11473             throw new SecurityException(
11474                     "Only the system can query restricted pkgs for a specific user");
11475         }
11476         synchronized (getLockObject()) {
11477             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
11478             if (admin != null && admin.meteredDisabledPackages != null) {
11479                 return admin.meteredDisabledPackages.contains(packageName);
11480             }
11481         }
11482         return false;
11483     }
11484 
pushMeteredDisabledPackagesLocked(int userId)11485     private void pushMeteredDisabledPackagesLocked(int userId) {
11486         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
11487                 getMeteredDisabledPackagesLocked(userId), userId);
11488     }
11489 
getMeteredDisabledPackagesLocked(int userId)11490     private Set<String> getMeteredDisabledPackagesLocked(int userId) {
11491         final ComponentName who = getOwnerComponent(userId);
11492         final Set<String> restrictedPkgs = new ArraySet<>();
11493         if (who != null) {
11494             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
11495             if (admin != null && admin.meteredDisabledPackages != null) {
11496                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
11497             }
11498         }
11499         return restrictedPkgs;
11500     }
11501 
11502     @Override
setAffiliationIds(ComponentName admin, List<String> ids)11503     public void setAffiliationIds(ComponentName admin, List<String> ids) {
11504         if (!mHasFeature) {
11505             return;
11506         }
11507         if (ids == null) {
11508             throw new IllegalArgumentException("ids must not be null");
11509         }
11510         for (String id : ids) {
11511             if (TextUtils.isEmpty(id)) {
11512                 throw new IllegalArgumentException("ids must not contain empty string");
11513             }
11514         }
11515 
11516         final Set<String> affiliationIds = new ArraySet<>(ids);
11517         final int callingUserId = mInjector.userHandleGetCallingUserId();
11518         synchronized (getLockObject()) {
11519             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11520             getUserData(callingUserId).mAffiliationIds = affiliationIds;
11521             saveSettingsLocked(callingUserId);
11522             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
11523                 // Affiliation ids specified by the device owner are additionally stored in
11524                 // UserHandle.USER_SYSTEM's DevicePolicyData.
11525                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
11526                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11527             }
11528 
11529             // Affiliation status for any user, not just the calling user, might have changed.
11530             // The device owner user will still be affiliated after changing its affiliation ids,
11531             // but as a result of that other users might become affiliated or un-affiliated.
11532             maybePauseDeviceWideLoggingLocked();
11533             maybeResumeDeviceWideLoggingLocked();
11534             maybeClearLockTaskPolicyLocked();
11535         }
11536     }
11537 
11538     @Override
getAffiliationIds(ComponentName admin)11539     public List<String> getAffiliationIds(ComponentName admin) {
11540         if (!mHasFeature) {
11541             return Collections.emptyList();
11542         }
11543 
11544         Preconditions.checkNotNull(admin);
11545         synchronized (getLockObject()) {
11546             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11547             return new ArrayList<String>(
11548                     getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
11549         }
11550     }
11551 
11552     @Override
isAffiliatedUser()11553     public boolean isAffiliatedUser() {
11554         if (!mHasFeature) {
11555             return false;
11556         }
11557 
11558         synchronized (getLockObject()) {
11559             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
11560         }
11561     }
11562 
isUserAffiliatedWithDeviceLocked(int userId)11563     private boolean isUserAffiliatedWithDeviceLocked(int userId) {
11564         if (!mOwners.hasDeviceOwner()) {
11565             return false;
11566         }
11567         if (userId == mOwners.getDeviceOwnerUserId()) {
11568             // The user that the DO is installed on is always affiliated with the device.
11569             return true;
11570         }
11571         if (userId == UserHandle.USER_SYSTEM) {
11572             // The system user is always affiliated in a DO device, even if the DO is set on a
11573             // different user. This could be the case if the DO is set in the primary user
11574             // of a split user device.
11575             return true;
11576         }
11577 
11578         final ComponentName profileOwner = getProfileOwner(userId);
11579         if (profileOwner == null) {
11580             return false;
11581         }
11582 
11583         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
11584         final Set<String> deviceAffiliationIds =
11585                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
11586         for (String id : userAffiliationIds) {
11587             if (deviceAffiliationIds.contains(id)) {
11588                 return true;
11589             }
11590         }
11591         return false;
11592     }
11593 
areAllUsersAffiliatedWithDeviceLocked()11594     private boolean areAllUsersAffiliatedWithDeviceLocked() {
11595         final long ident = mInjector.binderClearCallingIdentity();
11596         try {
11597             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
11598             for (int i = 0; i < userInfos.size(); i++) {
11599                 int userId = userInfos.get(i).id;
11600                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
11601                     Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
11602                     return false;
11603                 }
11604             }
11605         } finally {
11606             mInjector.binderRestoreCallingIdentity(ident);
11607         }
11608 
11609         return true;
11610     }
11611 
11612     @Override
setSecurityLoggingEnabled(ComponentName admin, boolean enabled)11613     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
11614         if (!mHasFeature) {
11615             return;
11616         }
11617         Preconditions.checkNotNull(admin);
11618 
11619         synchronized (getLockObject()) {
11620             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11621             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
11622                 return;
11623             }
11624             mInjector.securityLogSetLoggingEnabledProperty(enabled);
11625             if (enabled) {
11626                 mSecurityLogMonitor.start();
11627                 maybePauseDeviceWideLoggingLocked();
11628             } else {
11629                 mSecurityLogMonitor.stop();
11630             }
11631         }
11632     }
11633 
11634     @Override
isSecurityLoggingEnabled(ComponentName admin)11635     public boolean isSecurityLoggingEnabled(ComponentName admin) {
11636         if (!mHasFeature) {
11637             return false;
11638         }
11639 
11640         synchronized (getLockObject()) {
11641             if (!isCallerWithSystemUid()) {
11642                 Preconditions.checkNotNull(admin);
11643                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11644             }
11645             return mInjector.securityLogGetLoggingEnabledProperty();
11646         }
11647     }
11648 
recordSecurityLogRetrievalTime()11649     private void recordSecurityLogRetrievalTime() {
11650         synchronized (getLockObject()) {
11651             final long currentTime = System.currentTimeMillis();
11652             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
11653             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
11654                 policyData.mLastSecurityLogRetrievalTime = currentTime;
11655                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11656             }
11657         }
11658     }
11659 
11660     @Override
retrievePreRebootSecurityLogs(ComponentName admin)11661     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
11662         if (!mHasFeature) {
11663             return null;
11664         }
11665 
11666         Preconditions.checkNotNull(admin);
11667         ensureDeviceOwnerAndAllUsersAffiliated(admin);
11668 
11669         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
11670                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
11671             return null;
11672         }
11673 
11674         recordSecurityLogRetrievalTime();
11675 
11676         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
11677         try {
11678             SecurityLog.readPreviousEvents(output);
11679             return new ParceledListSlice<SecurityEvent>(output);
11680         } catch (IOException e) {
11681             Slog.w(LOG_TAG, "Fail to read previous events" , e);
11682             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
11683         }
11684     }
11685 
11686     @Override
retrieveSecurityLogs(ComponentName admin)11687     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
11688         if (!mHasFeature) {
11689             return null;
11690         }
11691 
11692         Preconditions.checkNotNull(admin);
11693         ensureDeviceOwnerAndAllUsersAffiliated(admin);
11694 
11695         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
11696             return null;
11697         }
11698 
11699         recordSecurityLogRetrievalTime();
11700 
11701         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
11702         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
11703     }
11704 
11705     @Override
forceSecurityLogs()11706     public long forceSecurityLogs() {
11707         enforceShell("forceSecurityLogs");
11708         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
11709             throw new IllegalStateException("logging is not available");
11710         }
11711         return mSecurityLogMonitor.forceLogs();
11712     }
11713 
enforceCanManageDeviceAdmin()11714     private void enforceCanManageDeviceAdmin() {
11715         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
11716                 null);
11717     }
11718 
enforceCanManageProfileAndDeviceOwners()11719     private void enforceCanManageProfileAndDeviceOwners() {
11720         mContext.enforceCallingOrSelfPermission(
11721                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
11722     }
11723 
enforceCallerSystemUserHandle()11724     private void enforceCallerSystemUserHandle() {
11725         final int callingUid = mInjector.binderGetCallingUid();
11726         final int userId = UserHandle.getUserId(callingUid);
11727         if (userId != UserHandle.USER_SYSTEM) {
11728             throw new SecurityException("Caller has to be in user 0");
11729         }
11730     }
11731 
11732     @Override
isUninstallInQueue(final String packageName)11733     public boolean isUninstallInQueue(final String packageName) {
11734         enforceCanManageDeviceAdmin();
11735         final int userId = mInjector.userHandleGetCallingUserId();
11736         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11737         synchronized (getLockObject()) {
11738             return mPackagesToRemove.contains(packageUserPair);
11739         }
11740     }
11741 
11742     @Override
uninstallPackageWithActiveAdmins(final String packageName)11743     public void uninstallPackageWithActiveAdmins(final String packageName) {
11744         enforceCanManageDeviceAdmin();
11745         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
11746 
11747         final int userId = mInjector.userHandleGetCallingUserId();
11748 
11749         enforceUserUnlocked(userId);
11750 
11751         final ComponentName profileOwner = getProfileOwner(userId);
11752         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
11753             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
11754         }
11755 
11756         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
11757         if (getDeviceOwnerUserId() == userId && deviceOwner != null
11758                 && packageName.equals(deviceOwner.getPackageName())) {
11759             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
11760         }
11761 
11762         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11763         synchronized (getLockObject()) {
11764             mPackagesToRemove.add(packageUserPair);
11765         }
11766 
11767         // All active admins on the user.
11768         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
11769 
11770         // Active admins in the target package.
11771         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
11772         if (allActiveAdmins != null) {
11773             for (ComponentName activeAdmin : allActiveAdmins) {
11774                 if (packageName.equals(activeAdmin.getPackageName())) {
11775                     packageActiveAdmins.add(activeAdmin);
11776                     removeActiveAdmin(activeAdmin, userId);
11777                 }
11778             }
11779         }
11780         if (packageActiveAdmins.size() == 0) {
11781             startUninstallIntent(packageName, userId);
11782         } else {
11783             mHandler.postDelayed(new Runnable() {
11784                 @Override
11785                 public void run() {
11786                     for (ComponentName activeAdmin : packageActiveAdmins) {
11787                         removeAdminArtifacts(activeAdmin, userId);
11788                     }
11789                     startUninstallIntent(packageName, userId);
11790                 }
11791             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
11792         }
11793     }
11794 
11795     @Override
isDeviceProvisioned()11796     public boolean isDeviceProvisioned() {
11797         enforceManageUsers();
11798         synchronized (getLockObject()) {
11799             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
11800         }
11801     }
11802 
isCurrentUserDemo()11803     private boolean isCurrentUserDemo() {
11804         if (UserManager.isDeviceInDemoMode(mContext)) {
11805             final int userId = mInjector.userHandleGetCallingUserId();
11806             final long callingIdentity = mInjector.binderClearCallingIdentity();
11807             try {
11808                 return mUserManager.getUserInfo(userId).isDemo();
11809             } finally {
11810                 mInjector.binderRestoreCallingIdentity(callingIdentity);
11811             }
11812         }
11813         return false;
11814     }
11815 
removePackageIfRequired(final String packageName, final int userId)11816     private void removePackageIfRequired(final String packageName, final int userId) {
11817         if (!packageHasActiveAdmins(packageName, userId)) {
11818             // Will not do anything if uninstall was not requested or was already started.
11819             startUninstallIntent(packageName, userId);
11820         }
11821     }
11822 
startUninstallIntent(final String packageName, final int userId)11823     private void startUninstallIntent(final String packageName, final int userId) {
11824         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11825         synchronized (getLockObject()) {
11826             if (!mPackagesToRemove.contains(packageUserPair)) {
11827                 // Do nothing if uninstall was not requested or was already started.
11828                 return;
11829             }
11830             mPackagesToRemove.remove(packageUserPair);
11831         }
11832         try {
11833             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
11834                 // Package does not exist. Nothing to do.
11835                 return;
11836             }
11837         } catch (RemoteException re) {
11838             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
11839         }
11840 
11841         try { // force stop the package before uninstalling
11842             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
11843         } catch (RemoteException re) {
11844             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
11845         }
11846         final Uri packageURI = Uri.parse("package:" + packageName);
11847         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
11848         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11849         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
11850     }
11851 
11852     /**
11853      * Removes the admin from the policy. Ideally called after the admin's
11854      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
11855      *
11856      * @param adminReceiver The admin to remove
11857      * @param userHandle The user for which this admin has to be removed.
11858      */
removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle)11859     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
11860         synchronized (getLockObject()) {
11861             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
11862             if (admin == null) {
11863                 return;
11864             }
11865             final DevicePolicyData policy = getUserData(userHandle);
11866             final boolean doProxyCleanup = admin.info.usesPolicy(
11867                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
11868             policy.mAdminList.remove(admin);
11869             policy.mAdminMap.remove(adminReceiver);
11870             validatePasswordOwnerLocked(policy);
11871             if (doProxyCleanup) {
11872                 resetGlobalProxyLocked(policy);
11873             }
11874             pushActiveAdminPackagesLocked(userHandle);
11875             pushMeteredDisabledPackagesLocked(userHandle);
11876             saveSettingsLocked(userHandle);
11877             updateMaximumTimeToLockLocked(userHandle);
11878             policy.mRemovingAdmins.remove(adminReceiver);
11879 
11880             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
11881         }
11882         // The removed admin might have disabled camera, so update user
11883         // restrictions.
11884         pushUserRestrictions(userHandle);
11885     }
11886 
11887     @Override
setDeviceProvisioningConfigApplied()11888     public void setDeviceProvisioningConfigApplied() {
11889         enforceManageUsers();
11890         synchronized (getLockObject()) {
11891             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11892             policy.mDeviceProvisioningConfigApplied = true;
11893             saveSettingsLocked(UserHandle.USER_SYSTEM);
11894         }
11895     }
11896 
11897     @Override
isDeviceProvisioningConfigApplied()11898     public boolean isDeviceProvisioningConfigApplied() {
11899         enforceManageUsers();
11900         synchronized (getLockObject()) {
11901             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11902             return policy.mDeviceProvisioningConfigApplied;
11903         }
11904     }
11905 
11906     /**
11907      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
11908      *
11909      * It's added for testing only. Please use this API carefully if it's used by other system app
11910      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
11911      * apps.
11912      */
11913     @Override
forceUpdateUserSetupComplete()11914     public void forceUpdateUserSetupComplete() {
11915         enforceCanManageProfileAndDeviceOwners();
11916         enforceCallerSystemUserHandle();
11917         // no effect if it's called from user build
11918         if (!mInjector.isBuildDebuggable()) {
11919             return;
11920         }
11921         final int userId = UserHandle.USER_SYSTEM;
11922         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
11923                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
11924         DevicePolicyData policy = getUserData(userId);
11925         policy.mUserSetupComplete = isUserCompleted;
11926         synchronized (getLockObject()) {
11927             saveSettingsLocked(userId);
11928         }
11929     }
11930 
11931     // TODO(b/22388012): When backup is available for secondary users and profiles, consider
11932     // whether there are any privacy/security implications of enabling the backup service here
11933     // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
11934     // affiliated).
11935     @Override
setBackupServiceEnabled(ComponentName admin, boolean enabled)11936     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
11937         if (!mHasFeature) {
11938             return;
11939         }
11940         Preconditions.checkNotNull(admin);
11941         synchronized (getLockObject()) {
11942             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(
11943                     admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11944             if (!enabled) {
11945                 activeAdmin.mandatoryBackupTransport = null;
11946                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11947             }
11948         }
11949 
11950         final long ident = mInjector.binderClearCallingIdentity();
11951         try {
11952             IBackupManager ibm = mInjector.getIBackupManager();
11953             if (ibm != null) {
11954                 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
11955             }
11956         } catch (RemoteException e) {
11957             throw new IllegalStateException(
11958                 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
11959         } finally {
11960             mInjector.binderRestoreCallingIdentity(ident);
11961         }
11962     }
11963 
11964     @Override
isBackupServiceEnabled(ComponentName admin)11965     public boolean isBackupServiceEnabled(ComponentName admin) {
11966         Preconditions.checkNotNull(admin);
11967         if (!mHasFeature) {
11968             return true;
11969         }
11970         synchronized (getLockObject()) {
11971             try {
11972                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11973                 IBackupManager ibm = mInjector.getIBackupManager();
11974                 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
11975             } catch (RemoteException e) {
11976                 throw new IllegalStateException("Failed requesting backup service state.", e);
11977             }
11978         }
11979     }
11980 
11981     @Override
setMandatoryBackupTransport( ComponentName admin, ComponentName backupTransportComponent)11982     public boolean setMandatoryBackupTransport(
11983             ComponentName admin,
11984             ComponentName backupTransportComponent) {
11985         if (!mHasFeature) {
11986             return false;
11987         }
11988         Preconditions.checkNotNull(admin);
11989         synchronized (getLockObject()) {
11990             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11991         }
11992 
11993         final int callingUid = mInjector.binderGetCallingUid();
11994         final AtomicBoolean success = new AtomicBoolean(false);
11995         final CountDownLatch countDownLatch = new CountDownLatch(1);
11996         final ISelectBackupTransportCallback selectBackupTransportCallbackInternal =
11997                 new ISelectBackupTransportCallback.Stub() {
11998                     public void onSuccess(String transportName) {
11999                         saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent);
12000                         success.set(true);
12001                         countDownLatch.countDown();
12002                     }
12003 
12004                     public void onFailure(int reason) {
12005                         countDownLatch.countDown();
12006                     }
12007                 };
12008         final long identity = mInjector.binderClearCallingIdentity();
12009         try {
12010             IBackupManager ibm = mInjector.getIBackupManager();
12011             if (ibm != null && backupTransportComponent != null) {
12012                 if (!ibm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12013                     ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, true);
12014                 }
12015                 ibm.selectBackupTransportAsync(
12016                         backupTransportComponent, selectBackupTransportCallbackInternal);
12017                 countDownLatch.await();
12018                 if (success.get()) {
12019                     ibm.setBackupEnabled(true);
12020                 }
12021             } else if (backupTransportComponent == null) {
12022                 saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent);
12023                 success.set(true);
12024             }
12025         } catch (RemoteException e) {
12026             throw new IllegalStateException("Failed to set mandatory backup transport.", e);
12027         } catch (InterruptedException e) {
12028             throw new IllegalStateException("Failed to set mandatory backup transport.", e);
12029         } finally {
12030             mInjector.binderRestoreCallingIdentity(identity);
12031         }
12032         return success.get();
12033     }
12034 
saveMandatoryBackupTransport( ComponentName admin, int callingUid, ComponentName backupTransportComponent)12035     private void saveMandatoryBackupTransport(
12036             ComponentName admin, int callingUid, ComponentName backupTransportComponent) {
12037         synchronized (getLockObject()) {
12038             ActiveAdmin activeAdmin =
12039                     getActiveAdminWithPolicyForUidLocked(
12040                             admin,
12041                             DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
12042                             callingUid);
12043             if (!Objects.equals(backupTransportComponent,
12044                     activeAdmin.mandatoryBackupTransport)) {
12045                 activeAdmin.mandatoryBackupTransport =
12046                         backupTransportComponent;
12047                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12048             }
12049         }
12050     }
12051 
12052     @Override
getMandatoryBackupTransport()12053     public ComponentName getMandatoryBackupTransport() {
12054         if (!mHasFeature) {
12055             return null;
12056         }
12057         synchronized (getLockObject()) {
12058             ActiveAdmin activeAdmin = getDeviceOwnerAdminLocked();
12059             return activeAdmin == null ? null : activeAdmin.mandatoryBackupTransport;
12060         }
12061     }
12062 
12063 
12064     @Override
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, @NonNull IApplicationThread caller, @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId)12065     public boolean bindDeviceAdminServiceAsUser(
12066             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
12067             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
12068             @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
12069         if (!mHasFeature) {
12070             return false;
12071         }
12072         Preconditions.checkNotNull(admin);
12073         Preconditions.checkNotNull(caller);
12074         Preconditions.checkNotNull(serviceIntent);
12075         Preconditions.checkArgument(
12076                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
12077                 "Service intent must be explicit (with a package name or component): "
12078                         + serviceIntent);
12079         Preconditions.checkNotNull(connection);
12080         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
12081                 "target user id must be different from the calling user id");
12082 
12083         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
12084             throw new SecurityException("Not allowed to bind to target user id");
12085         }
12086 
12087         final String targetPackage;
12088         synchronized (getLockObject()) {
12089             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
12090         }
12091 
12092         final long callingIdentity = mInjector.binderClearCallingIdentity();
12093         try {
12094             // Validate and sanitize the incoming service intent.
12095             final Intent sanitizedIntent =
12096                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
12097             if (sanitizedIntent == null) {
12098                 // Fail, cannot lookup the target service.
12099                 return false;
12100             }
12101             // Ask ActivityManager to bind it. Notice that we are binding the service with the
12102             // caller app instead of DevicePolicyManagerService.
12103             return mInjector.getIActivityManager().bindService(
12104                     caller, activtiyToken, serviceIntent,
12105                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
12106                     connection, flags, mContext.getOpPackageName(),
12107                     targetUserId) != 0;
12108         } catch (RemoteException ex) {
12109             // Same process, should not happen.
12110         } finally {
12111             mInjector.binderRestoreCallingIdentity(callingIdentity);
12112         }
12113 
12114         // Failed to bind.
12115         return false;
12116     }
12117 
12118     @Override
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)12119     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
12120         if (!mHasFeature) {
12121             return Collections.emptyList();
12122         }
12123         Preconditions.checkNotNull(admin);
12124 
12125         synchronized (getLockObject()) {
12126             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12127 
12128             final int callingUserId = mInjector.userHandleGetCallingUserId();
12129             final long callingIdentity = mInjector.binderClearCallingIdentity();
12130             try {
12131                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
12132                 if (!isDeviceOwner(admin, callingUserId)) {
12133                     // Profile owners can only bind to the device owner.
12134                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
12135                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
12136                     }
12137                 } else {
12138                     // Caller is the device owner: Look for profile owners that it can bind to.
12139                     final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
12140                     for (int i = 0; i < userInfos.size(); i++) {
12141                         final int userId = userInfos.get(i).id;
12142                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
12143                             targetUsers.add(UserHandle.of(userId));
12144                         }
12145                     }
12146                 }
12147 
12148                 return targetUsers;
12149             } finally {
12150                 mInjector.binderRestoreCallingIdentity(callingIdentity);
12151             }
12152         }
12153     }
12154 
canUserBindToDeviceOwnerLocked(int userId)12155     private boolean canUserBindToDeviceOwnerLocked(int userId) {
12156         // There has to be a device owner, under another user id.
12157         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
12158             return false;
12159         }
12160 
12161         // The user must have a profile owner that belongs to the same package as the device owner.
12162         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
12163                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
12164             return false;
12165         }
12166 
12167         // The user must be affiliated.
12168         return isUserAffiliatedWithDeviceLocked(userId);
12169     }
12170 
12171     /**
12172      * Return true if a given user has any accounts that'll prevent installing a device or profile
12173      * owner {@code owner}.
12174      * - If the user has no accounts, then return false.
12175      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
12176      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
12177      *   ..._DISALLOWED, return true.
12178      * - Otherwise return false.
12179      *
12180      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
12181      * when the caller is not ADB.
12182      *
12183      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
12184      */
hasIncompatibleAccountsOrNonAdbNoLock( int userId, @Nullable ComponentName owner)12185     private boolean hasIncompatibleAccountsOrNonAdbNoLock(
12186             int userId, @Nullable ComponentName owner) {
12187         if (!isAdb()) {
12188             return true;
12189         }
12190         wtfIfInLock();
12191 
12192         final long token = mInjector.binderClearCallingIdentity();
12193         try {
12194             final AccountManager am = AccountManager.get(mContext);
12195             final Account accounts[] = am.getAccountsAsUser(userId);
12196             if (accounts.length == 0) {
12197                 return false;
12198             }
12199             synchronized (getLockObject()) {
12200                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
12201                     Log.w(LOG_TAG,
12202                             "Non test-only owner can't be installed with existing accounts.");
12203                     return true;
12204                 }
12205             }
12206 
12207             final String[] feature_allow =
12208                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
12209             final String[] feature_disallow =
12210                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
12211 
12212             boolean compatible = true;
12213             for (Account account : accounts) {
12214                 if (hasAccountFeatures(am, account, feature_disallow)) {
12215                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
12216                     compatible = false;
12217                     break;
12218                 }
12219                 if (!hasAccountFeatures(am, account, feature_allow)) {
12220                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
12221                     compatible = false;
12222                     break;
12223                 }
12224             }
12225             if (compatible) {
12226                 Log.w(LOG_TAG, "All accounts are compatible");
12227             } else {
12228                 Log.e(LOG_TAG, "Found incompatible accounts");
12229             }
12230             return !compatible;
12231         } finally {
12232             mInjector.binderRestoreCallingIdentity(token);
12233         }
12234     }
12235 
hasAccountFeatures(AccountManager am, Account account, String[] features)12236     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
12237         try {
12238             return am.hasFeatures(account, features, null, null).getResult();
12239         } catch (Exception e) {
12240             Log.w(LOG_TAG, "Failed to get account feature", e);
12241             return false;
12242         }
12243     }
12244 
isAdb()12245     private boolean isAdb() {
12246         final int callingUid = mInjector.binderGetCallingUid();
12247         return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
12248     }
12249 
12250     @Override
setNetworkLoggingEnabled(ComponentName admin, boolean enabled)12251     public void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
12252         if (!mHasFeature) {
12253             return;
12254         }
12255         synchronized (getLockObject()) {
12256             Preconditions.checkNotNull(admin);
12257             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12258 
12259             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
12260                 // already in the requested state
12261                 return;
12262             }
12263             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12264             deviceOwner.isNetworkLoggingEnabled = enabled;
12265             if (!enabled) {
12266                 deviceOwner.numNetworkLoggingNotifications = 0;
12267                 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
12268             }
12269             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12270 
12271             setNetworkLoggingActiveInternal(enabled);
12272         }
12273     }
12274 
setNetworkLoggingActiveInternal(boolean active)12275     private void setNetworkLoggingActiveInternal(boolean active) {
12276         synchronized (getLockObject()) {
12277             final long callingIdentity = mInjector.binderClearCallingIdentity();
12278             try {
12279                 if (active) {
12280                     mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
12281                     if (!mNetworkLogger.startNetworkLogging()) {
12282                         mNetworkLogger = null;
12283                         Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
12284                                 + " service not being available yet.");
12285                     }
12286                     maybePauseDeviceWideLoggingLocked();
12287                     sendNetworkLoggingNotificationLocked();
12288                 } else {
12289                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
12290                         Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
12291                                 + " service not being available yet.");
12292                     }
12293                     mNetworkLogger = null;
12294                     mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
12295                 }
12296             } finally {
12297                 mInjector.binderRestoreCallingIdentity(callingIdentity);
12298             }
12299         }
12300     }
12301 
12302     /** Pauses security and network logging if there are unaffiliated users on the device */
maybePauseDeviceWideLoggingLocked()12303     private void maybePauseDeviceWideLoggingLocked() {
12304         if (!areAllUsersAffiliatedWithDeviceLocked()) {
12305             Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
12306                     + "paused if enabled.");
12307             mSecurityLogMonitor.pause();
12308             if (mNetworkLogger != null) {
12309                 mNetworkLogger.pause();
12310             }
12311         }
12312     }
12313 
12314     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
maybeResumeDeviceWideLoggingLocked()12315     private void maybeResumeDeviceWideLoggingLocked() {
12316         if (areAllUsersAffiliatedWithDeviceLocked()) {
12317             final long ident = mInjector.binderClearCallingIdentity();
12318             try {
12319                 mSecurityLogMonitor.resume();
12320                 if (mNetworkLogger != null) {
12321                     mNetworkLogger.resume();
12322                 }
12323             } finally {
12324                 mInjector.binderRestoreCallingIdentity(ident);
12325             }
12326         }
12327     }
12328 
12329     /** Deletes any security and network logs that might have been collected so far */
discardDeviceWideLogsLocked()12330     private void discardDeviceWideLogsLocked() {
12331         mSecurityLogMonitor.discardLogs();
12332         if (mNetworkLogger != null) {
12333             mNetworkLogger.discardLogs();
12334         }
12335         // TODO: We should discard pre-boot security logs here too, as otherwise those
12336         // logs (which might contain data from the user just removed) will be
12337         // available after next boot.
12338     }
12339 
12340     @Override
isNetworkLoggingEnabled(ComponentName admin)12341     public boolean isNetworkLoggingEnabled(ComponentName admin) {
12342         if (!mHasFeature) {
12343             return false;
12344         }
12345         synchronized (getLockObject()) {
12346             enforceDeviceOwnerOrManageUsers();
12347             return isNetworkLoggingEnabledInternalLocked();
12348         }
12349     }
12350 
isNetworkLoggingEnabledInternalLocked()12351     private boolean isNetworkLoggingEnabledInternalLocked() {
12352         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12353         return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
12354     }
12355 
12356     /*
12357      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
12358      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
12359      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
12360      *
12361      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
12362      */
12363     @Override
retrieveNetworkLogs(ComponentName admin, long batchToken)12364     public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
12365         if (!mHasFeature) {
12366             return null;
12367         }
12368         Preconditions.checkNotNull(admin);
12369         ensureDeviceOwnerAndAllUsersAffiliated(admin);
12370 
12371         synchronized (getLockObject()) {
12372             if (mNetworkLogger == null
12373                     || !isNetworkLoggingEnabledInternalLocked()) {
12374                 return null;
12375             }
12376 
12377             final long currentTime = System.currentTimeMillis();
12378             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
12379             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
12380                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
12381                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12382             }
12383             return mNetworkLogger.retrieveLogs(batchToken);
12384         }
12385     }
12386 
sendNetworkLoggingNotificationLocked()12387     private void sendNetworkLoggingNotificationLocked() {
12388         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12389         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
12390             return;
12391         }
12392         if (deviceOwner.numNetworkLoggingNotifications >=
12393                 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12394             return;
12395         }
12396         final long now = System.currentTimeMillis();
12397         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
12398             return;
12399         }
12400         deviceOwner.numNetworkLoggingNotifications++;
12401         if (deviceOwner.numNetworkLoggingNotifications
12402                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12403             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
12404         } else {
12405             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
12406         }
12407         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
12408         intent.setPackage("com.android.systemui");
12409         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
12410                 UserHandle.CURRENT);
12411         Notification notification =
12412                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
12413                 .setSmallIcon(R.drawable.ic_info_outline)
12414                 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
12415                 .setContentText(mContext.getString(R.string.network_logging_notification_text))
12416                 .setTicker(mContext.getString(R.string.network_logging_notification_title))
12417                 .setShowWhen(true)
12418                 .setContentIntent(pendingIntent)
12419                 .setStyle(new Notification.BigTextStyle()
12420                         .bigText(mContext.getString(R.string.network_logging_notification_text)))
12421                 .build();
12422         mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
12423         saveSettingsLocked(mOwners.getDeviceOwnerUserId());
12424     }
12425 
12426     /**
12427      * Return the package name of owner in a given user.
12428      */
getOwnerPackageNameForUserLocked(int userId)12429     private String getOwnerPackageNameForUserLocked(int userId) {
12430         return mOwners.getDeviceOwnerUserId() == userId
12431                 ? mOwners.getDeviceOwnerPackageName()
12432                 : mOwners.getProfileOwnerPackage(userId);
12433     }
12434 
12435     /**
12436      * @param rawIntent Original service intent specified by caller. It must be explicit.
12437      * @param expectedPackageName The expected package name of the resolved service.
12438      * @return Intent that have component explicitly set. {@code null} if no service is resolved
12439      *     with the given intent.
12440      * @throws SecurityException if the intent is resolved to an invalid service.
12441      */
createCrossUserServiceIntent( @onNull Intent rawIntent, @NonNull String expectedPackageName, @UserIdInt int targetUserId)12442     private Intent createCrossUserServiceIntent(
12443             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
12444             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
12445         ResolveInfo info = mIPackageManager.resolveService(
12446                 rawIntent,
12447                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
12448                 0,  // flags
12449                 targetUserId);
12450         if (info == null || info.serviceInfo == null) {
12451             Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
12452                     + " or user " + targetUserId + " is not running");
12453             return null;
12454         }
12455         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
12456             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
12457         }
12458         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
12459         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
12460             throw new SecurityException(
12461                     "Service must be protected by BIND_DEVICE_ADMIN permission");
12462         }
12463         // It is the system server to bind the service, it would be extremely dangerous if it
12464         // can be exploited to bind any service. Set the component explicitly to make sure we
12465         // do not bind anything accidentally.
12466         rawIntent.setComponent(info.serviceInfo.getComponentName());
12467         return rawIntent;
12468     }
12469 
12470     @Override
getLastSecurityLogRetrievalTime()12471     public long getLastSecurityLogRetrievalTime() {
12472         enforceDeviceOwnerOrManageUsers();
12473         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
12474      }
12475 
12476     @Override
getLastBugReportRequestTime()12477     public long getLastBugReportRequestTime() {
12478         enforceDeviceOwnerOrManageUsers();
12479         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
12480      }
12481 
12482     @Override
getLastNetworkLogRetrievalTime()12483     public long getLastNetworkLogRetrievalTime() {
12484         enforceDeviceOwnerOrManageUsers();
12485         return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
12486     }
12487 
12488     @Override
setResetPasswordToken(ComponentName admin, byte[] token)12489     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
12490         if (!mHasFeature) {
12491             return false;
12492         }
12493         if (token == null || token.length < 32) {
12494             throw new IllegalArgumentException("token must be at least 32-byte long");
12495         }
12496         synchronized (getLockObject()) {
12497             final int userHandle = mInjector.userHandleGetCallingUserId();
12498             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12499 
12500             DevicePolicyData policy = getUserData(userHandle);
12501             long ident = mInjector.binderClearCallingIdentity();
12502             try {
12503                 if (policy.mPasswordTokenHandle != 0) {
12504                     mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
12505                 }
12506 
12507                 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
12508                 saveSettingsLocked(userHandle);
12509                 return policy.mPasswordTokenHandle != 0;
12510             } finally {
12511                 mInjector.binderRestoreCallingIdentity(ident);
12512             }
12513         }
12514     }
12515 
12516     @Override
clearResetPasswordToken(ComponentName admin)12517     public boolean clearResetPasswordToken(ComponentName admin) {
12518         if (!mHasFeature) {
12519             return false;
12520         }
12521         synchronized (getLockObject()) {
12522             final int userHandle = mInjector.userHandleGetCallingUserId();
12523             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12524 
12525             DevicePolicyData policy = getUserData(userHandle);
12526             if (policy.mPasswordTokenHandle != 0) {
12527                 long ident = mInjector.binderClearCallingIdentity();
12528                 try {
12529                     boolean result = mLockPatternUtils.removeEscrowToken(
12530                             policy.mPasswordTokenHandle, userHandle);
12531                     policy.mPasswordTokenHandle = 0;
12532                     saveSettingsLocked(userHandle);
12533                     return result;
12534                 } finally {
12535                     mInjector.binderRestoreCallingIdentity(ident);
12536                 }
12537             }
12538         }
12539         return false;
12540     }
12541 
12542     @Override
isResetPasswordTokenActive(ComponentName admin)12543     public boolean isResetPasswordTokenActive(ComponentName admin) {
12544         synchronized (getLockObject()) {
12545             final int userHandle = mInjector.userHandleGetCallingUserId();
12546             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12547 
12548             DevicePolicyData policy = getUserData(userHandle);
12549             if (policy.mPasswordTokenHandle != 0) {
12550                 long ident = mInjector.binderClearCallingIdentity();
12551                 try {
12552                     return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
12553                             userHandle);
12554                 } finally {
12555                     mInjector.binderRestoreCallingIdentity(ident);
12556                 }
12557             }
12558         }
12559         return false;
12560     }
12561 
12562     @Override
resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, int flags)12563     public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
12564             int flags) {
12565         Preconditions.checkNotNull(token);
12566         synchronized (getLockObject()) {
12567             final int userHandle = mInjector.userHandleGetCallingUserId();
12568             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12569 
12570             DevicePolicyData policy = getUserData(userHandle);
12571             if (policy.mPasswordTokenHandle != 0) {
12572                 final String password = passwordOrNull != null ? passwordOrNull : "";
12573                 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
12574                         flags, mInjector.binderGetCallingUid(), userHandle);
12575             } else {
12576                 Slog.w(LOG_TAG, "No saved token handle");
12577             }
12578         }
12579         return false;
12580     }
12581 
12582     @Override
isCurrentInputMethodSetByOwner()12583     public boolean isCurrentInputMethodSetByOwner() {
12584         enforceProfileOwnerOrSystemUser();
12585         return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
12586     }
12587 
12588     @Override
getOwnerInstalledCaCerts(@onNull UserHandle user)12589     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
12590         final int userId = user.getIdentifier();
12591         enforceProfileOwnerOrFullCrossUsersPermission(userId);
12592         synchronized (getLockObject()) {
12593             return new StringParceledListSlice(
12594                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
12595         }
12596     }
12597 
12598     @Override
clearApplicationUserData(ComponentName admin, String packageName, IPackageDataObserver callback)12599     public void clearApplicationUserData(ComponentName admin, String packageName,
12600             IPackageDataObserver callback) {
12601         Preconditions.checkNotNull(admin, "ComponentName is null");
12602         Preconditions.checkNotNull(packageName, "packageName is null");
12603         Preconditions.checkNotNull(callback, "callback is null");
12604         synchronized (getLockObject()) {
12605             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12606         }
12607         final int userId = UserHandle.getCallingUserId();
12608 
12609         long ident = mInjector.binderClearCallingIdentity();
12610         try {
12611             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
12612                     userId);
12613         } catch(RemoteException re) {
12614             // Same process, should not happen.
12615         } catch (SecurityException se) {
12616             // This can happen e.g. for device admin packages, do not throw out the exception,
12617             // because callers have no means to know beforehand for which packages this might
12618             // happen. If so, we send back that removal failed.
12619             Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
12620                     se);
12621             try {
12622                 callback.onRemoveCompleted(packageName, false);
12623             } catch (RemoteException re) {
12624                 // Caller is no longer available, ignore
12625             }
12626         } finally {
12627             mInjector.binderRestoreCallingIdentity(ident);
12628         }
12629     }
12630 
12631     @Override
setLogoutEnabled(ComponentName admin, boolean enabled)12632     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
12633         if (!mHasFeature) {
12634             return;
12635         }
12636         Preconditions.checkNotNull(admin);
12637 
12638         synchronized (getLockObject()) {
12639             ActiveAdmin deviceOwner =
12640                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12641 
12642             if (deviceOwner.isLogoutEnabled == enabled) {
12643                 // already in the requested state
12644                 return;
12645             }
12646             deviceOwner.isLogoutEnabled = enabled;
12647             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12648         }
12649     }
12650 
12651     @Override
isLogoutEnabled()12652     public boolean isLogoutEnabled() {
12653         if (!mHasFeature) {
12654             return false;
12655         }
12656         synchronized (getLockObject()) {
12657             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12658             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
12659         }
12660     }
12661 
12662     @Override
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)12663     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
12664             String provisioningAction) throws RemoteException {
12665         enforceCanManageProfileAndDeviceOwners();
12666         return new ArrayList<>(
12667                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
12668     }
12669 
12670     @Override
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)12671     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
12672             @Nullable PersistableBundle bundle) {
12673         if (!mHasFeature) {
12674             return;
12675         }
12676 
12677         Preconditions.checkNotNull(admin, "Admin cannot be null.");
12678         Preconditions.checkNotNull(target, "Target cannot be null.");
12679 
12680         enforceProfileOrDeviceOwner(admin);
12681 
12682         if (admin.equals(target)) {
12683             throw new IllegalArgumentException("Provided administrator and target are "
12684                     + "the same object.");
12685         }
12686 
12687         if (admin.getPackageName().equals(target.getPackageName())) {
12688             throw new IllegalArgumentException("Provided administrator and target have "
12689                     + "the same package name.");
12690         }
12691 
12692         final int callingUserId = mInjector.userHandleGetCallingUserId();
12693         final DevicePolicyData policy = getUserData(callingUserId);
12694         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
12695                 /* throwForMissingPermission= */ true);
12696         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
12697         if (!incomingDeviceInfo.supportsTransferOwnership()) {
12698             throw new IllegalArgumentException("Provided target does not support "
12699                     + "ownership transfer.");
12700         }
12701 
12702         final long id = mInjector.binderClearCallingIdentity();
12703         try {
12704             synchronized (getLockObject()) {
12705                 /*
12706                 * We must ensure the whole process is atomic to prevent the device from ending up
12707                 * in an invalid state (e.g. no active admin). This could happen if the device
12708                 * is rebooted or work mode is turned off mid-transfer.
12709                 * In order to guarantee atomicity, we:
12710                 *
12711                 * 1. Save an atomic journal file describing the transfer process
12712                 * 2. Perform the transfer itself
12713                 * 3. Delete the journal file
12714                 *
12715                 * That way if the journal file exists on device boot, we know that the transfer
12716                 * must be reverted back to the original administrator. This logic is implemented in
12717                 * revertTransferOwnershipIfNecessaryLocked.
12718                 * */
12719                 if (bundle == null) {
12720                     bundle = new PersistableBundle();
12721                 }
12722                 if (isProfileOwner(admin, callingUserId)) {
12723                     prepareTransfer(admin, target, bundle, callingUserId,
12724                             ADMIN_TYPE_PROFILE_OWNER);
12725                     transferProfileOwnershipLocked(admin, target, callingUserId);
12726                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12727                             getTransferOwnershipAdminExtras(bundle), callingUserId);
12728                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
12729                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
12730                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
12731                     }
12732                 } else if (isDeviceOwner(admin, callingUserId)) {
12733                     prepareTransfer(admin, target, bundle, callingUserId,
12734                             ADMIN_TYPE_DEVICE_OWNER);
12735                     transferDeviceOwnershipLocked(admin, target, callingUserId);
12736                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12737                             getTransferOwnershipAdminExtras(bundle));
12738                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
12739                 }
12740             }
12741         } finally {
12742             mInjector.binderRestoreCallingIdentity(id);
12743         }
12744     }
12745 
prepareTransfer(ComponentName admin, ComponentName target, PersistableBundle bundle, int callingUserId, String adminType)12746     private void prepareTransfer(ComponentName admin, ComponentName target,
12747             PersistableBundle bundle, int callingUserId, String adminType) {
12748         saveTransferOwnershipBundleLocked(bundle, callingUserId);
12749         mTransferOwnershipMetadataManager.saveMetadataFile(
12750                 new TransferOwnershipMetadataManager.Metadata(admin, target,
12751                         callingUserId, adminType));
12752     }
12753 
postTransfer(String broadcast, int callingUserId)12754     private void postTransfer(String broadcast, int callingUserId) {
12755         deleteTransferOwnershipMetadataFileLocked();
12756         sendOwnerChangedBroadcast(broadcast, callingUserId);
12757     }
12758 
notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId)12759     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
12760         final Bundle extras = new Bundle();
12761         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
12762         sendDeviceOwnerCommand(
12763                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
12764     }
12765 
12766     /**
12767      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
12768      */
transferProfileOwnershipLocked(ComponentName admin, ComponentName target, int profileOwnerUserId)12769     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
12770             int profileOwnerUserId) {
12771         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
12772         mOwners.transferProfileOwner(target, profileOwnerUserId);
12773         Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
12774         mOwners.writeProfileOwner(profileOwnerUserId);
12775         mDeviceAdminServiceController.startServiceForOwner(
12776                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
12777     }
12778 
12779     /**
12780      * Transfers the device owner for user with id userId from admin to target.
12781      */
transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId)12782     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
12783         transferActiveAdminUncheckedLocked(target, admin, userId);
12784         mOwners.transferDeviceOwnership(target);
12785         Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
12786         mOwners.writeDeviceOwner();
12787         mDeviceAdminServiceController.startServiceForOwner(
12788                 target.getPackageName(), userId, "transfer-device-owner");
12789     }
12790 
getTransferOwnershipAdminExtras(PersistableBundle bundle)12791     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
12792         Bundle extras = new Bundle();
12793         if (bundle != null) {
12794             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
12795         }
12796         return extras;
12797     }
12798 
12799     @Override
setStartUserSessionMessage( ComponentName admin, CharSequence startUserSessionMessage)12800     public void setStartUserSessionMessage(
12801             ComponentName admin, CharSequence startUserSessionMessage) {
12802         if (!mHasFeature) {
12803             return;
12804         }
12805         Preconditions.checkNotNull(admin);
12806 
12807         final String startUserSessionMessageString =
12808                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
12809 
12810         synchronized (getLockObject()) {
12811             final ActiveAdmin deviceOwner =
12812                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12813 
12814             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
12815                 return;
12816             }
12817             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
12818             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12819         }
12820 
12821         mInjector.getActivityManagerInternal()
12822                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
12823     }
12824 
12825     @Override
setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage)12826     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
12827         if (!mHasFeature) {
12828             return;
12829         }
12830         Preconditions.checkNotNull(admin);
12831 
12832         final String endUserSessionMessageString =
12833                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
12834 
12835         synchronized (getLockObject()) {
12836             final ActiveAdmin deviceOwner =
12837                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12838 
12839             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
12840                 return;
12841             }
12842             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
12843             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12844         }
12845 
12846         mInjector.getActivityManagerInternal()
12847                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
12848     }
12849 
12850     @Override
getStartUserSessionMessage(ComponentName admin)12851     public String getStartUserSessionMessage(ComponentName admin) {
12852         if (!mHasFeature) {
12853             return null;
12854         }
12855         Preconditions.checkNotNull(admin);
12856 
12857         synchronized (getLockObject()) {
12858             final ActiveAdmin deviceOwner =
12859                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12860             return deviceOwner.startUserSessionMessage;
12861         }
12862     }
12863 
12864     @Override
getEndUserSessionMessage(ComponentName admin)12865     public String getEndUserSessionMessage(ComponentName admin) {
12866         if (!mHasFeature) {
12867             return null;
12868         }
12869         Preconditions.checkNotNull(admin);
12870 
12871         synchronized (getLockObject()) {
12872             final ActiveAdmin deviceOwner =
12873                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12874             return deviceOwner.endUserSessionMessage;
12875         }
12876     }
12877 
deleteTransferOwnershipMetadataFileLocked()12878     private void deleteTransferOwnershipMetadataFileLocked() {
12879         mTransferOwnershipMetadataManager.deleteMetadataFile();
12880     }
12881 
12882     @Override
12883     @Nullable
getTransferOwnershipBundle()12884     public PersistableBundle getTransferOwnershipBundle() {
12885         synchronized (getLockObject()) {
12886             final int callingUserId = mInjector.userHandleGetCallingUserId();
12887             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12888             final File bundleFile = new File(
12889                     mInjector.environmentGetUserSystemDirectory(callingUserId),
12890                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
12891             if (!bundleFile.exists()) {
12892                 return null;
12893             }
12894             try (FileInputStream stream = new FileInputStream(bundleFile)) {
12895                 XmlPullParser parser = Xml.newPullParser();
12896                 parser.setInput(stream, null);
12897                 parser.next();
12898                 return PersistableBundle.restoreFromXml(parser);
12899             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
12900                 Slog.e(LOG_TAG, "Caught exception while trying to load the "
12901                         + "owner transfer parameters from file " + bundleFile, e);
12902                 return null;
12903             }
12904         }
12905     }
12906 
12907     @Override
addOverrideApn(@onNull ComponentName who, @NonNull ApnSetting apnSetting)12908     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
12909         if (!mHasFeature) {
12910             return -1;
12911         }
12912         Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn");
12913         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn");
12914         synchronized (getLockObject()) {
12915             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12916         }
12917 
12918         int operatedId = -1;
12919         Uri resultUri;
12920         final long id = mInjector.binderClearCallingIdentity();
12921         try {
12922             resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12923         } finally {
12924             mInjector.binderRestoreCallingIdentity(id);
12925         }
12926         if (resultUri != null) {
12927             try {
12928                 operatedId = Integer.parseInt(resultUri.getLastPathSegment());
12929             } catch (NumberFormatException e) {
12930                 Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e);
12931             }
12932         }
12933 
12934         return operatedId;
12935     }
12936 
12937     @Override
updateOverrideApn(@onNull ComponentName who, int apnId, @NonNull ApnSetting apnSetting)12938     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
12939             @NonNull ApnSetting apnSetting) {
12940         if (!mHasFeature) {
12941             return false;
12942         }
12943         Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn");
12944         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn");
12945         synchronized (getLockObject()) {
12946             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12947         }
12948 
12949         if (apnId < 0) {
12950             return false;
12951         }
12952         final long id = mInjector.binderClearCallingIdentity();
12953         try {
12954             return mContext.getContentResolver().update(
12955                     Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12956                     apnSetting.toContentValues(), null, null) > 0;
12957         } finally {
12958             mInjector.binderRestoreCallingIdentity(id);
12959         }
12960     }
12961 
12962     @Override
removeOverrideApn(@onNull ComponentName who, int apnId)12963     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
12964         if (!mHasFeature) {
12965             return false;
12966         }
12967         Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn");
12968         synchronized (getLockObject()) {
12969             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12970         }
12971 
12972         return removeOverrideApnUnchecked(apnId);
12973     }
12974 
removeOverrideApnUnchecked(int apnId)12975     private boolean removeOverrideApnUnchecked(int apnId) {
12976         if(apnId < 0) {
12977             return false;
12978         }
12979         int numDeleted = 0;
12980         final long id = mInjector.binderClearCallingIdentity();
12981         try {
12982             numDeleted = mContext.getContentResolver().delete(
12983                     Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null);
12984         } finally {
12985             mInjector.binderRestoreCallingIdentity(id);
12986         }
12987         return numDeleted > 0;
12988     }
12989 
12990     @Override
getOverrideApns(@onNull ComponentName who)12991     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
12992         if (!mHasFeature) {
12993             return Collections.emptyList();
12994         }
12995         Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns");
12996         synchronized (getLockObject()) {
12997             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12998         }
12999 
13000         return getOverrideApnsUnchecked();
13001     }
13002 
getOverrideApnsUnchecked()13003     private List<ApnSetting> getOverrideApnsUnchecked() {
13004         final Cursor cursor;
13005         final long id = mInjector.binderClearCallingIdentity();
13006         try {
13007             cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null);
13008         } finally {
13009             mInjector.binderRestoreCallingIdentity(id);
13010         }
13011 
13012         if (cursor == null) {
13013             return Collections.emptyList();
13014         }
13015         try {
13016             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
13017             cursor.moveToPosition(-1);
13018             while (cursor.moveToNext()) {
13019                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
13020                 apnList.add(apn);
13021             }
13022             return apnList;
13023         } finally {
13024             cursor.close();
13025         }
13026     }
13027 
13028     @Override
setOverrideApnsEnabled(@onNull ComponentName who, boolean enabled)13029     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
13030         if (!mHasFeature) {
13031             return;
13032         }
13033         Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled");
13034         synchronized (getLockObject()) {
13035             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13036         }
13037 
13038         setOverrideApnsEnabledUnchecked(enabled);
13039     }
13040 
setOverrideApnsEnabledUnchecked(boolean enabled)13041     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
13042         ContentValues value = new ContentValues();
13043         value.put(ENFORCE_KEY, enabled);
13044         final long id = mInjector.binderClearCallingIdentity();
13045         try {
13046             mContext.getContentResolver().update(
13047                     ENFORCE_MANAGED_URI, value, null, null);
13048         } finally {
13049             mInjector.binderRestoreCallingIdentity(id);
13050         }
13051     }
13052 
13053     @Override
isOverrideApnEnabled(@onNull ComponentName who)13054     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
13055         if (!mHasFeature) {
13056             return false;
13057         }
13058         Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled");
13059         synchronized (getLockObject()) {
13060             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13061         }
13062 
13063         Cursor enforceCursor;
13064         final long id = mInjector.binderClearCallingIdentity();
13065         try {
13066             enforceCursor = mContext.getContentResolver().query(
13067                     ENFORCE_MANAGED_URI, null, null, null, null);
13068         } finally {
13069             mInjector.binderRestoreCallingIdentity(id);
13070         }
13071 
13072         if (enforceCursor == null) {
13073             return false;
13074         }
13075         try {
13076             if (enforceCursor.moveToFirst()) {
13077                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
13078             }
13079         } catch (IllegalArgumentException e) {
13080             Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
13081                     + "correct info.", e);
13082         } finally {
13083             enforceCursor.close();
13084         }
13085         return false;
13086     }
13087 
13088     @VisibleForTesting
saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId)13089     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
13090         final File parametersFile = new File(
13091                 mInjector.environmentGetUserSystemDirectory(userId),
13092                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
13093         final AtomicFile atomicFile = new AtomicFile(parametersFile);
13094         FileOutputStream stream = null;
13095         try {
13096             stream = atomicFile.startWrite();
13097             final XmlSerializer serializer = new FastXmlSerializer();
13098             serializer.setOutput(stream, StandardCharsets.UTF_8.name());
13099             serializer.startDocument(null, true);
13100             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
13101             bundle.saveToXml(serializer);
13102             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
13103             serializer.endDocument();
13104             atomicFile.finishWrite(stream);
13105         } catch (IOException | XmlPullParserException e) {
13106             Slog.e(LOG_TAG, "Caught exception while trying to save the "
13107                     + "owner transfer parameters to file " + parametersFile, e);
13108             parametersFile.delete();
13109             atomicFile.failWrite(stream);
13110         }
13111     }
13112 
deleteTransferOwnershipBundleLocked(int userId)13113     void deleteTransferOwnershipBundleLocked(int userId) {
13114         final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId),
13115                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
13116         parametersFile.delete();
13117     }
13118 
maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, PasswordMetrics metrics)13119     private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent,
13120             PasswordMetrics metrics) {
13121         if (SecurityLog.isLoggingEnabled()) {
13122             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
13123             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
13124                     userId, affectedUserId, metrics.length, metrics.quality, metrics.letters,
13125                     metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase,
13126                     metrics.symbols);
13127         }
13128     }
13129 
getManagedProvisioningPackage(Context context)13130     private static String getManagedProvisioningPackage(Context context) {
13131         return context.getResources().getString(R.string.config_managed_provisioning_package);
13132     }
13133 }
13134