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         ComponentName profileOwner = getProfileOwner(userHandle);
3934         // Profile challenge is supported on N or newer release.
3935         return profileOwner != null &&
3936                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3937     }
3938 
3939     @Override
setPasswordQuality(ComponentName who, int quality, boolean parent)3940     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3941         if (!mHasFeature) {
3942             return;
3943         }
3944         Preconditions.checkNotNull(who, "ComponentName is null");
3945         validateQualityConstant(quality);
3946 
3947         final int userId = mInjector.userHandleGetCallingUserId();
3948         synchronized (getLockObject()) {
3949             ActiveAdmin ap = getActiveAdminForCallerLocked(
3950                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3951             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
3952             if (metrics.quality != quality) {
3953                 metrics.quality = quality;
3954                 updatePasswordValidityCheckpointLocked(userId, parent);
3955                 saveSettingsLocked(userId);
3956             }
3957             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
3958         }
3959     }
3960 
3961     /**
3962      * Updates a flag that tells us whether the user's password currently satisfies the
3963      * requirements set by all of the user's active admins. The flag is updated both in memory
3964      * and persisted to disk by calling {@link #saveSettingsLocked}, for the value of the flag
3965      * be the correct one upon boot.
3966      * This should be called whenever the password or the admin policies have changed.
3967      */
updatePasswordValidityCheckpointLocked(int userHandle, boolean parent)3968     private void updatePasswordValidityCheckpointLocked(int userHandle, boolean parent) {
3969         final int credentialOwner = getCredentialOwner(userHandle, parent);
3970         DevicePolicyData policy = getUserData(credentialOwner);
3971         PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
3972         if (metrics == null) {
3973             metrics = new PasswordMetrics();
3974         }
3975         policy.mPasswordValidAtLastCheckpoint =
3976                 isPasswordSufficientForUserWithoutCheckpointLocked(
3977                         metrics, userHandle, parent);
3978 
3979         saveSettingsLocked(credentialOwner);
3980     }
3981 
3982     @Override
getPasswordQuality(ComponentName who, int userHandle, boolean parent)3983     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3984         if (!mHasFeature) {
3985             return PASSWORD_QUALITY_UNSPECIFIED;
3986         }
3987         enforceFullCrossUsersPermission(userHandle);
3988         synchronized (getLockObject()) {
3989             int mode = PASSWORD_QUALITY_UNSPECIFIED;
3990 
3991             if (who != null) {
3992                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3993                 return admin != null ? admin.minimumPasswordMetrics.quality : mode;
3994             }
3995 
3996             // Return the strictest policy across all participating admins.
3997             List<ActiveAdmin> admins =
3998                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3999             final int N = admins.size();
4000             for (int i = 0; i < N; i++) {
4001                 ActiveAdmin admin = admins.get(i);
4002                 if (mode < admin.minimumPasswordMetrics.quality) {
4003                     mode = admin.minimumPasswordMetrics.quality;
4004                 }
4005             }
4006             return mode;
4007         }
4008     }
4009 
getActiveAdminsForLockscreenPoliciesLocked( int userHandle, boolean parent)4010     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
4011             int userHandle, boolean parent) {
4012         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
4013             // If this user has a separate challenge, only return its restrictions.
4014             return getUserDataUnchecked(userHandle).mAdminList;
4015         } else {
4016             // Return all admins for this user and the profiles that are visible from this
4017             // user that do not use a separate work challenge.
4018             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4019             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4020                 DevicePolicyData policy = getUserData(userInfo.id);
4021                 if (!userInfo.isManagedProfile()) {
4022                     admins.addAll(policy.mAdminList);
4023                 } else {
4024                     // For managed profiles, we always include the policies set on the parent
4025                     // profile. Additionally, we include the ones set on the managed profile
4026                     // if no separate challenge is in place.
4027                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
4028                     final int N = policy.mAdminList.size();
4029                     for (int i = 0; i < N; i++) {
4030                         ActiveAdmin admin = policy.mAdminList.get(i);
4031                         if (admin.hasParentActiveAdmin()) {
4032                             admins.add(admin.getParentActiveAdmin());
4033                         }
4034                         if (!hasSeparateChallenge) {
4035                             admins.add(admin);
4036                         }
4037                     }
4038                 }
4039             }
4040             return admins;
4041         }
4042     }
4043 
isSeparateProfileChallengeEnabled(int userHandle)4044     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
4045         long ident = mInjector.binderClearCallingIdentity();
4046         try {
4047             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
4048         } finally {
4049             mInjector.binderRestoreCallingIdentity(ident);
4050         }
4051     }
4052 
4053     @Override
setPasswordMinimumLength(ComponentName who, int length, boolean parent)4054     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
4055         if (!mHasFeature) {
4056             return;
4057         }
4058         Preconditions.checkNotNull(who, "ComponentName is null");
4059         final int userId = mInjector.userHandleGetCallingUserId();
4060         synchronized (getLockObject()) {
4061             ActiveAdmin ap = getActiveAdminForCallerLocked(
4062                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4063             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4064             if (metrics.length != length) {
4065                 metrics.length = length;
4066                 updatePasswordValidityCheckpointLocked(userId, parent);
4067                 saveSettingsLocked(userId);
4068             }
4069             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4070         }
4071     }
4072 
4073     @Override
getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent)4074     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
4075         return getStrictestPasswordRequirement(who, userHandle, parent,
4076                 admin -> admin.minimumPasswordMetrics.length, PASSWORD_QUALITY_UNSPECIFIED);
4077     }
4078 
4079     @Override
setPasswordHistoryLength(ComponentName who, int length, boolean parent)4080     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
4081         if (!mHasFeature) {
4082             return;
4083         }
4084         Preconditions.checkNotNull(who, "ComponentName is null");
4085         final int userId = mInjector.userHandleGetCallingUserId();
4086         synchronized (getLockObject()) {
4087             ActiveAdmin ap = getActiveAdminForCallerLocked(
4088                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4089             if (ap.passwordHistoryLength != length) {
4090                 ap.passwordHistoryLength = length;
4091                 updatePasswordValidityCheckpointLocked(userId, parent);
4092                 saveSettingsLocked(userId);
4093             }
4094         }
4095         if (SecurityLog.isLoggingEnabled()) {
4096             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4097             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_HISTORY_LENGTH_SET,
4098                     who.getPackageName(), userId, affectedUserId, length);
4099         }
4100     }
4101 
4102     @Override
getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent)4103     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
4104         return getStrictestPasswordRequirement(who, userHandle, parent,
4105                 admin -> admin.passwordHistoryLength, PASSWORD_QUALITY_UNSPECIFIED);
4106     }
4107 
4108     @Override
setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent)4109     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
4110         if (!mHasFeature) {
4111             return;
4112         }
4113         Preconditions.checkNotNull(who, "ComponentName is null");
4114         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
4115         final int userHandle = mInjector.userHandleGetCallingUserId();
4116         synchronized (getLockObject()) {
4117             ActiveAdmin ap = getActiveAdminForCallerLocked(
4118                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
4119             // Calling this API automatically bumps the expiration date
4120             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4121             ap.passwordExpirationDate = expiration;
4122             ap.passwordExpirationTimeout = timeout;
4123             if (timeout > 0L) {
4124                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
4125                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
4126                         .format(new Date(expiration)));
4127             }
4128             saveSettingsLocked(userHandle);
4129 
4130             // in case this is the first one, set the alarm on the appropriate user.
4131             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
4132         }
4133         if (SecurityLog.isLoggingEnabled()) {
4134             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4135             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_EXPIRATION_SET, who.getPackageName(),
4136                     userHandle, affectedUserId, timeout);
4137         }
4138     }
4139 
4140     /**
4141      * Return a single admin's expiration cycle time, or the min of all cycle times.
4142      * Returns 0 if not configured.
4143      */
4144     @Override
getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent)4145     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
4146         if (!mHasFeature) {
4147             return 0L;
4148         }
4149         enforceFullCrossUsersPermission(userHandle);
4150         synchronized (getLockObject()) {
4151             long timeout = 0L;
4152 
4153             if (who != null) {
4154                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4155                 return admin != null ? admin.passwordExpirationTimeout : timeout;
4156             }
4157 
4158             // Return the strictest policy across all participating admins.
4159             List<ActiveAdmin> admins =
4160                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4161             final int N = admins.size();
4162             for (int i = 0; i < N; i++) {
4163                 ActiveAdmin admin = admins.get(i);
4164                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
4165                         && timeout > admin.passwordExpirationTimeout)) {
4166                     timeout = admin.passwordExpirationTimeout;
4167                 }
4168             }
4169             return timeout;
4170         }
4171     }
4172 
4173     @Override
addCrossProfileWidgetProvider(ComponentName admin, String packageName)4174     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4175         final int userId = UserHandle.getCallingUserId();
4176         List<String> changedProviders = null;
4177 
4178         synchronized (getLockObject()) {
4179             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4180                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4181             if (activeAdmin.crossProfileWidgetProviders == null) {
4182                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
4183             }
4184             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4185             if (!providers.contains(packageName)) {
4186                 providers.add(packageName);
4187                 changedProviders = new ArrayList<>(providers);
4188                 saveSettingsLocked(userId);
4189             }
4190         }
4191 
4192         if (changedProviders != null) {
4193             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4194             return true;
4195         }
4196 
4197         return false;
4198     }
4199 
4200     @Override
removeCrossProfileWidgetProvider(ComponentName admin, String packageName)4201     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
4202         final int userId = UserHandle.getCallingUserId();
4203         List<String> changedProviders = null;
4204 
4205         synchronized (getLockObject()) {
4206             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4207                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4208             if (activeAdmin.crossProfileWidgetProviders == null
4209                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4210                 return false;
4211             }
4212             List<String> providers = activeAdmin.crossProfileWidgetProviders;
4213             if (providers.remove(packageName)) {
4214                 changedProviders = new ArrayList<>(providers);
4215                 saveSettingsLocked(userId);
4216             }
4217         }
4218 
4219         if (changedProviders != null) {
4220             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
4221             return true;
4222         }
4223 
4224         return false;
4225     }
4226 
4227     @Override
getCrossProfileWidgetProviders(ComponentName admin)4228     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
4229         synchronized (getLockObject()) {
4230             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
4231                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4232             if (activeAdmin.crossProfileWidgetProviders == null
4233                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
4234                 return null;
4235             }
4236             if (mInjector.binderIsCallingUidMyUid()) {
4237                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
4238             } else {
4239                 return activeAdmin.crossProfileWidgetProviders;
4240             }
4241         }
4242     }
4243 
4244     /**
4245      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
4246      * Returns 0 if not configured.
4247      */
getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent)4248     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
4249         long timeout = 0L;
4250 
4251         if (who != null) {
4252             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4253             return admin != null ? admin.passwordExpirationDate : timeout;
4254         }
4255 
4256         // Return the strictest policy across all participating admins.
4257         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4258         final int N = admins.size();
4259         for (int i = 0; i < N; i++) {
4260             ActiveAdmin admin = admins.get(i);
4261             if (timeout == 0L || (admin.passwordExpirationDate != 0
4262                     && timeout > admin.passwordExpirationDate)) {
4263                 timeout = admin.passwordExpirationDate;
4264             }
4265         }
4266         return timeout;
4267     }
4268 
4269     @Override
getPasswordExpiration(ComponentName who, int userHandle, boolean parent)4270     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
4271         if (!mHasFeature) {
4272             return 0L;
4273         }
4274         enforceFullCrossUsersPermission(userHandle);
4275         synchronized (getLockObject()) {
4276             return getPasswordExpirationLocked(who, userHandle, parent);
4277         }
4278     }
4279 
4280     @Override
setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent)4281     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
4282         if (!mHasFeature) {
4283             return;
4284         }
4285         Preconditions.checkNotNull(who, "ComponentName is null");
4286         final int userId = mInjector.userHandleGetCallingUserId();
4287         synchronized (getLockObject()) {
4288             final ActiveAdmin ap = getActiveAdminForCallerLocked(
4289                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4290             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4291             if (metrics.upperCase != length) {
4292                 metrics.upperCase = length;
4293                 updatePasswordValidityCheckpointLocked(userId, parent);
4294                 saveSettingsLocked(userId);
4295             }
4296             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4297         }
4298     }
4299 
4300     @Override
getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent)4301     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
4302         return getStrictestPasswordRequirement(who, userHandle, parent,
4303                 admin -> admin.minimumPasswordMetrics.upperCase, PASSWORD_QUALITY_COMPLEX);
4304     }
4305 
4306     @Override
setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent)4307     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
4308         Preconditions.checkNotNull(who, "ComponentName is null");
4309         final int userId = mInjector.userHandleGetCallingUserId();
4310         synchronized (getLockObject()) {
4311             ActiveAdmin ap = getActiveAdminForCallerLocked(
4312                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4313             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4314             if (metrics.lowerCase != length) {
4315                 metrics.lowerCase = length;
4316                 updatePasswordValidityCheckpointLocked(userId, parent);
4317                 saveSettingsLocked(userId);
4318             }
4319             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4320         }
4321     }
4322 
4323     @Override
getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent)4324     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
4325         return getStrictestPasswordRequirement(who, userHandle, parent,
4326                 admin -> admin.minimumPasswordMetrics.lowerCase, PASSWORD_QUALITY_COMPLEX);
4327     }
4328 
4329     @Override
setPasswordMinimumLetters(ComponentName who, int length, boolean parent)4330     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
4331         if (!mHasFeature) {
4332             return;
4333         }
4334         Preconditions.checkNotNull(who, "ComponentName is null");
4335         final int userId = mInjector.userHandleGetCallingUserId();
4336         synchronized (getLockObject()) {
4337             ActiveAdmin ap = getActiveAdminForCallerLocked(
4338                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4339             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4340             if (metrics.letters != length) {
4341                 metrics.letters = length;
4342                 updatePasswordValidityCheckpointLocked(userId, parent);
4343                 saveSettingsLocked(userId);
4344             }
4345             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4346         }
4347     }
4348 
4349     @Override
getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent)4350     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
4351         return getStrictestPasswordRequirement(who, userHandle, parent,
4352                 admin -> admin.minimumPasswordMetrics.letters, PASSWORD_QUALITY_COMPLEX);
4353     }
4354 
4355     @Override
setPasswordMinimumNumeric(ComponentName who, int length, boolean parent)4356     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
4357         if (!mHasFeature) {
4358             return;
4359         }
4360         Preconditions.checkNotNull(who, "ComponentName is null");
4361         final int userId = mInjector.userHandleGetCallingUserId();
4362         synchronized (getLockObject()) {
4363             ActiveAdmin ap = getActiveAdminForCallerLocked(
4364                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4365             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4366             if (metrics.numeric != length) {
4367                 metrics.numeric = length;
4368                 updatePasswordValidityCheckpointLocked(userId, parent);
4369                 saveSettingsLocked(userId);
4370             }
4371             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4372         }
4373     }
4374 
4375     @Override
getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent)4376     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
4377         return getStrictestPasswordRequirement(who, userHandle, parent,
4378                 admin -> admin.minimumPasswordMetrics.numeric, PASSWORD_QUALITY_COMPLEX);
4379     }
4380 
4381     @Override
setPasswordMinimumSymbols(ComponentName who, int length, boolean parent)4382     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
4383         if (!mHasFeature) {
4384             return;
4385         }
4386         Preconditions.checkNotNull(who, "ComponentName is null");
4387         final int userId = mInjector.userHandleGetCallingUserId();
4388         synchronized (getLockObject()) {
4389             ActiveAdmin ap = getActiveAdminForCallerLocked(
4390                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4391             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4392             if (metrics.symbols != length) {
4393                 ap.minimumPasswordMetrics.symbols = length;
4394                 updatePasswordValidityCheckpointLocked(userId, parent);
4395                 saveSettingsLocked(userId);
4396             }
4397             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4398         }
4399     }
4400 
4401     @Override
getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent)4402     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
4403         return getStrictestPasswordRequirement(who, userHandle, parent,
4404                 admin -> admin.minimumPasswordMetrics.symbols, PASSWORD_QUALITY_COMPLEX);
4405     }
4406 
4407     @Override
setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent)4408     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
4409         if (!mHasFeature) {
4410             return;
4411         }
4412         Preconditions.checkNotNull(who, "ComponentName is null");
4413         final int userId = mInjector.userHandleGetCallingUserId();
4414         synchronized (getLockObject()) {
4415             ActiveAdmin ap = getActiveAdminForCallerLocked(
4416                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4417             final PasswordMetrics metrics = ap.minimumPasswordMetrics;
4418             if (metrics.nonLetter != length) {
4419                 ap.minimumPasswordMetrics.nonLetter = length;
4420                 updatePasswordValidityCheckpointLocked(userId, parent);
4421                 saveSettingsLocked(userId);
4422             }
4423             maybeLogPasswordComplexitySet(who, userId, parent, metrics);
4424         }
4425     }
4426 
4427     @Override
getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent)4428     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
4429         return getStrictestPasswordRequirement(who, userHandle, parent,
4430                 admin -> admin.minimumPasswordMetrics.nonLetter, PASSWORD_QUALITY_COMPLEX);
4431     }
4432 
4433     /**
4434      * Calculates strictest (maximum) value for a given password property enforced by admin[s].
4435      */
getStrictestPasswordRequirement(ComponentName who, int userHandle, boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality)4436     private int getStrictestPasswordRequirement(ComponentName who, int userHandle,
4437             boolean parent, Function<ActiveAdmin, Integer> getter, int minimumPasswordQuality) {
4438         if (!mHasFeature) {
4439             return 0;
4440         }
4441         enforceFullCrossUsersPermission(userHandle);
4442         synchronized (getLockObject()) {
4443             if (who != null) {
4444                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4445                 return admin != null ? getter.apply(admin) : 0;
4446             }
4447 
4448             int maxValue = 0;
4449             final List<ActiveAdmin> admins =
4450                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4451             final int N = admins.size();
4452             for (int i = 0; i < N; i++) {
4453                 final ActiveAdmin admin = admins.get(i);
4454                 if (!isLimitPasswordAllowed(admin, minimumPasswordQuality)) {
4455                     continue;
4456                 }
4457                 final Integer adminValue = getter.apply(admin);
4458                 if (adminValue > maxValue) {
4459                     maxValue = adminValue;
4460                 }
4461             }
4462             return maxValue;
4463         }
4464     }
4465 
4466     @Override
isActivePasswordSufficient(int userHandle, boolean parent)4467     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
4468         if (!mHasFeature) {
4469             return true;
4470         }
4471         enforceFullCrossUsersPermission(userHandle);
4472         enforceUserUnlocked(userHandle, parent);
4473 
4474         synchronized (getLockObject()) {
4475             // This API can only be called by an active device admin,
4476             // so try to retrieve it to check that the caller is one.
4477             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
4478             int credentialOwner = getCredentialOwner(userHandle, parent);
4479             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4480             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4481             return isActivePasswordSufficientForUserLocked(
4482                     policy.mPasswordValidAtLastCheckpoint, metrics, userHandle, parent);
4483         }
4484     }
4485 
4486     @Override
isUsingUnifiedPassword(ComponentName admin)4487     public boolean isUsingUnifiedPassword(ComponentName admin) {
4488         if (!mHasFeature) {
4489             return true;
4490         }
4491         final int userId = mInjector.userHandleGetCallingUserId();
4492         enforceProfileOrDeviceOwner(admin);
4493         enforceManagedProfile(userId, "query unified challenge status");
4494         return !isSeparateProfileChallengeEnabled(userId);
4495     }
4496 
4497     @Override
isProfileActivePasswordSufficientForParent(int userHandle)4498     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
4499         if (!mHasFeature) {
4500             return true;
4501         }
4502         enforceFullCrossUsersPermission(userHandle);
4503         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
4504 
4505         synchronized (getLockObject()) {
4506             final int targetUser = getProfileParentId(userHandle);
4507             enforceUserUnlocked(targetUser, false);
4508             int credentialOwner = getCredentialOwner(userHandle, false);
4509             DevicePolicyData policy = getUserDataUnchecked(credentialOwner);
4510             PasswordMetrics metrics = getUserPasswordMetricsLocked(credentialOwner);
4511             return isActivePasswordSufficientForUserLocked(
4512                     policy.mPasswordValidAtLastCheckpoint, metrics, targetUser, false);
4513         }
4514     }
4515 
isActivePasswordSufficientForUserLocked( boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle, boolean parent)4516     private boolean isActivePasswordSufficientForUserLocked(
4517             boolean passwordValidAtLastCheckpoint, PasswordMetrics metrics, int userHandle,
4518             boolean parent) {
4519         if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && (metrics == null)) {
4520             // Before user enters their password for the first time after a reboot, return the
4521             // value of this flag, which tells us whether the password was valid the last time
4522             // settings were saved.  If DPC changes password requirements on boot so that the
4523             // current password no longer meets the requirements, this value will be stale until
4524             // the next time the password is entered.
4525             return passwordValidAtLastCheckpoint;
4526         }
4527 
4528         if (metrics == null) {
4529             // This could happen if the user never had a password set, for example, so
4530             // setActivePasswordState has never been called for it.
4531             metrics = new PasswordMetrics();
4532         }
4533         return isPasswordSufficientForUserWithoutCheckpointLocked(metrics, userHandle, parent);
4534     }
4535 
4536     /**
4537      * Returns {@code true} if the password represented by the {@code passwordMetrics} argument
4538      * sufficiently fulfills the password requirements for the user corresponding to
4539      * {@code userHandle} (or its parent, if {@code parent} is set to {@code true}).
4540      */
isPasswordSufficientForUserWithoutCheckpointLocked( PasswordMetrics passwordMetrics, int userHandle, boolean parent)4541     private boolean isPasswordSufficientForUserWithoutCheckpointLocked(
4542             PasswordMetrics passwordMetrics, int userHandle, boolean parent) {
4543         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
4544 
4545         if (passwordMetrics.quality < requiredPasswordQuality) {
4546             return false;
4547         }
4548         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
4549                 && passwordMetrics.length < getPasswordMinimumLength(
4550                         null, userHandle, parent)) {
4551             return false;
4552         }
4553         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4554             return true;
4555         }
4556         return passwordMetrics.upperCase >= getPasswordMinimumUpperCase(
4557                     null, userHandle, parent)
4558                 && passwordMetrics.lowerCase >= getPasswordMinimumLowerCase(
4559                         null, userHandle, parent)
4560                 && passwordMetrics.letters >= getPasswordMinimumLetters(
4561                         null, userHandle, parent)
4562                 && passwordMetrics.numeric >= getPasswordMinimumNumeric(
4563                         null, userHandle, parent)
4564                 && passwordMetrics.symbols >= getPasswordMinimumSymbols(
4565                         null, userHandle, parent)
4566                 && passwordMetrics.nonLetter >= getPasswordMinimumNonLetter(
4567                         null, userHandle, parent);
4568     }
4569 
4570     @Override
getCurrentFailedPasswordAttempts(int userHandle, boolean parent)4571     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
4572         enforceFullCrossUsersPermission(userHandle);
4573         synchronized (getLockObject()) {
4574             if (!isCallerWithSystemUid()) {
4575                 // This API can only be called by an active device admin,
4576                 // so try to retrieve it to check that the caller is one.
4577                 getActiveAdminForCallerLocked(
4578                         null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4579             }
4580 
4581             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
4582 
4583             return policy.mFailedPasswordAttempts;
4584         }
4585     }
4586 
4587     @Override
setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent)4588     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
4589         if (!mHasFeature) {
4590             return;
4591         }
4592         Preconditions.checkNotNull(who, "ComponentName is null");
4593         final int userId = mInjector.userHandleGetCallingUserId();
4594         synchronized (getLockObject()) {
4595             // This API can only be called by an active device admin,
4596             // so try to retrieve it to check that the caller is one.
4597             getActiveAdminForCallerLocked(
4598                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
4599             ActiveAdmin ap = getActiveAdminForCallerLocked(
4600                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
4601             if (ap.maximumFailedPasswordsForWipe != num) {
4602                 ap.maximumFailedPasswordsForWipe = num;
4603                 saveSettingsLocked(userId);
4604             }
4605         }
4606         if (SecurityLog.isLoggingEnabled()) {
4607             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
4608             SecurityLog.writeEvent(SecurityLog.TAG_MAX_PASSWORD_ATTEMPTS_SET, who.getPackageName(),
4609                     userId, affectedUserId, num);
4610         }
4611     }
4612 
4613     @Override
getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent)4614     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
4615         if (!mHasFeature) {
4616             return 0;
4617         }
4618         enforceFullCrossUsersPermission(userHandle);
4619         synchronized (getLockObject()) {
4620             ActiveAdmin admin = (who != null)
4621                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
4622                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
4623             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
4624         }
4625     }
4626 
4627     @Override
getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent)4628     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
4629         if (!mHasFeature) {
4630             return UserHandle.USER_NULL;
4631         }
4632         enforceFullCrossUsersPermission(userHandle);
4633         synchronized (getLockObject()) {
4634             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4635                     userHandle, parent);
4636             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
4637         }
4638     }
4639 
4640     /**
4641      * Returns the admin with the strictest policy on maximum failed passwords for:
4642      * <ul>
4643      *   <li>this user if it has a separate profile challenge, or
4644      *   <li>this user and all profiles that don't have their own challenge otherwise.
4645      * </ul>
4646      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
4647      * the primary profile.
4648      * Returns {@code null} if no participating admin has that policy set.
4649      */
getAdminWithMinimumFailedPasswordsForWipeLocked( int userHandle, boolean parent)4650     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
4651             int userHandle, boolean parent) {
4652         int count = 0;
4653         ActiveAdmin strictestAdmin = null;
4654 
4655         // Return the strictest policy across all participating admins.
4656         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
4657         final int N = admins.size();
4658         for (int i = 0; i < N; i++) {
4659             ActiveAdmin admin = admins.get(i);
4660             if (admin.maximumFailedPasswordsForWipe ==
4661                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
4662                 continue;  // No max number of failed passwords policy set for this profile.
4663             }
4664 
4665             // We always favor the primary profile if several profiles have the same value set.
4666             int userId = admin.getUserHandle().getIdentifier();
4667             if (count == 0 ||
4668                     count > admin.maximumFailedPasswordsForWipe ||
4669                     (count == admin.maximumFailedPasswordsForWipe &&
4670                             getUserInfo(userId).isPrimary())) {
4671                 count = admin.maximumFailedPasswordsForWipe;
4672                 strictestAdmin = admin;
4673             }
4674         }
4675         return strictestAdmin;
4676     }
4677 
getUserInfo(@serIdInt int userId)4678     private UserInfo getUserInfo(@UserIdInt int userId) {
4679         final long token = mInjector.binderClearCallingIdentity();
4680         try {
4681             return mUserManager.getUserInfo(userId);
4682         } finally {
4683             mInjector.binderRestoreCallingIdentity(token);
4684         }
4685     }
4686 
canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId)4687     private boolean canPOorDOCallResetPassword(ActiveAdmin admin, @UserIdInt int userId) {
4688         // Only if the admins targets a pre-O SDK
4689         return getTargetSdk(admin.info.getPackageName(), userId) < Build.VERSION_CODES.O;
4690     }
4691 
4692     /* PO or DO could do an untrusted reset in certain conditions. */
canUserHaveUntrustedCredentialReset(@serIdInt int userId)4693     private boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
4694         synchronized (getLockObject()) {
4695             // An active DO or PO might be able to fo an untrusted credential reset
4696             for (final ActiveAdmin admin : getUserData(userId).mAdminList) {
4697                 if (!isActiveAdminWithPolicyForUserLocked(admin,
4698                           DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, userId)) {
4699                     continue;
4700                 }
4701                 if (canPOorDOCallResetPassword(admin, userId)) {
4702                     return true;
4703                 }
4704             }
4705             return false;
4706         }
4707     }
4708     @Override
resetPassword(String passwordOrNull, int flags)4709     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
4710         final int callingUid = mInjector.binderGetCallingUid();
4711         final int userHandle = mInjector.userHandleGetCallingUserId();
4712 
4713         String password = passwordOrNull != null ? passwordOrNull : "";
4714 
4715         // Password resetting to empty/null is not allowed for managed profiles.
4716         if (TextUtils.isEmpty(password)) {
4717             enforceNotManagedProfile(userHandle, "clear the active password");
4718         }
4719 
4720         synchronized (getLockObject()) {
4721             // If caller has PO (or DO) it can change the password, so see if that's the case first.
4722             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
4723                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
4724             final boolean preN;
4725             if (admin != null) {
4726                 if (!canPOorDOCallResetPassword(admin, userHandle)) {
4727                     throw new SecurityException("resetPassword() is deprecated for DPC targeting O"
4728                             + " or later");
4729                 }
4730                 preN = getTargetSdk(admin.info.getPackageName(),
4731                         userHandle) <= android.os.Build.VERSION_CODES.M;
4732             } else {
4733                 // Otherwise, make sure the caller has any active admin with the right policy.
4734                 admin = getActiveAdminForCallerLocked(null,
4735                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
4736                 preN = getTargetSdk(admin.info.getPackageName(),
4737                         userHandle) <= android.os.Build.VERSION_CODES.M;
4738 
4739                 // As of N, password resetting to empty/null is not allowed anymore.
4740                 // TODO Should we allow DO/PO to set an empty password?
4741                 if (TextUtils.isEmpty(password)) {
4742                     if (!preN) {
4743                         throw new SecurityException("Cannot call with null password");
4744                     } else {
4745                         Slog.e(LOG_TAG, "Cannot call with null password");
4746                         return false;
4747                     }
4748                 }
4749                 // As of N, password cannot be changed by the admin if it is already set.
4750                 if (isLockScreenSecureUnchecked(userHandle)) {
4751                     if (!preN) {
4752                         throw new SecurityException("Admin cannot change current password");
4753                     } else {
4754                         Slog.e(LOG_TAG, "Admin cannot change current password");
4755                         return false;
4756                     }
4757                 }
4758             }
4759             // Do not allow to reset password when current user has a managed profile
4760             if (!isManagedProfile(userHandle)) {
4761                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4762                     if (userInfo.isManagedProfile()) {
4763                         if (!preN) {
4764                             throw new IllegalStateException(
4765                                     "Cannot reset password on user has managed profile");
4766                         } else {
4767                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
4768                             return false;
4769                         }
4770                     }
4771                 }
4772             }
4773             // Do not allow to reset password when user is locked
4774             if (!mUserManager.isUserUnlocked(userHandle)) {
4775                 if (!preN) {
4776                     throw new IllegalStateException("Cannot reset password when user is locked");
4777                 } else {
4778                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
4779                     return false;
4780                 }
4781             }
4782         }
4783 
4784         return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle);
4785     }
4786 
resetPasswordInternal(String password, long tokenHandle, byte[] token, int flags, int callingUid, int userHandle)4787     private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token,
4788             int flags, int callingUid, int userHandle) {
4789         int quality;
4790         synchronized (getLockObject()) {
4791             quality = getPasswordQuality(null, userHandle, /* parent */ false);
4792             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
4793                 quality = PASSWORD_QUALITY_UNSPECIFIED;
4794             }
4795             final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password);
4796             if (quality != PASSWORD_QUALITY_UNSPECIFIED) {
4797                 final int realQuality = metrics.quality;
4798                 if (realQuality < quality
4799                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4800                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
4801                             + Integer.toHexString(realQuality)
4802                             + " does not meet required quality 0x"
4803                             + Integer.toHexString(quality));
4804                     return false;
4805                 }
4806                 quality = Math.max(realQuality, quality);
4807             }
4808             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
4809             if (password.length() < length) {
4810                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
4811                         + " does not meet required length " + length);
4812                 return false;
4813             }
4814             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
4815                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4816                 if(metrics.letters < neededLetters) {
4817                     Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters
4818                             + " does not meet required number of letters " + neededLetters);
4819                     return false;
4820                 }
4821                 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4822                 if (metrics.numeric < neededNumeric) {
4823                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric
4824                             + " does not meet required number of numerical digits "
4825                             + neededNumeric);
4826                     return false;
4827                 }
4828                 int neededLowerCase = getPasswordMinimumLowerCase(
4829                         null, userHandle, /* parent */ false);
4830                 if (metrics.lowerCase < neededLowerCase) {
4831                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters "
4832                             + metrics.lowerCase
4833                             + " does not meet required number of lowercase letters "
4834                             + neededLowerCase);
4835                     return false;
4836                 }
4837                 int neededUpperCase = getPasswordMinimumUpperCase(
4838                         null, userHandle, /* parent */ false);
4839                 if (metrics.upperCase < neededUpperCase) {
4840                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters "
4841                             + metrics.upperCase
4842                             + " does not meet required number of uppercase letters "
4843                             + neededUpperCase);
4844                     return false;
4845                 }
4846                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4847                 if (metrics.symbols < neededSymbols) {
4848                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols
4849                             + " does not meet required number of special symbols " + neededSymbols);
4850                     return false;
4851                 }
4852                 int neededNonLetter = getPasswordMinimumNonLetter(
4853                         null, userHandle, /* parent */ false);
4854                 if (metrics.nonLetter < neededNonLetter) {
4855                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters "
4856                             + metrics.nonLetter
4857                             + " does not meet required number of non-letter characters "
4858                             + neededNonLetter);
4859                     return false;
4860                 }
4861             }
4862         }
4863 
4864         DevicePolicyData policy = getUserData(userHandle);
4865         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4866             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4867             return false;
4868         }
4869 
4870         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4871         boolean doNotAskCredentialsOnBoot =
4872                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4873         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4874             setDoNotAskCredentialsOnBoot();
4875         }
4876 
4877         // Don't do this with the lock held, because it is going to call
4878         // back in to the service.
4879         final long ident = mInjector.binderClearCallingIdentity();
4880         final boolean result;
4881         try {
4882             if (token == null) {
4883                 if (!TextUtils.isEmpty(password)) {
4884                     mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4885                 } else {
4886                     mLockPatternUtils.clearLock(null, userHandle);
4887                 }
4888                 result = true;
4889             } else {
4890                 result = mLockPatternUtils.setLockCredentialWithToken(password,
4891                         TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE
4892                                 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
4893                                 quality, tokenHandle, token, userHandle);
4894             }
4895             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4896             if (requireEntry) {
4897                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4898                         UserHandle.USER_ALL);
4899             }
4900             synchronized (getLockObject()) {
4901                 int newOwner = requireEntry ? callingUid : -1;
4902                 if (policy.mPasswordOwner != newOwner) {
4903                     policy.mPasswordOwner = newOwner;
4904                     saveSettingsLocked(userHandle);
4905                 }
4906             }
4907         } finally {
4908             mInjector.binderRestoreCallingIdentity(ident);
4909         }
4910         return result;
4911     }
4912 
isLockScreenSecureUnchecked(int userId)4913     private boolean isLockScreenSecureUnchecked(int userId) {
4914         long ident = mInjector.binderClearCallingIdentity();
4915         try {
4916             return mLockPatternUtils.isSecure(userId);
4917         } finally {
4918             mInjector.binderRestoreCallingIdentity(ident);
4919         }
4920     }
4921 
setDoNotAskCredentialsOnBoot()4922     private void setDoNotAskCredentialsOnBoot() {
4923         synchronized (getLockObject()) {
4924             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4925             if (!policyData.doNotAskCredentialsOnBoot) {
4926                 policyData.doNotAskCredentialsOnBoot = true;
4927                 saveSettingsLocked(UserHandle.USER_SYSTEM);
4928             }
4929         }
4930     }
4931 
4932     @Override
getDoNotAskCredentialsOnBoot()4933     public boolean getDoNotAskCredentialsOnBoot() {
4934         mContext.enforceCallingOrSelfPermission(
4935                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4936         synchronized (getLockObject()) {
4937             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4938             return policyData.doNotAskCredentialsOnBoot;
4939         }
4940     }
4941 
4942     @Override
setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent)4943     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4944         if (!mHasFeature) {
4945             return;
4946         }
4947         Preconditions.checkNotNull(who, "ComponentName is null");
4948         final int userHandle = mInjector.userHandleGetCallingUserId();
4949         synchronized (getLockObject()) {
4950             ActiveAdmin ap = getActiveAdminForCallerLocked(
4951                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4952             if (ap.maximumTimeToUnlock != timeMs) {
4953                 ap.maximumTimeToUnlock = timeMs;
4954                 saveSettingsLocked(userHandle);
4955                 updateMaximumTimeToLockLocked(userHandle);
4956             }
4957         }
4958         if (SecurityLog.isLoggingEnabled()) {
4959             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
4960             SecurityLog.writeEvent(SecurityLog.TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
4961                     who.getPackageName(), userHandle, affectedUserId, timeMs);
4962         }
4963     }
4964 
updateMaximumTimeToLockLocked(@serIdInt int userId)4965     private void updateMaximumTimeToLockLocked(@UserIdInt int userId) {
4966         // Update the profile's timeout
4967         if (isManagedProfile(userId)) {
4968             updateProfileLockTimeoutLocked(userId);
4969         }
4970 
4971         final long timeMs;
4972         final long ident = mInjector.binderClearCallingIdentity();
4973         try {
4974             // Update the device timeout
4975             final int parentId = getProfileParentId(userId);
4976             timeMs = getMaximumTimeToLockPolicyFromAdmins(
4977                     getActiveAdminsForLockscreenPoliciesLocked(parentId, false));
4978 
4979             final DevicePolicyData policy = getUserDataUnchecked(parentId);
4980             if (policy.mLastMaximumTimeToLock == timeMs) {
4981                 return;
4982             }
4983             policy.mLastMaximumTimeToLock = timeMs;
4984 
4985             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4986                 // Make sure KEEP_SCREEN_ON is disabled, since that
4987                 // would allow bypassing of the maximum time to lock.
4988                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4989             }
4990         } finally {
4991             mInjector.binderRestoreCallingIdentity(ident);
4992         }
4993 
4994         mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4995                 UserHandle.USER_SYSTEM, timeMs);
4996     }
4997 
updateProfileLockTimeoutLocked(@serIdInt int userId)4998     private void updateProfileLockTimeoutLocked(@UserIdInt int userId) {
4999         final long timeMs;
5000         if (isSeparateProfileChallengeEnabled(userId)) {
5001             timeMs = getMaximumTimeToLockPolicyFromAdmins(
5002                     getActiveAdminsForLockscreenPoliciesLocked(userId, false /* parent */));
5003         } else {
5004             timeMs = Long.MAX_VALUE;
5005         }
5006 
5007         final DevicePolicyData policy = getUserDataUnchecked(userId);
5008         if (policy.mLastMaximumTimeToLock == timeMs) {
5009             return;
5010         }
5011         policy.mLastMaximumTimeToLock = timeMs;
5012 
5013         mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
5014                 userId, policy.mLastMaximumTimeToLock);
5015     }
5016 
5017     @Override
getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent)5018     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
5019         if (!mHasFeature) {
5020             return 0;
5021         }
5022         enforceFullCrossUsersPermission(userHandle);
5023         synchronized (getLockObject()) {
5024             if (who != null) {
5025                 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5026                 return admin != null ? admin.maximumTimeToUnlock : 0;
5027             }
5028             // Return the strictest policy across all participating admins.
5029             final List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
5030                     userHandle, parent);
5031             final long timeMs = getMaximumTimeToLockPolicyFromAdmins(admins);
5032             return timeMs == Long.MAX_VALUE ? 0 : timeMs;
5033         }
5034     }
5035 
getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins)5036     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
5037         long time = Long.MAX_VALUE;
5038         for (final ActiveAdmin admin : admins) {
5039             if (admin.maximumTimeToUnlock > 0 && admin.maximumTimeToUnlock < time) {
5040                 time = admin.maximumTimeToUnlock;
5041             }
5042         }
5043         return time;
5044     }
5045 
5046     @Override
setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, boolean parent)5047     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
5048             boolean parent) {
5049         if (!mHasFeature) {
5050             return;
5051         }
5052         Preconditions.checkNotNull(who, "ComponentName is null");
5053         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
5054         // timeoutMs with value 0 means that the admin doesn't participate
5055         // timeoutMs is clamped to the interval in case the internal constants change in the future
5056         final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs();
5057         if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) {
5058             timeoutMs = minimumStrongAuthTimeout;
5059         }
5060         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
5061             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5062         }
5063 
5064         final int userHandle = mInjector.userHandleGetCallingUserId();
5065         synchronized (getLockObject()) {
5066             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5067                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
5068             if (ap.strongAuthUnlockTimeout != timeoutMs) {
5069                 ap.strongAuthUnlockTimeout = timeoutMs;
5070                 saveSettingsLocked(userHandle);
5071             }
5072         }
5073     }
5074 
5075     /**
5076      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
5077      * admins if who is null.
5078      * Returns 0 if not configured for the provided admin.
5079      */
5080     @Override
getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent)5081     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
5082         if (!mHasFeature) {
5083             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5084         }
5085         enforceFullCrossUsersPermission(userId);
5086         synchronized (getLockObject()) {
5087             if (who != null) {
5088                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
5089                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
5090             }
5091 
5092             // Return the strictest policy across all participating admins.
5093             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
5094 
5095             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
5096             for (int i = 0; i < admins.size(); i++) {
5097                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
5098                 if (timeout != 0) { // take only participating admins into account
5099                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
5100                 }
5101             }
5102             return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
5103         }
5104     }
5105 
getMinimumStrongAuthTimeoutMs()5106     private long getMinimumStrongAuthTimeoutMs() {
5107         if (!mInjector.isBuildDebuggable()) {
5108             return MINIMUM_STRONG_AUTH_TIMEOUT_MS;
5109         }
5110         // ideally the property was named persist.sys.min_strong_auth_timeout, but system property
5111         // name cannot be longer than 31 characters
5112         return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo",
5113                 MINIMUM_STRONG_AUTH_TIMEOUT_MS),
5114                 MINIMUM_STRONG_AUTH_TIMEOUT_MS);
5115     }
5116 
5117     @Override
lockNow(int flags, boolean parent)5118     public void lockNow(int flags, boolean parent) {
5119         if (!mHasFeature) {
5120             return;
5121         }
5122 
5123         final int callingUserId = mInjector.userHandleGetCallingUserId();
5124         synchronized (getLockObject()) {
5125             // This API can only be called by an active device admin,
5126             // so try to retrieve it to check that the caller is one.
5127             final ActiveAdmin admin = getActiveAdminForCallerLocked(
5128                     null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
5129 
5130             final long ident = mInjector.binderClearCallingIdentity();
5131             try {
5132                 final ComponentName adminComponent = admin.info.getComponent();
5133                 // Evict key
5134                 if ((flags & DevicePolicyManager.FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY) != 0) {
5135                     enforceManagedProfile(
5136                             callingUserId, "set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5137                     if (!isProfileOwner(adminComponent, callingUserId)) {
5138                         throw new SecurityException("Only profile owner admins can set "
5139                                 + "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY");
5140                     }
5141                     if (parent) {
5142                         throw new IllegalArgumentException(
5143                                 "Cannot set FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY for the parent");
5144                     }
5145                     if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5146                         throw new UnsupportedOperationException(
5147                                 "FLAG_EVICT_CREDENTIAL_ENCRYPTION_KEY only applies to FBE devices");
5148                     }
5149                     mUserManager.evictCredentialEncryptionKey(callingUserId);
5150                 }
5151 
5152                 // Lock all users unless this is a managed profile with a separate challenge
5153                 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId)
5154                         ? UserHandle.USER_ALL : callingUserId);
5155                 mLockPatternUtils.requireStrongAuth(
5156                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
5157 
5158                 // Require authentication for the device or profile
5159                 if (userToLock == UserHandle.USER_ALL) {
5160                     // Power off the display
5161                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
5162                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
5163                     mInjector.getIWindowManager().lockNow(null);
5164                 } else {
5165                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
5166                 }
5167 
5168                 if (SecurityLog.isLoggingEnabled()) {
5169                     final int affectedUserId =
5170                             parent ? getProfileParentId(callingUserId) : callingUserId;
5171                     SecurityLog.writeEvent(SecurityLog.TAG_REMOTE_LOCK,
5172                             adminComponent.getPackageName(), callingUserId, affectedUserId);
5173                 }
5174             } catch (RemoteException e) {
5175             } finally {
5176                 mInjector.binderRestoreCallingIdentity(ident);
5177             }
5178         }
5179     }
5180 
5181     @Override
enforceCanManageCaCerts(ComponentName who, String callerPackage)5182     public void enforceCanManageCaCerts(ComponentName who, String callerPackage) {
5183         if (who == null) {
5184             if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5185                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
5186             }
5187         } else {
5188             enforceProfileOrDeviceOwner(who);
5189         }
5190     }
5191 
enforceProfileOrDeviceOwner(ComponentName who)5192     private void enforceProfileOrDeviceOwner(ComponentName who) {
5193         synchronized (getLockObject()) {
5194             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5195         }
5196     }
5197 
5198     @Override
approveCaCert(String alias, int userId, boolean approval)5199     public boolean approveCaCert(String alias, int userId, boolean approval) {
5200         enforceManageUsers();
5201         synchronized (getLockObject()) {
5202             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
5203             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
5204             if (!changed) {
5205                 return false;
5206             }
5207             saveSettingsLocked(userId);
5208         }
5209         mCertificateMonitor.onCertificateApprovalsChanged(userId);
5210         return true;
5211     }
5212 
5213     @Override
isCaCertApproved(String alias, int userId)5214     public boolean isCaCertApproved(String alias, int userId) {
5215         enforceManageUsers();
5216         synchronized (getLockObject()) {
5217             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
5218         }
5219     }
5220 
removeCaApprovalsIfNeeded(int userId)5221     private void removeCaApprovalsIfNeeded(int userId) {
5222         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
5223             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
5224             if (userInfo.isManagedProfile()){
5225                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
5226             }
5227             if (!isSecure) {
5228                 synchronized (getLockObject()) {
5229                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
5230                     saveSettingsLocked(userInfo.id);
5231                 }
5232                 mCertificateMonitor.onCertificateApprovalsChanged(userId);
5233             }
5234         }
5235     }
5236 
5237     @Override
installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)5238     public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer)
5239             throws RemoteException {
5240         if (!mHasFeature) {
5241             return false;
5242         }
5243         enforceCanManageCaCerts(admin, callerPackage);
5244 
5245         final String alias;
5246 
5247         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5248         final long id = mInjector.binderClearCallingIdentity();
5249         try {
5250             alias = mCertificateMonitor.installCaCert(userHandle, certBuffer);
5251             if (alias == null) {
5252                 Log.w(LOG_TAG, "Problem installing cert");
5253                 return false;
5254             }
5255         } finally {
5256             mInjector.binderRestoreCallingIdentity(id);
5257         }
5258 
5259         synchronized (getLockObject()) {
5260             getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias);
5261             saveSettingsLocked(userHandle.getIdentifier());
5262         }
5263         return true;
5264     }
5265 
5266     @Override
uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases)5267     public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) {
5268         if (!mHasFeature) {
5269             return;
5270         }
5271         enforceCanManageCaCerts(admin, callerPackage);
5272 
5273         final int userId = mInjector.userHandleGetCallingUserId();
5274         final long id = mInjector.binderClearCallingIdentity();
5275         try {
5276             mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases);
5277         } finally {
5278             mInjector.binderRestoreCallingIdentity(id);
5279         }
5280 
5281         synchronized (getLockObject()) {
5282             if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) {
5283                 saveSettingsLocked(userId);
5284             }
5285         }
5286     }
5287 
5288     @Override
installKeyPair(ComponentName who, String callerPackage, byte[] privKey, byte[] cert, byte[] chain, String alias, boolean requestAccess, boolean isUserSelectable)5289     public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey,
5290             byte[] cert, byte[] chain, String alias, boolean requestAccess,
5291             boolean isUserSelectable) {
5292         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5293                 DELEGATION_CERT_INSTALL);
5294 
5295 
5296         final int callingUid = mInjector.binderGetCallingUid();
5297         final long id = mInjector.binderClearCallingIdentity();
5298         try {
5299             final KeyChainConnection keyChainConnection =
5300                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
5301             try {
5302                 IKeyChainService keyChain = keyChainConnection.getService();
5303                 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
5304                     return false;
5305                 }
5306                 if (requestAccess) {
5307                     keyChain.setGrant(callingUid, alias, true);
5308                 }
5309                 keyChain.setUserSelectable(alias, isUserSelectable);
5310                 return true;
5311             } catch (RemoteException e) {
5312                 Log.e(LOG_TAG, "Installing certificate", e);
5313             } finally {
5314                 keyChainConnection.close();
5315             }
5316         } catch (InterruptedException e) {
5317             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
5318             Thread.currentThread().interrupt();
5319         } finally {
5320             mInjector.binderRestoreCallingIdentity(id);
5321         }
5322         return false;
5323     }
5324 
5325     @Override
removeKeyPair(ComponentName who, String callerPackage, String alias)5326     public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) {
5327         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5328                 DELEGATION_CERT_INSTALL);
5329 
5330         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
5331         final long id = Binder.clearCallingIdentity();
5332         try {
5333             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
5334             try {
5335                 IKeyChainService keyChain = keyChainConnection.getService();
5336                 return keyChain.removeKeyPair(alias);
5337             } catch (RemoteException e) {
5338                 Log.e(LOG_TAG, "Removing keypair", e);
5339             } finally {
5340                 keyChainConnection.close();
5341             }
5342         } catch (InterruptedException e) {
5343             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
5344             Thread.currentThread().interrupt();
5345         } finally {
5346             Binder.restoreCallingIdentity(id);
5347         }
5348         return false;
5349     }
5350 
enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner( ComponentName who, String callerPackage, int callerUid)5351     private void enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(
5352             ComponentName who, String callerPackage, int callerUid) throws SecurityException {
5353         if (who == null) {
5354             if (!mOwners.hasDeviceOwner()) {
5355                 throw new SecurityException("Not in Device Owner mode.");
5356             }
5357             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
5358                 throw new SecurityException("Caller not from device owner user");
5359             }
5360             if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) {
5361                 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() +
5362                         "has no permission to generate keys.");
5363             }
5364         } else {
5365             // Caller provided - check it is the device owner.
5366             synchronized (getLockObject()) {
5367                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5368             }
5369         }
5370     }
5371 
5372     @VisibleForTesting
translateIdAttestationFlags( int idAttestationFlags)5373     public static int[] translateIdAttestationFlags(
5374             int idAttestationFlags) {
5375         Map<Integer, Integer> idTypeToAttestationFlag = new HashMap();
5376         idTypeToAttestationFlag.put(ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_SERIAL);
5377         idTypeToAttestationFlag.put(ID_TYPE_IMEI, AttestationUtils.ID_TYPE_IMEI);
5378         idTypeToAttestationFlag.put(ID_TYPE_MEID, AttestationUtils.ID_TYPE_MEID);
5379 
5380         int numFlagsSet = Integer.bitCount(idAttestationFlags);
5381         // No flags are set - return null to indicate no device ID attestation information should
5382         // be included in the attestation record.
5383         if (numFlagsSet == 0) {
5384             return null;
5385         }
5386 
5387         // If the ID_TYPE_BASE_INFO is set, make sure that a non-null array is returned, even if
5388         // no other flag is set. That will lead to inclusion of general device make data in the
5389         // attestation record, but no specific device identifiers.
5390         if ((idAttestationFlags & ID_TYPE_BASE_INFO) != 0) {
5391             numFlagsSet -= 1;
5392             idAttestationFlags = idAttestationFlags & (~ID_TYPE_BASE_INFO);
5393         }
5394 
5395         int[] attestationUtilsFlags = new int[numFlagsSet];
5396         int i = 0;
5397         for (Integer idType: idTypeToAttestationFlag.keySet()) {
5398             if ((idType & idAttestationFlags) != 0) {
5399                 attestationUtilsFlags[i++] = idTypeToAttestationFlag.get(idType);
5400             }
5401         }
5402 
5403         return attestationUtilsFlags;
5404     }
5405 
5406     @Override
generateKeyPair(ComponentName who, String callerPackage, String algorithm, ParcelableKeyGenParameterSpec parcelableKeySpec, int idAttestationFlags, KeymasterCertificateChain attestationChain)5407     public boolean generateKeyPair(ComponentName who, String callerPackage, String algorithm,
5408             ParcelableKeyGenParameterSpec parcelableKeySpec,
5409             int idAttestationFlags,
5410             KeymasterCertificateChain attestationChain) {
5411         // Get attestation flags, if any.
5412         final int[] attestationUtilsFlags = translateIdAttestationFlags(idAttestationFlags);
5413         final boolean deviceIdAttestationRequired = attestationUtilsFlags != null;
5414         final int callingUid = mInjector.binderGetCallingUid();
5415 
5416         if (deviceIdAttestationRequired && attestationUtilsFlags.length > 0) {
5417             enforceIsDeviceOwnerOrCertInstallerOfDeviceOwner(who, callerPackage, callingUid);
5418         } else {
5419             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5420                     DELEGATION_CERT_INSTALL);
5421         }
5422         final KeyGenParameterSpec keySpec = parcelableKeySpec.getSpec();
5423         final String alias = keySpec.getKeystoreAlias();
5424         if (TextUtils.isEmpty(alias)) {
5425             throw new IllegalArgumentException("Empty alias provided.");
5426         }
5427         // As the caller will be granted access to the key, ensure no UID was specified, as
5428         // it will not have the desired effect.
5429         if (keySpec.getUid() != KeyStore.UID_SELF) {
5430             Log.e(LOG_TAG, "Only the caller can be granted access to the generated keypair.");
5431             return false;
5432         }
5433 
5434         if (deviceIdAttestationRequired && (keySpec.getAttestationChallenge() == null)) {
5435             throw new IllegalArgumentException(
5436                     "Requested Device ID attestation but challenge is empty.");
5437         }
5438 
5439         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
5440         final long id = mInjector.binderClearCallingIdentity();
5441         try {
5442             try (KeyChainConnection keyChainConnection =
5443                     KeyChain.bindAsUser(mContext, userHandle)) {
5444                 IKeyChainService keyChain = keyChainConnection.getService();
5445 
5446                 // Copy the provided keySpec, excluding the attestation challenge, which will be
5447                 // used later for requesting key attestation record.
5448                 final KeyGenParameterSpec noAttestationSpec =
5449                     new KeyGenParameterSpec.Builder(keySpec)
5450                         .setAttestationChallenge(null)
5451                         .build();
5452 
5453                 final int generationResult = keyChain.generateKeyPair(algorithm,
5454                     new ParcelableKeyGenParameterSpec(noAttestationSpec));
5455                 if (generationResult != KeyChain.KEY_GEN_SUCCESS) {
5456                     Log.e(LOG_TAG, String.format(
5457                             "KeyChain failed to generate a keypair, error %d.", generationResult));
5458                     return false;
5459                 }
5460 
5461                 // Set a grant for the caller here so that when the client calls
5462                 // requestPrivateKey, it will be able to get the key from Keystore.
5463                 // Note the use of the calling  UID, since the request for the private
5464                 // key will come from the client's process, so the grant has to be for
5465                 // that UID.
5466                 keyChain.setGrant(callingUid, alias, true);
5467 
5468                 final byte[] attestationChallenge = keySpec.getAttestationChallenge();
5469                 if (attestationChallenge != null) {
5470                     final int attestationResult = keyChain.attestKey(
5471                             alias, attestationChallenge, attestationUtilsFlags, attestationChain);
5472                     if (attestationResult != KeyChain.KEY_ATTESTATION_SUCCESS) {
5473                         Log.e(LOG_TAG, String.format(
5474                                 "Attestation for %s failed (rc=%d), deleting key.",
5475                                 alias, attestationResult));
5476                         keyChain.removeKeyPair(alias);
5477                         if (attestationResult == KeyChain.KEY_ATTESTATION_CANNOT_ATTEST_IDS) {
5478                             throw new UnsupportedOperationException(
5479                                     "Device does not support Device ID attestation.");
5480                         }
5481                         return false;
5482                     }
5483                 }
5484                 return true;
5485             }
5486         } catch (RemoteException e) {
5487             Log.e(LOG_TAG, "KeyChain error while generating a keypair", e);
5488         } catch (InterruptedException e) {
5489             Log.w(LOG_TAG, "Interrupted while generating keypair", e);
5490             Thread.currentThread().interrupt();
5491         } finally {
5492             mInjector.binderRestoreCallingIdentity(id);
5493         }
5494         return false;
5495     }
5496 
5497     @Override
setKeyPairCertificate(ComponentName who, String callerPackage, String alias, byte[] cert, byte[] chain, boolean isUserSelectable)5498     public boolean setKeyPairCertificate(ComponentName who, String callerPackage, String alias,
5499             byte[] cert, byte[] chain, boolean isUserSelectable) {
5500         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
5501                 DELEGATION_CERT_INSTALL);
5502 
5503         final int callingUid = mInjector.binderGetCallingUid();
5504         final long id = mInjector.binderClearCallingIdentity();
5505         try (final KeyChainConnection keyChainConnection =
5506                 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid))) {
5507             IKeyChainService keyChain = keyChainConnection.getService();
5508             if (!keyChain.setKeyPairCertificate(alias, cert, chain)) {
5509                 return false;
5510             }
5511             keyChain.setUserSelectable(alias, isUserSelectable);
5512             return true;
5513         } catch (InterruptedException e) {
5514             Log.w(LOG_TAG, "Interrupted while setting keypair certificate", e);
5515             Thread.currentThread().interrupt();
5516         } catch (RemoteException e) {
5517             Log.e(LOG_TAG, "Failed setting keypair certificate", e);
5518         } finally {
5519             mInjector.binderRestoreCallingIdentity(id);
5520         }
5521         return false;
5522     }
5523 
5524     @Override
choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, final IBinder response)5525     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
5526             final IBinder response) {
5527         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
5528         if (!isCallerWithSystemUid()) {
5529             return;
5530         }
5531 
5532         final UserHandle caller = mInjector.binderGetCallingUserHandle();
5533         // If there is a profile owner, redirect to that; otherwise query the device owner.
5534         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
5535         if (aliasChooser == null && caller.isSystem()) {
5536             synchronized (getLockObject()) {
5537                 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
5538                 if (deviceOwnerAdmin != null) {
5539                     aliasChooser = deviceOwnerAdmin.info.getComponent();
5540                 }
5541             }
5542         }
5543         if (aliasChooser == null) {
5544             sendPrivateKeyAliasResponse(null, response);
5545             return;
5546         }
5547 
5548         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
5549         intent.setComponent(aliasChooser);
5550         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
5551         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
5552         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
5553         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
5554         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
5555 
5556         final long id = mInjector.binderClearCallingIdentity();
5557         try {
5558             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
5559                 @Override
5560                 public void onReceive(Context context, Intent intent) {
5561                     final String chosenAlias = getResultData();
5562                     sendPrivateKeyAliasResponse(chosenAlias, response);
5563                 }
5564             }, null, Activity.RESULT_OK, null, null);
5565         } finally {
5566             mInjector.binderRestoreCallingIdentity(id);
5567         }
5568     }
5569 
sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder)5570     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
5571         final IKeyChainAliasCallback keyChainAliasResponse =
5572                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
5573         // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback
5574         // is oneway, which means it won't block if the recipient lives in another process.
5575         try {
5576             keyChainAliasResponse.alias(alias);
5577         } catch (Exception e) {
5578             // Caller could throw RuntimeException or RemoteException back across processes. Catch
5579             // everything just to be sure.
5580             Log.e(LOG_TAG, "error while responding to callback", e);
5581         }
5582     }
5583 
5584     /**
5585      * Determine whether DPMS should check if a delegate package is already installed before
5586      * granting it new delegations via {@link #setDelegatedScopes}.
5587      */
shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, int targetSdk, List<String> scopes)5588     private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage,
5589             int targetSdk, List<String> scopes) {
5590         // 1) Never skip is installed check from N.
5591         if (targetSdk >= Build.VERSION_CODES.N) {
5592             return true;
5593         }
5594         // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given.
5595         if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) {
5596             return false;
5597         }
5598         // 3) Skip if all previously granted scopes are being cleared.
5599         if (scopes.isEmpty()) {
5600             return false;
5601         }
5602         // Otherwise it should check that delegatePackage is installed.
5603         return true;
5604     }
5605 
5606     /**
5607      * Set the scopes of a device owner or profile owner delegate.
5608      *
5609      * @param who the device owner or profile owner.
5610      * @param delegatePackage the name of the delegate package.
5611      * @param scopes the list of delegation scopes to be given to the delegate package.
5612      */
5613     @Override
setDelegatedScopes(ComponentName who, String delegatePackage, List<String> scopes)5614     public void setDelegatedScopes(ComponentName who, String delegatePackage,
5615             List<String> scopes) throws SecurityException {
5616         Preconditions.checkNotNull(who, "ComponentName is null");
5617         Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty");
5618         Preconditions.checkCollectionElementsNotNull(scopes, "Scopes");
5619         // Remove possible duplicates.
5620         scopes = new ArrayList(new ArraySet(scopes));
5621         // Ensure given scopes are valid.
5622         if (scopes.retainAll(Arrays.asList(DELEGATIONS))) {
5623             throw new IllegalArgumentException("Unexpected delegation scopes");
5624         }
5625 
5626         // Retrieve the user ID of the calling process.
5627         final int userId = mInjector.userHandleGetCallingUserId();
5628         synchronized (getLockObject()) {
5629             // Ensure calling process is device/profile owner.
5630             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5631             // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N).
5632             if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage,
5633                         getTargetSdk(who.getPackageName(), userId), scopes)) {
5634                 // Throw when the delegate package is not installed.
5635                 if (!isPackageInstalledForUser(delegatePackage, userId)) {
5636                     throw new IllegalArgumentException("Package " + delegatePackage
5637                             + " is not installed on the current user");
5638                 }
5639             }
5640 
5641             // Set the new delegate in user policies.
5642             final DevicePolicyData policy = getUserData(userId);
5643             if (!scopes.isEmpty()) {
5644                 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes));
5645             } else {
5646                 // Remove any delegation info if the given scopes list is empty.
5647                 policy.mDelegationMap.remove(delegatePackage);
5648             }
5649 
5650             // Notify delegate package of updates.
5651             final Intent intent = new Intent(
5652                     DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED);
5653             // Only call receivers registered with Context#registerReceiver (don’t wake delegate).
5654             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
5655             // Limit components this intent resolves to to the delegate package.
5656             intent.setPackage(delegatePackage);
5657             // Include the list of delegated scopes as an extra.
5658             intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES,
5659                     (ArrayList<String>) scopes);
5660             // Send the broadcast.
5661             mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
5662 
5663             // Persist updates.
5664             saveSettingsLocked(userId);
5665         }
5666     }
5667 
5668     /**
5669      * Get the delegation scopes given to a delegate package by a device owner or profile owner.
5670      *
5671      * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by
5672      * passing in {@code null} as the {@code who} parameter and its own name as the
5673      * {@code delegatepackage}.
5674      *
5675      * @param who the device owner or profile owner, or {@code null} if the caller is
5676      *            {@code delegatePackage}.
5677      * @param delegatePackage the name of the delegate package whose scopes are to be retrieved.
5678      * @return a list of the delegation scopes currently given to {@code delegatePackage}.
5679      */
5680     @Override
5681     @NonNull
getDelegatedScopes(ComponentName who, String delegatePackage)5682     public List<String> getDelegatedScopes(ComponentName who,
5683             String delegatePackage) throws SecurityException {
5684         Preconditions.checkNotNull(delegatePackage, "Delegate package is null");
5685 
5686         // Retrieve the user ID of the calling process.
5687         final int callingUid = mInjector.binderGetCallingUid();
5688         final int userId = UserHandle.getUserId(callingUid);
5689         synchronized (getLockObject()) {
5690             // Ensure calling process is device/profile owner.
5691             if (who != null) {
5692                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5693             // Or ensure calling process is delegatePackage itself.
5694             } else {
5695                 int uid = 0;
5696                 try {
5697                   uid = mInjector.getPackageManager()
5698                           .getPackageUidAsUser(delegatePackage, userId);
5699                 } catch(NameNotFoundException e) {
5700                 }
5701                 if (uid != callingUid) {
5702                     throw new SecurityException("Caller with uid " + callingUid + " is not "
5703                             + delegatePackage);
5704                 }
5705             }
5706             final DevicePolicyData policy = getUserData(userId);
5707             // Retrieve the scopes assigned to delegatePackage, or null if no scope was given.
5708             final List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5709             return scopes == null ? Collections.EMPTY_LIST : scopes;
5710         }
5711     }
5712 
5713     /**
5714      * Get a list of  packages that were given a specific delegation scopes by a device owner or
5715      * profile owner.
5716      *
5717      * @param who the device owner or profile owner.
5718      * @param scope the scope whose delegates are to be retrieved.
5719      * @return a list of the delegate packages currently given the {@code scope} delegation.
5720      */
5721     @NonNull
getDelegatePackages(ComponentName who, String scope)5722     public List<String> getDelegatePackages(ComponentName who, String scope)
5723             throws SecurityException {
5724         Preconditions.checkNotNull(who, "ComponentName is null");
5725         Preconditions.checkNotNull(scope, "Scope is null");
5726         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5727             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5728         }
5729 
5730         // Retrieve the user ID of the calling process.
5731         final int userId = mInjector.userHandleGetCallingUserId();
5732         synchronized (getLockObject()) {
5733             // Ensure calling process is device/profile owner.
5734             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5735             final DevicePolicyData policy = getUserData(userId);
5736 
5737             // Create a list to hold the resulting delegate packages.
5738             final List<String> delegatePackagesWithScope = new ArrayList<>();
5739             // Add all delegations containing scope to the result list.
5740             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5741                 if (policy.mDelegationMap.valueAt(i).contains(scope)) {
5742                     delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i));
5743                 }
5744             }
5745             return delegatePackagesWithScope;
5746         }
5747     }
5748 
5749     /**
5750      * Check whether a caller application has been delegated a given scope via
5751      * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or
5752      * device owner.
5753      * <p>
5754      * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and
5755      * then comparing the calling UID with the UID of {@code callerPackage} as reported by
5756      * {@link PackageManager#getPackageUidAsUser}.
5757      *
5758      * @param callerPackage the name of the package that is trying to invoke a function in the DPMS.
5759      * @param scope the delegation scope to be checked.
5760      * @return {@code true} if the calling process is a delegate of {@code scope}.
5761      */
isCallerDelegate(String callerPackage, String scope)5762     private boolean isCallerDelegate(String callerPackage, String scope) {
5763         Preconditions.checkNotNull(callerPackage, "callerPackage is null");
5764         if (!Arrays.asList(DELEGATIONS).contains(scope)) {
5765             throw new IllegalArgumentException("Unexpected delegation scope: " + scope);
5766         }
5767 
5768         // Retrieve the UID and user ID of the calling process.
5769         final int callingUid = mInjector.binderGetCallingUid();
5770         final int userId = UserHandle.getUserId(callingUid);
5771         synchronized (getLockObject()) {
5772             // Retrieve user policy data.
5773             final DevicePolicyData policy = getUserData(userId);
5774             // Retrieve the list of delegation scopes granted to callerPackage.
5775             final List<String> scopes = policy.mDelegationMap.get(callerPackage);
5776             // Check callingUid only if callerPackage has the required scope delegation.
5777             if (scopes != null && scopes.contains(scope)) {
5778                 try {
5779                     // Retrieve the expected UID for callerPackage.
5780                     final int uid = mInjector.getPackageManager()
5781                             .getPackageUidAsUser(callerPackage, userId);
5782                     // Return true if the caller is actually callerPackage.
5783                     return uid == callingUid;
5784                 } catch (NameNotFoundException e) {
5785                     // Ignore.
5786                 }
5787             }
5788             return false;
5789         }
5790     }
5791 
5792     /**
5793      * Throw a security exception if a ComponentName is given and it is not a device/profile owner
5794      * or if the calling process is not a delegate of the given scope.
5795      *
5796      * @param who the device owner of profile owner, or null if {@code callerPackage} is a
5797      *            {@code scope} delegate.
5798      * @param callerPackage the name of the calling package. Required if {@code who} is
5799      *            {@code null}.
5800      * @param reqPolicy the policy used in the API whose access permission is being checked.
5801      * @param scope the delegation scope corresponding to the API being checked.
5802      * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy};
5803      *            or when {@code who} is {@code null} and {@code callerPackage} is not a delegate
5804      *            of {@code scope}.
5805      */
enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, String scope)5806     private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy,
5807             String scope) {
5808         // If a ComponentName is given ensure it is a device or profile owner according to policy.
5809         if (who != null) {
5810             synchronized (getLockObject()) {
5811                 getActiveAdminForCallerLocked(who, reqPolicy);
5812             }
5813         // If no ComponentName is given ensure calling process has scope delegation.
5814         } else if (!isCallerDelegate(callerPackage, scope)) {
5815             throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid()
5816                     + " is not a delegate of scope " + scope + ".");
5817         }
5818     }
5819 
5820     /**
5821      * Helper function to preserve delegation behavior pre-O when using the deprecated functions
5822      * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}.
5823      */
setDelegatedScopePreO(ComponentName who, String delegatePackage, String scope)5824     private void setDelegatedScopePreO(ComponentName who,
5825             String delegatePackage, String scope) {
5826         Preconditions.checkNotNull(who, "ComponentName is null");
5827 
5828         final int userId = mInjector.userHandleGetCallingUserId();
5829         synchronized (getLockObject()) {
5830             // Ensure calling process is device/profile owner.
5831             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5832             final DevicePolicyData policy = getUserData(userId);
5833 
5834             if (delegatePackage != null) {
5835                 // Set package as a delegate for scope if it is not already one.
5836                 List<String> scopes = policy.mDelegationMap.get(delegatePackage);
5837                 if (scopes == null) {
5838                     scopes = new ArrayList<>();
5839                 }
5840                 if (!scopes.contains(scope)) {
5841                     scopes.add(scope);
5842                     setDelegatedScopes(who, delegatePackage, scopes);
5843                 }
5844             }
5845 
5846             // Clear any existing scope delegates.
5847             for (int i = 0; i < policy.mDelegationMap.size(); i++) {
5848                 final String currentPackage = policy.mDelegationMap.keyAt(i);
5849                 final List<String> currentScopes = policy.mDelegationMap.valueAt(i);
5850 
5851                 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) {
5852                     final List<String> newScopes = new ArrayList(currentScopes);
5853                     newScopes.remove(scope);
5854                     setDelegatedScopes(who, currentPackage, newScopes);
5855                 }
5856             }
5857         }
5858     }
5859 
5860     @Override
setCertInstallerPackage(ComponentName who, String installerPackage)5861     public void setCertInstallerPackage(ComponentName who, String installerPackage)
5862             throws SecurityException {
5863         setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL);
5864     }
5865 
5866     @Override
getCertInstallerPackage(ComponentName who)5867     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
5868         final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL);
5869         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
5870     }
5871 
5872     /**
5873      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
5874      * not installed and therefore not available.
5875      *
5876      * @throws SecurityException if the caller is not a profile or device owner.
5877      * @throws UnsupportedOperationException if the package does not support being set as always-on.
5878      */
5879     @Override
setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)5880     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
5881             throws SecurityException {
5882         enforceProfileOrDeviceOwner(admin);
5883 
5884         final int userId = mInjector.userHandleGetCallingUserId();
5885         final long token = mInjector.binderClearCallingIdentity();
5886         try {
5887             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
5888                 return false;
5889             }
5890             ConnectivityManager connectivityManager = (ConnectivityManager)
5891                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5892             if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
5893                 throw new UnsupportedOperationException();
5894             }
5895         } finally {
5896             mInjector.binderRestoreCallingIdentity(token);
5897         }
5898         return true;
5899     }
5900 
5901     @Override
getAlwaysOnVpnPackage(ComponentName admin)5902     public String getAlwaysOnVpnPackage(ComponentName admin)
5903             throws SecurityException {
5904         enforceProfileOrDeviceOwner(admin);
5905 
5906         final int userId = mInjector.userHandleGetCallingUserId();
5907         final long token = mInjector.binderClearCallingIdentity();
5908         try{
5909             ConnectivityManager connectivityManager = (ConnectivityManager)
5910                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5911             return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
5912         } finally {
5913             mInjector.binderRestoreCallingIdentity(token);
5914         }
5915     }
5916 
forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc)5917     private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason, boolean wipeEuicc) {
5918         wtfIfInLock();
5919         boolean success = false;
5920         try {
5921             if (wipeExtRequested) {
5922                 StorageManager sm = (StorageManager) mContext.getSystemService(
5923                     Context.STORAGE_SERVICE);
5924                 sm.wipeAdoptableDisks();
5925             }
5926             mInjector.recoverySystemRebootWipeUserData(
5927                 /*shutdown=*/ false, reason, /*force=*/ true, /*wipeEuicc=*/ wipeEuicc);
5928             success = true;
5929         } catch (IOException | SecurityException e) {
5930             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
5931         } finally {
5932             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
5933         }
5934     }
5935 
forceWipeUser(int userId, String wipeReasonForUser)5936     private void forceWipeUser(int userId, String wipeReasonForUser) {
5937         boolean success = false;
5938         try {
5939             IActivityManager am = mInjector.getIActivityManager();
5940             if (am.getCurrentUser().id == userId) {
5941                 am.switchUser(UserHandle.USER_SYSTEM);
5942             }
5943 
5944             success = mUserManagerInternal.removeUserEvenWhenDisallowed(userId);
5945             if (!success) {
5946                 Slog.w(LOG_TAG, "Couldn't remove user " + userId);
5947             } else if (isManagedProfile(userId)) {
5948                 sendWipeProfileNotification(wipeReasonForUser);
5949             }
5950         } catch (RemoteException re) {
5951             // Shouldn't happen
5952         } finally {
5953             if (!success) SecurityLog.writeEvent(SecurityLog.TAG_WIPE_FAILURE);
5954         }
5955     }
5956 
5957     @Override
wipeDataWithReason(int flags, String wipeReasonForUser)5958     public void wipeDataWithReason(int flags, String wipeReasonForUser) {
5959         if (!mHasFeature) {
5960             return;
5961         }
5962         Preconditions.checkStringNotEmpty(wipeReasonForUser, "wipeReasonForUser is null or empty");
5963         enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId());
5964 
5965         final ActiveAdmin admin;
5966         synchronized (getLockObject()) {
5967             admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA);
5968         }
5969         String internalReason = "DevicePolicyManager.wipeDataWithReason() from "
5970                 + admin.info.getComponent().flattenToShortString();
5971         wipeDataNoLock(
5972                 admin.info.getComponent(), flags, internalReason, wipeReasonForUser,
5973                 admin.getUserHandle().getIdentifier());
5974     }
5975 
wipeDataNoLock(ComponentName admin, int flags, String internalReason, String wipeReasonForUser, int userId)5976     private void wipeDataNoLock(ComponentName admin, int flags, String internalReason,
5977                                 String wipeReasonForUser, int userId) {
5978         wtfIfInLock();
5979 
5980         long ident = mInjector.binderClearCallingIdentity();
5981         try {
5982             // First check whether the admin is allowed to wipe the device/user/profile.
5983             final String restriction;
5984             if (userId == UserHandle.USER_SYSTEM) {
5985                 restriction = UserManager.DISALLOW_FACTORY_RESET;
5986             } else if (isManagedProfile(userId)) {
5987                 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
5988             } else {
5989                 restriction = UserManager.DISALLOW_REMOVE_USER;
5990             }
5991             if (isAdminAffectedByRestriction(admin, restriction, userId)) {
5992                 throw new SecurityException("Cannot wipe data. " + restriction
5993                         + " restriction is set for user " + userId);
5994             }
5995 
5996             if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
5997                 if (!isDeviceOwner(admin, userId)) {
5998                     throw new SecurityException(
5999                             "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
6000                 }
6001                 PersistentDataBlockManager manager = (PersistentDataBlockManager)
6002                         mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
6003                 if (manager != null) {
6004                     manager.wipe();
6005                 }
6006             }
6007 
6008             // TODO If split user is enabled and the device owner is set in the primary user
6009             // (rather than system), we should probably trigger factory reset. Current code just
6010             // removes that user (but still clears FRP...)
6011             if (userId == UserHandle.USER_SYSTEM) {
6012                 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (
6013                         flags & WIPE_EXTERNAL_STORAGE) != 0,
6014                         internalReason,
6015                         /*wipeEuicc=*/ (flags & WIPE_EUICC) != 0);
6016             } else {
6017                 forceWipeUser(userId, wipeReasonForUser);
6018             }
6019         } finally {
6020             mInjector.binderRestoreCallingIdentity(ident);
6021         }
6022     }
6023 
sendWipeProfileNotification(String wipeReasonForUser)6024     private void sendWipeProfileNotification(String wipeReasonForUser) {
6025         Notification notification =
6026                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
6027                         .setSmallIcon(android.R.drawable.stat_sys_warning)
6028                         .setContentTitle(mContext.getString(R.string.work_profile_deleted))
6029                         .setContentText(wipeReasonForUser)
6030                         .setColor(mContext.getColor(R.color.system_notification_accent_color))
6031                         .setStyle(new Notification.BigTextStyle().bigText(wipeReasonForUser))
6032                         .build();
6033         mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification);
6034     }
6035 
clearWipeProfileNotification()6036     private void clearWipeProfileNotification() {
6037         mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED);
6038     }
6039 
6040     @Override
getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle)6041     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
6042         if (!mHasFeature) {
6043             return;
6044         }
6045         enforceFullCrossUsersPermission(userHandle);
6046         mContext.enforceCallingOrSelfPermission(
6047                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6048 
6049         synchronized (getLockObject()) {
6050             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
6051             if (admin == null) {
6052                 result.sendResult(null);
6053                 return;
6054             }
6055             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
6056             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
6057             intent.setComponent(admin.info.getComponent());
6058             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
6059                     null, new BroadcastReceiver() {
6060                 @Override
6061                 public void onReceive(Context context, Intent intent) {
6062                     result.sendResult(getResultExtras(false));
6063                 }
6064             }, null, Activity.RESULT_OK, null, null);
6065         }
6066     }
6067 
6068     /**
6069      * Notify DPMS regarding the metric of the current password. This happens when the user changes
6070      * the password, but also when the user just unlocks the keyguard. In comparison,
6071      * reportPasswordChanged() is only called when the user changes the password.
6072      */
6073     @Override
setActivePasswordState(PasswordMetrics metrics, int userHandle)6074     public void setActivePasswordState(PasswordMetrics metrics, int userHandle) {
6075         if (!mHasFeature) {
6076             return;
6077         }
6078         enforceFullCrossUsersPermission(userHandle);
6079         mContext.enforceCallingOrSelfPermission(
6080                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6081 
6082         // If the managed profile doesn't have a separate password, set the metrics to default
6083         if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
6084             metrics = new PasswordMetrics();
6085         }
6086 
6087         validateQualityConstant(metrics.quality);
6088         synchronized (getLockObject()) {
6089             mUserPasswordMetrics.put(userHandle, metrics);
6090         }
6091     }
6092 
6093     @Override
reportPasswordChanged(@serIdInt int userId)6094     public void reportPasswordChanged(@UserIdInt int userId) {
6095         if (!mHasFeature) {
6096             return;
6097         }
6098         enforceFullCrossUsersPermission(userId);
6099 
6100         // Managed Profile password can only be changed when it has a separate challenge.
6101         if (!isSeparateProfileChallengeEnabled(userId)) {
6102             enforceNotManagedProfile(userId, "set the active password");
6103         }
6104 
6105         mContext.enforceCallingOrSelfPermission(
6106                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6107 
6108         DevicePolicyData policy = getUserData(userId);
6109 
6110         long ident = mInjector.binderClearCallingIdentity();
6111         try {
6112             synchronized (getLockObject()) {
6113                 policy.mFailedPasswordAttempts = 0;
6114                 updatePasswordValidityCheckpointLocked(userId, /* parent */ false);
6115                 saveSettingsLocked(userId);
6116                 updatePasswordExpirationsLocked(userId);
6117                 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
6118 
6119                 // Send a broadcast to each profile using this password as its primary unlock.
6120                 sendAdminCommandForLockscreenPoliciesLocked(
6121                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
6122                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
6123             }
6124             removeCaApprovalsIfNeeded(userId);
6125         } finally {
6126             mInjector.binderRestoreCallingIdentity(ident);
6127         }
6128     }
6129 
6130     /**
6131      * Called any time the device password is updated. Resets all password expiration clocks.
6132      */
updatePasswordExpirationsLocked(int userHandle)6133     private void updatePasswordExpirationsLocked(int userHandle) {
6134         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
6135         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
6136                 userHandle, /* parent */ false);
6137         final int N = admins.size();
6138         for (int i = 0; i < N; i++) {
6139             ActiveAdmin admin = admins.get(i);
6140             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
6141                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
6142                 long timeout = admin.passwordExpirationTimeout;
6143                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
6144                 admin.passwordExpirationDate = expiration;
6145             }
6146         }
6147         for (int affectedUserId : affectedUserIds) {
6148             saveSettingsLocked(affectedUserId);
6149         }
6150     }
6151 
6152     @Override
reportFailedPasswordAttempt(int userHandle)6153     public void reportFailedPasswordAttempt(int userHandle) {
6154         enforceFullCrossUsersPermission(userHandle);
6155         if (!isSeparateProfileChallengeEnabled(userHandle)) {
6156             enforceNotManagedProfile(userHandle,
6157                     "report failed password attempt if separate profile challenge is not in place");
6158         }
6159         mContext.enforceCallingOrSelfPermission(
6160                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6161 
6162         boolean wipeData = false;
6163         ActiveAdmin strictestAdmin = null;
6164         final long ident = mInjector.binderClearCallingIdentity();
6165         try {
6166             synchronized (getLockObject()) {
6167                 DevicePolicyData policy = getUserData(userHandle);
6168                 policy.mFailedPasswordAttempts++;
6169                 saveSettingsLocked(userHandle);
6170                 if (mHasFeature) {
6171                     strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
6172                             userHandle, /* parent */ false);
6173                     int max = strictestAdmin != null
6174                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
6175                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
6176                         wipeData = true;
6177                     }
6178 
6179                     sendAdminCommandForLockscreenPoliciesLocked(
6180                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
6181                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6182                 }
6183             }
6184         } finally {
6185             mInjector.binderRestoreCallingIdentity(ident);
6186         }
6187 
6188         if (wipeData && strictestAdmin != null) {
6189             final int userId = strictestAdmin.getUserHandle().getIdentifier();
6190             Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: "
6191                     + strictestAdmin.info.getComponent().flattenToShortString()
6192                     + ". Calling wipeData for user " + userId);
6193 
6194             // Attempt to wipe the device/user/profile associated with the admin, as if the
6195             // admin had called wipeData(). That way we can check whether the admin is actually
6196             // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the
6197             // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be
6198             // able to do so).
6199             // IMPORTANT: Call without holding the lock to prevent deadlock.
6200             try {
6201                 String wipeReasonForUser = mContext.getString(
6202                         R.string.work_profile_deleted_reason_maximum_password_failure);
6203                 wipeDataNoLock(strictestAdmin.info.getComponent(),
6204                         /*flags=*/ 0,
6205                         /*reason=*/ "reportFailedPasswordAttempt()",
6206                         wipeReasonForUser,
6207                         userId);
6208             } catch (SecurityException e) {
6209                 Slog.w(LOG_TAG, "Failed to wipe user " + userId
6210                         + " after max failed password attempts reached.", e);
6211             }
6212         }
6213 
6214         if (mInjector.securityLogIsLoggingEnabled()) {
6215             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
6216                     /*result*/ 0, /*method strength*/ 1);
6217         }
6218     }
6219 
6220     @Override
reportSuccessfulPasswordAttempt(int userHandle)6221     public void reportSuccessfulPasswordAttempt(int userHandle) {
6222         enforceFullCrossUsersPermission(userHandle);
6223         mContext.enforceCallingOrSelfPermission(
6224                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6225 
6226         synchronized (getLockObject()) {
6227             DevicePolicyData policy = getUserData(userHandle);
6228             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
6229                 long ident = mInjector.binderClearCallingIdentity();
6230                 try {
6231                     policy.mFailedPasswordAttempts = 0;
6232                     policy.mPasswordOwner = -1;
6233                     saveSettingsLocked(userHandle);
6234                     if (mHasFeature) {
6235                         sendAdminCommandForLockscreenPoliciesLocked(
6236                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
6237                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
6238                     }
6239                 } finally {
6240                     mInjector.binderRestoreCallingIdentity(ident);
6241                 }
6242             }
6243         }
6244 
6245         if (mInjector.securityLogIsLoggingEnabled()) {
6246             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6247                     /*method strength*/ 1);
6248         }
6249     }
6250 
6251     @Override
reportFailedFingerprintAttempt(int userHandle)6252     public void reportFailedFingerprintAttempt(int userHandle) {
6253         enforceFullCrossUsersPermission(userHandle);
6254         mContext.enforceCallingOrSelfPermission(
6255                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6256         if (mInjector.securityLogIsLoggingEnabled()) {
6257             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
6258                     /*method strength*/ 0);
6259         }
6260     }
6261 
6262     @Override
reportSuccessfulFingerprintAttempt(int userHandle)6263     public void reportSuccessfulFingerprintAttempt(int userHandle) {
6264         enforceFullCrossUsersPermission(userHandle);
6265         mContext.enforceCallingOrSelfPermission(
6266                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6267         if (mInjector.securityLogIsLoggingEnabled()) {
6268             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
6269                     /*method strength*/ 0);
6270         }
6271     }
6272 
6273     @Override
reportKeyguardDismissed(int userHandle)6274     public void reportKeyguardDismissed(int userHandle) {
6275         enforceFullCrossUsersPermission(userHandle);
6276         mContext.enforceCallingOrSelfPermission(
6277                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6278 
6279         if (mInjector.securityLogIsLoggingEnabled()) {
6280             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
6281         }
6282     }
6283 
6284     @Override
reportKeyguardSecured(int userHandle)6285     public void reportKeyguardSecured(int userHandle) {
6286         enforceFullCrossUsersPermission(userHandle);
6287         mContext.enforceCallingOrSelfPermission(
6288                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
6289 
6290         if (mInjector.securityLogIsLoggingEnabled()) {
6291             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
6292         }
6293     }
6294 
6295     @Override
setGlobalProxy(ComponentName who, String proxySpec, String exclusionList)6296     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
6297             String exclusionList) {
6298         if (!mHasFeature) {
6299             return null;
6300         }
6301         synchronized (getLockObject()) {
6302             Preconditions.checkNotNull(who, "ComponentName is null");
6303 
6304             // Only check if system user has set global proxy. We don't allow other users to set it.
6305             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6306             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6307                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
6308 
6309             // Scan through active admins and find if anyone has already
6310             // set the global proxy.
6311             Set<ComponentName> compSet = policy.mAdminMap.keySet();
6312             for (ComponentName component : compSet) {
6313                 ActiveAdmin ap = policy.mAdminMap.get(component);
6314                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
6315                     // Another admin already sets the global proxy
6316                     // Return it to the caller.
6317                     return component;
6318                 }
6319             }
6320 
6321             // If the user is not system, don't set the global proxy. Fail silently.
6322             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
6323                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
6324                         + UserHandle.getCallingUserId() + " is not permitted.");
6325                 return null;
6326             }
6327             if (proxySpec == null) {
6328                 admin.specifiesGlobalProxy = false;
6329                 admin.globalProxySpec = null;
6330                 admin.globalProxyExclusionList = null;
6331             } else {
6332 
6333                 admin.specifiesGlobalProxy = true;
6334                 admin.globalProxySpec = proxySpec;
6335                 admin.globalProxyExclusionList = exclusionList;
6336             }
6337 
6338             // Reset the global proxy accordingly
6339             // Do this using system permissions, as apps cannot write to secure settings
6340             long origId = mInjector.binderClearCallingIdentity();
6341             try {
6342                 resetGlobalProxyLocked(policy);
6343             } finally {
6344                 mInjector.binderRestoreCallingIdentity(origId);
6345             }
6346             return null;
6347         }
6348     }
6349 
6350     @Override
getGlobalProxyAdmin(int userHandle)6351     public ComponentName getGlobalProxyAdmin(int userHandle) {
6352         if (!mHasFeature) {
6353             return null;
6354         }
6355         enforceFullCrossUsersPermission(userHandle);
6356         synchronized (getLockObject()) {
6357             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6358             // Scan through active admins and find if anyone has already
6359             // set the global proxy.
6360             final int N = policy.mAdminList.size();
6361             for (int i = 0; i < N; i++) {
6362                 ActiveAdmin ap = policy.mAdminList.get(i);
6363                 if (ap.specifiesGlobalProxy) {
6364                     // Device admin sets the global proxy
6365                     // Return it to the caller.
6366                     return ap.info.getComponent();
6367                 }
6368             }
6369         }
6370         // No device admin sets the global proxy.
6371         return null;
6372     }
6373 
6374     @Override
setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo)6375     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
6376         synchronized (getLockObject()) {
6377             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6378         }
6379         long token = mInjector.binderClearCallingIdentity();
6380         try {
6381             ConnectivityManager connectivityManager = (ConnectivityManager)
6382                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
6383             connectivityManager.setGlobalProxy(proxyInfo);
6384         } finally {
6385             mInjector.binderRestoreCallingIdentity(token);
6386         }
6387     }
6388 
resetGlobalProxyLocked(DevicePolicyData policy)6389     private void resetGlobalProxyLocked(DevicePolicyData policy) {
6390         final int N = policy.mAdminList.size();
6391         for (int i = 0; i < N; i++) {
6392             ActiveAdmin ap = policy.mAdminList.get(i);
6393             if (ap.specifiesGlobalProxy) {
6394                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
6395                 return;
6396             }
6397         }
6398         // No device admins defining global proxies - reset global proxy settings to none
6399         saveGlobalProxyLocked(null, null);
6400     }
6401 
saveGlobalProxyLocked(String proxySpec, String exclusionList)6402     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
6403         if (exclusionList == null) {
6404             exclusionList = "";
6405         }
6406         if (proxySpec == null) {
6407             proxySpec = "";
6408         }
6409         // Remove white spaces
6410         proxySpec = proxySpec.trim();
6411         String data[] = proxySpec.split(":");
6412         int proxyPort = 8080;
6413         if (data.length > 1) {
6414             try {
6415                 proxyPort = Integer.parseInt(data[1]);
6416             } catch (NumberFormatException e) {}
6417         }
6418         exclusionList = exclusionList.trim();
6419 
6420         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
6421         if (!proxyProperties.isValid()) {
6422             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
6423             return;
6424         }
6425         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
6426         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
6427         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
6428                 exclusionList);
6429     }
6430 
6431     /**
6432      * Called by an application that is administering the device to request that the storage system
6433      * be encrypted. Does nothing if the caller is on a secondary user or a managed profile.
6434      *
6435      * @return the new total request status (for all admins), or {@link
6436      *         DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} if called for a non-system user
6437      */
6438     @Override
setStorageEncryption(ComponentName who, boolean encrypt)6439     public int setStorageEncryption(ComponentName who, boolean encrypt) {
6440         if (!mHasFeature) {
6441             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6442         }
6443         Preconditions.checkNotNull(who, "ComponentName is null");
6444         final int userHandle = UserHandle.getCallingUserId();
6445         synchronized (getLockObject()) {
6446             // Check for permissions
6447             // Only system user can set storage encryption
6448             if (userHandle != UserHandle.USER_SYSTEM) {
6449                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
6450                         + UserHandle.getCallingUserId() + " is not permitted.");
6451                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6452             }
6453 
6454             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6455                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
6456 
6457             // Quick exit:  If the filesystem does not support encryption, we can exit early.
6458             if (!isEncryptionSupported()) {
6459                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6460             }
6461 
6462             // (1) Record the value for the admin so it's sticky
6463             if (ap.encryptionRequested != encrypt) {
6464                 ap.encryptionRequested = encrypt;
6465                 saveSettingsLocked(userHandle);
6466             }
6467 
6468             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
6469             // (2) Compute "max" for all admins
6470             boolean newRequested = false;
6471             final int N = policy.mAdminList.size();
6472             for (int i = 0; i < N; i++) {
6473                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
6474             }
6475 
6476             // Notify OS of new request
6477             setEncryptionRequested(newRequested);
6478 
6479             // Return the new global request status
6480             return newRequested
6481                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
6482                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6483         }
6484     }
6485 
6486     /**
6487      * Get the current storage encryption request status for a given admin, or aggregate of all
6488      * active admins.
6489      */
6490     @Override
getStorageEncryption(ComponentName who, int userHandle)6491     public boolean getStorageEncryption(ComponentName who, int userHandle) {
6492         if (!mHasFeature) {
6493             return false;
6494         }
6495         enforceFullCrossUsersPermission(userHandle);
6496         synchronized (getLockObject()) {
6497             // Check for permissions if a particular caller is specified
6498             if (who != null) {
6499                 // When checking for a single caller, status is based on caller's request
6500                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
6501                 return ap != null ? ap.encryptionRequested : false;
6502             }
6503 
6504             // If no particular caller is specified, return the aggregate set of requests.
6505             // This is short circuited by returning true on the first hit.
6506             DevicePolicyData policy = getUserData(userHandle);
6507             final int N = policy.mAdminList.size();
6508             for (int i = 0; i < N; i++) {
6509                 if (policy.mAdminList.get(i).encryptionRequested) {
6510                     return true;
6511                 }
6512             }
6513             return false;
6514         }
6515     }
6516 
6517     /**
6518      * Get the current encryption status of the device.
6519      */
6520     @Override
getStorageEncryptionStatus(@ullable String callerPackage, int userHandle)6521     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
6522         if (!mHasFeature) {
6523             // Ok to return current status.
6524         }
6525         enforceFullCrossUsersPermission(userHandle);
6526 
6527         // It's not critical here, but let's make sure the package name is correct, in case
6528         // we start using it for different purposes.
6529         ensureCallerPackage(callerPackage);
6530 
6531         final ApplicationInfo ai;
6532         try {
6533             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
6534         } catch (RemoteException e) {
6535             throw new SecurityException(e);
6536         }
6537 
6538         boolean legacyApp = false;
6539         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
6540             legacyApp = true;
6541         }
6542 
6543         final int rawStatus = getEncryptionStatus();
6544         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
6545             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6546         }
6547         return rawStatus;
6548     }
6549 
6550     /**
6551      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
6552      */
isEncryptionSupported()6553     private boolean isEncryptionSupported() {
6554         // Note, this can be implemented as
6555         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6556         // But is provided as a separate internal method if there's a faster way to do a
6557         // simple check for supported-or-not.
6558         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6559     }
6560 
6561     /**
6562      * Hook to low-levels:  Reporting the current status of encryption.
6563      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
6564      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
6565      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
6566      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
6567      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
6568      */
getEncryptionStatus()6569     private int getEncryptionStatus() {
6570         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
6571             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
6572         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
6573             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
6574         } else if (mInjector.storageManagerIsEncrypted()) {
6575             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
6576         } else if (mInjector.storageManagerIsEncryptable()) {
6577             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
6578         } else {
6579             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
6580         }
6581     }
6582 
6583     /**
6584      * Hook to low-levels:  If needed, record the new admin setting for encryption.
6585      */
setEncryptionRequested(boolean encrypt)6586     private void setEncryptionRequested(boolean encrypt) {
6587     }
6588 
6589     /**
6590      * Set whether the screen capture is disabled for the user managed by the specified admin.
6591      */
6592     @Override
setScreenCaptureDisabled(ComponentName who, boolean disabled)6593     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
6594         if (!mHasFeature) {
6595             return;
6596         }
6597         Preconditions.checkNotNull(who, "ComponentName is null");
6598         final int userHandle = UserHandle.getCallingUserId();
6599         synchronized (getLockObject()) {
6600             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6601                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6602             if (ap.disableScreenCapture != disabled) {
6603                 ap.disableScreenCapture = disabled;
6604                 saveSettingsLocked(userHandle);
6605                 updateScreenCaptureDisabled(userHandle, disabled);
6606             }
6607         }
6608     }
6609 
6610     /**
6611      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
6612      * active admin (if given admin is null).
6613      */
6614     @Override
getScreenCaptureDisabled(ComponentName who, int userHandle)6615     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
6616         if (!mHasFeature) {
6617             return false;
6618         }
6619         synchronized (getLockObject()) {
6620             if (who != null) {
6621                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
6622                 return (admin != null) ? admin.disableScreenCapture : false;
6623             }
6624 
6625             DevicePolicyData policy = getUserData(userHandle);
6626             final int N = policy.mAdminList.size();
6627             for (int i = 0; i < N; i++) {
6628                 ActiveAdmin admin = policy.mAdminList.get(i);
6629                 if (admin.disableScreenCapture) {
6630                     return true;
6631                 }
6632             }
6633             return false;
6634         }
6635     }
6636 
updateScreenCaptureDisabled(int userHandle, boolean disabled)6637     private void updateScreenCaptureDisabled(int userHandle, boolean disabled) {
6638         mPolicyCache.setScreenCaptureDisabled(userHandle, disabled);
6639         mHandler.post(new Runnable() {
6640             @Override
6641             public void run() {
6642                 try {
6643                     mInjector.getIWindowManager().refreshScreenCaptureDisabled(userHandle);
6644                 } catch (RemoteException e) {
6645                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
6646                 }
6647             }
6648         });
6649     }
6650 
6651     /**
6652      * Set whether auto time is required by the specified admin (must be device or profile owner).
6653      */
6654     @Override
setAutoTimeRequired(ComponentName who, boolean required)6655     public void setAutoTimeRequired(ComponentName who, boolean required) {
6656         if (!mHasFeature) {
6657             return;
6658         }
6659         Preconditions.checkNotNull(who, "ComponentName is null");
6660         final int userHandle = UserHandle.getCallingUserId();
6661         synchronized (getLockObject()) {
6662             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
6663                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6664             if (admin.requireAutoTime != required) {
6665                 admin.requireAutoTime = required;
6666                 saveSettingsLocked(userHandle);
6667             }
6668         }
6669 
6670         // Turn AUTO_TIME on in settings if it is required
6671         if (required) {
6672             long ident = mInjector.binderClearCallingIdentity();
6673             try {
6674                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
6675             } finally {
6676                 mInjector.binderRestoreCallingIdentity(ident);
6677             }
6678         }
6679     }
6680 
6681     /**
6682      * Returns whether or not auto time is required by the device owner or any profile owner.
6683      */
6684     @Override
getAutoTimeRequired()6685     public boolean getAutoTimeRequired() {
6686         if (!mHasFeature) {
6687             return false;
6688         }
6689         synchronized (getLockObject()) {
6690             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
6691             if (deviceOwner != null && deviceOwner.requireAutoTime) {
6692                 // If the device owner enforces auto time, we don't need to check the PO's
6693                 return true;
6694             }
6695 
6696             // Now check to see if any profile owner on any user enforces auto time
6697             for (Integer userId : mOwners.getProfileOwnerKeys()) {
6698                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
6699                 if (profileOwner != null && profileOwner.requireAutoTime) {
6700                     return true;
6701                 }
6702             }
6703 
6704             return false;
6705         }
6706     }
6707 
6708     @Override
setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers)6709     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
6710         if (!mHasFeature) {
6711             return;
6712         }
6713         Preconditions.checkNotNull(who, "ComponentName is null");
6714         // Allow setting this policy to true only if there is a split system user.
6715         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
6716             throw new UnsupportedOperationException(
6717                     "Cannot force ephemeral users on systems without split system user.");
6718         }
6719         boolean removeAllUsers = false;
6720         synchronized (getLockObject()) {
6721             final ActiveAdmin deviceOwner =
6722                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6723             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
6724                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
6725                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
6726                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
6727                 removeAllUsers = forceEphemeralUsers;
6728             }
6729         }
6730         if (removeAllUsers) {
6731             long identitity = mInjector.binderClearCallingIdentity();
6732             try {
6733                 mUserManagerInternal.removeAllUsers();
6734             } finally {
6735                 mInjector.binderRestoreCallingIdentity(identitity);
6736             }
6737         }
6738     }
6739 
6740     @Override
getForceEphemeralUsers(ComponentName who)6741     public boolean getForceEphemeralUsers(ComponentName who) {
6742         if (!mHasFeature) {
6743             return false;
6744         }
6745         Preconditions.checkNotNull(who, "ComponentName is null");
6746         synchronized (getLockObject()) {
6747             final ActiveAdmin deviceOwner =
6748                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6749             return deviceOwner.forceEphemeralUsers;
6750         }
6751     }
6752 
ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who)6753     private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException {
6754         synchronized (getLockObject()) {
6755             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6756             if (!areAllUsersAffiliatedWithDeviceLocked()) {
6757                 throw new SecurityException("Not all users are affiliated.");
6758             }
6759         }
6760     }
6761 
6762     @Override
requestBugreport(ComponentName who)6763     public boolean requestBugreport(ComponentName who) {
6764         if (!mHasFeature) {
6765             return false;
6766         }
6767         Preconditions.checkNotNull(who, "ComponentName is null");
6768 
6769         // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport
6770         // which could still contain data related to that user. Should we disallow that, e.g. until
6771         // next boot? Might not be needed given that this still requires user consent.
6772         ensureDeviceOwnerAndAllUsersAffiliated(who);
6773 
6774         if (mRemoteBugreportServiceIsActive.get()
6775                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
6776             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
6777             return false;
6778         }
6779 
6780         final long currentTime = System.currentTimeMillis();
6781         synchronized (getLockObject()) {
6782             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
6783             if (currentTime > policyData.mLastBugReportRequestTime) {
6784                 policyData.mLastBugReportRequestTime = currentTime;
6785                 saveSettingsLocked(UserHandle.USER_SYSTEM);
6786             }
6787         }
6788 
6789         final long callingIdentity = mInjector.binderClearCallingIdentity();
6790         try {
6791             mInjector.getIActivityManager().requestBugReport(
6792                     ActivityManager.BUGREPORT_OPTION_REMOTE);
6793 
6794             mRemoteBugreportServiceIsActive.set(true);
6795             mRemoteBugreportSharingAccepted.set(false);
6796             registerRemoteBugreportReceivers();
6797             mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
6798                     RemoteBugreportUtils.NOTIFICATION_ID,
6799                     RemoteBugreportUtils.buildNotification(mContext,
6800                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
6801             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
6802                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
6803             return true;
6804         } catch (RemoteException re) {
6805             // should never happen
6806             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
6807             return false;
6808         } finally {
6809             mInjector.binderRestoreCallingIdentity(callingIdentity);
6810         }
6811     }
6812 
sendDeviceOwnerCommand(String action, Bundle extras)6813     void sendDeviceOwnerCommand(String action, Bundle extras) {
6814         int deviceOwnerUserId;
6815         ComponentName deviceOwnerComponent;
6816         synchronized (getLockObject()) {
6817             deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6818             deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6819         }
6820         sendActiveAdminCommand(action, extras, deviceOwnerUserId,
6821                 deviceOwnerComponent);
6822     }
6823 
sendProfileOwnerCommand(String action, Bundle extras, int userHandle)6824     private void sendProfileOwnerCommand(String action, Bundle extras, int userHandle) {
6825         sendActiveAdminCommand(action, extras, userHandle,
6826                 mOwners.getProfileOwnerComponent(userHandle));
6827     }
6828 
sendActiveAdminCommand(String action, Bundle extras, int userHandle, ComponentName receiverComponent)6829     private void sendActiveAdminCommand(String action, Bundle extras,
6830             int userHandle, ComponentName receiverComponent) {
6831         final Intent intent = new Intent(action);
6832         intent.setComponent(receiverComponent);
6833         if (extras != null) {
6834             intent.putExtras(extras);
6835         }
6836         mContext.sendBroadcastAsUser(intent, UserHandle.of(userHandle));
6837     }
6838 
sendOwnerChangedBroadcast(String broadcast, int userId)6839     private void sendOwnerChangedBroadcast(String broadcast, int userId) {
6840         final Intent intent = new Intent(broadcast)
6841                 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
6842         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
6843     }
6844 
getDeviceOwnerRemoteBugreportUri()6845     private String getDeviceOwnerRemoteBugreportUri() {
6846         synchronized (getLockObject()) {
6847             return mOwners.getDeviceOwnerRemoteBugreportUri();
6848         }
6849     }
6850 
setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, String bugreportHash)6851     private void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
6852             String bugreportHash) {
6853         synchronized (getLockObject()) {
6854             mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
6855         }
6856     }
6857 
registerRemoteBugreportReceivers()6858     private void registerRemoteBugreportReceivers() {
6859         try {
6860             IntentFilter filterFinished = new IntentFilter(
6861                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
6862                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6863             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
6864         } catch (IntentFilter.MalformedMimeTypeException e) {
6865             // should never happen, as setting a constant
6866             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
6867         }
6868         IntentFilter filterConsent = new IntentFilter();
6869         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
6870         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
6871         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
6872     }
6873 
onBugreportFinished(Intent intent)6874     private void onBugreportFinished(Intent intent) {
6875         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6876         mRemoteBugreportServiceIsActive.set(false);
6877         Uri bugreportUri = intent.getData();
6878         String bugreportUriString = null;
6879         if (bugreportUri != null) {
6880             bugreportUriString = bugreportUri.toString();
6881         }
6882         String bugreportHash = intent.getStringExtra(
6883                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
6884         if (mRemoteBugreportSharingAccepted.get()) {
6885             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6886             mInjector.getNotificationManager().cancel(LOG_TAG,
6887                     RemoteBugreportUtils.NOTIFICATION_ID);
6888         } else {
6889             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
6890             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6891                     RemoteBugreportUtils.buildNotification(mContext,
6892                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
6893                             UserHandle.ALL);
6894         }
6895         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6896     }
6897 
onBugreportFailed()6898     private void onBugreportFailed() {
6899         mRemoteBugreportServiceIsActive.set(false);
6900         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6901                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6902         mRemoteBugreportSharingAccepted.set(false);
6903         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6904         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
6905         Bundle extras = new Bundle();
6906         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6907                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
6908         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6909         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
6910         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6911     }
6912 
onBugreportSharingAccepted()6913     private void onBugreportSharingAccepted() {
6914         mRemoteBugreportSharingAccepted.set(true);
6915         String bugreportUriString = null;
6916         String bugreportHash = null;
6917         synchronized (getLockObject()) {
6918             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
6919             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
6920         }
6921         if (bugreportUriString != null) {
6922             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
6923         } else if (mRemoteBugreportServiceIsActive.get()) {
6924             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
6925                     RemoteBugreportUtils.buildNotification(mContext,
6926                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
6927                             UserHandle.ALL);
6928         }
6929     }
6930 
onBugreportSharingDeclined()6931     private void onBugreportSharingDeclined() {
6932         if (mRemoteBugreportServiceIsActive.get()) {
6933             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
6934                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
6935             mRemoteBugreportServiceIsActive.set(false);
6936             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
6937             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
6938         }
6939         mRemoteBugreportSharingAccepted.set(false);
6940         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6941         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
6942     }
6943 
shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, String bugreportHash)6944     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
6945             String bugreportHash) {
6946         ParcelFileDescriptor pfd = null;
6947         try {
6948             if (bugreportUriString == null) {
6949                 throw new FileNotFoundException();
6950             }
6951             Uri bugreportUri = Uri.parse(bugreportUriString);
6952             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
6953 
6954             synchronized (getLockObject()) {
6955                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
6956                 intent.setComponent(mOwners.getDeviceOwnerComponent());
6957                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
6958                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
6959                 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
6960 
6961                 LocalServices.getService(ActivityManagerInternal.class)
6962                         .grantUriPermissionFromIntent(Process.SHELL_UID,
6963                                 mOwners.getDeviceOwnerComponent().getPackageName(),
6964                                 intent, mOwners.getDeviceOwnerUserId());
6965                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
6966             }
6967         } catch (FileNotFoundException e) {
6968             Bundle extras = new Bundle();
6969             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
6970                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
6971             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
6972         } finally {
6973             try {
6974                 if (pfd != null) {
6975                     pfd.close();
6976                 }
6977             } catch (IOException ex) {
6978                 // Ignore
6979             }
6980             mRemoteBugreportSharingAccepted.set(false);
6981             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
6982         }
6983     }
6984 
6985     /**
6986      * Disables all device cameras according to the specified admin.
6987      */
6988     @Override
setCameraDisabled(ComponentName who, boolean disabled)6989     public void setCameraDisabled(ComponentName who, boolean disabled) {
6990         if (!mHasFeature) {
6991             return;
6992         }
6993         Preconditions.checkNotNull(who, "ComponentName is null");
6994         final int userHandle = mInjector.userHandleGetCallingUserId();
6995         synchronized (getLockObject()) {
6996             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
6997                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
6998             if (ap.disableCamera != disabled) {
6999                 ap.disableCamera = disabled;
7000                 saveSettingsLocked(userHandle);
7001             }
7002         }
7003         // Tell the user manager that the restrictions have changed.
7004         pushUserRestrictions(userHandle);
7005     }
7006 
7007     /**
7008      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
7009      * active admins.
7010      */
7011     @Override
getCameraDisabled(ComponentName who, int userHandle)7012     public boolean getCameraDisabled(ComponentName who, int userHandle) {
7013         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
7014     }
7015 
getCameraDisabled(ComponentName who, int userHandle, boolean mergeDeviceOwnerRestriction)7016     private boolean getCameraDisabled(ComponentName who, int userHandle,
7017             boolean mergeDeviceOwnerRestriction) {
7018         if (!mHasFeature) {
7019             return false;
7020         }
7021         synchronized (getLockObject()) {
7022             if (who != null) {
7023                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7024                 return (admin != null) ? admin.disableCamera : false;
7025             }
7026             // First, see if DO has set it.  If so, it's device-wide.
7027             if (mergeDeviceOwnerRestriction) {
7028                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7029                 if (deviceOwner != null && deviceOwner.disableCamera) {
7030                     return true;
7031                 }
7032             }
7033 
7034             // Then check each device admin on the user.
7035             DevicePolicyData policy = getUserData(userHandle);
7036             // Determine whether or not the device camera is disabled for any active admins.
7037             final int N = policy.mAdminList.size();
7038             for (int i = 0; i < N; i++) {
7039                 ActiveAdmin admin = policy.mAdminList.get(i);
7040                 if (admin.disableCamera) {
7041                     return true;
7042                 }
7043             }
7044             return false;
7045         }
7046     }
7047 
7048     @Override
setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent)7049     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
7050         if (!mHasFeature) {
7051             return;
7052         }
7053         Preconditions.checkNotNull(who, "ComponentName is null");
7054         final int userHandle = mInjector.userHandleGetCallingUserId();
7055         if (isManagedProfile(userHandle)) {
7056             if (parent) {
7057                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
7058             } else {
7059                 which = which & PROFILE_KEYGUARD_FEATURES;
7060             }
7061         }
7062         synchronized (getLockObject()) {
7063             ActiveAdmin ap = getActiveAdminForCallerLocked(
7064                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
7065             if (ap.disabledKeyguardFeatures != which) {
7066                 ap.disabledKeyguardFeatures = which;
7067                 saveSettingsLocked(userHandle);
7068             }
7069         }
7070         if (SecurityLog.isLoggingEnabled()) {
7071             final int affectedUserId = parent ? getProfileParentId(userHandle) : userHandle;
7072             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISABLED_FEATURES_SET,
7073                     who.getPackageName(), userHandle, affectedUserId, which);
7074         }
7075     }
7076 
7077     /**
7078      * Gets the disabled state for features in keyguard for the given admin,
7079      * or the aggregate of all active admins if who is null.
7080      */
7081     @Override
getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent)7082     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
7083         if (!mHasFeature) {
7084             return 0;
7085         }
7086         enforceFullCrossUsersPermission(userHandle);
7087         final long ident = mInjector.binderClearCallingIdentity();
7088         try {
7089             synchronized (getLockObject()) {
7090                 if (who != null) {
7091                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
7092                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
7093                 }
7094 
7095                 final List<ActiveAdmin> admins;
7096                 if (!parent && isManagedProfile(userHandle)) {
7097                     // If we are being asked about a managed profile, just return keyguard features
7098                     // disabled by admins in the profile.
7099                     admins = getUserDataUnchecked(userHandle).mAdminList;
7100                 } else {
7101                     // Otherwise return those set by admins in the user and its profiles.
7102                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
7103                 }
7104 
7105                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
7106                 final int N = admins.size();
7107                 for (int i = 0; i < N; i++) {
7108                     ActiveAdmin admin = admins.get(i);
7109                     int userId = admin.getUserHandle().getIdentifier();
7110                     boolean isRequestedUser = !parent && (userId == userHandle);
7111                     if (isRequestedUser || !isManagedProfile(userId)) {
7112                         // If we are being asked explicitly about this user
7113                         // return all disabled features even if its a managed profile.
7114                         which |= admin.disabledKeyguardFeatures;
7115                     } else {
7116                         // Otherwise a managed profile is only allowed to disable
7117                         // some features on the parent user.
7118                         which |= (admin.disabledKeyguardFeatures
7119                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
7120                     }
7121                 }
7122                 return which;
7123             }
7124         } finally {
7125             mInjector.binderRestoreCallingIdentity(ident);
7126         }
7127     }
7128 
7129     @Override
setKeepUninstalledPackages(ComponentName who, String callerPackage, List<String> packageList)7130     public void setKeepUninstalledPackages(ComponentName who, String callerPackage,
7131             List<String> packageList) {
7132         if (!mHasFeature) {
7133             return;
7134         }
7135         Preconditions.checkNotNull(packageList, "packageList is null");
7136         final int userHandle = UserHandle.getCallingUserId();
7137         synchronized (getLockObject()) {
7138             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7139             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7140                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7141             // Get the device owner
7142             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7143             // Set list of packages to be kept even if uninstalled.
7144             deviceOwner.keepUninstalledPackages = packageList;
7145             // Save settings.
7146             saveSettingsLocked(userHandle);
7147             // Notify package manager.
7148             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
7149         }
7150     }
7151 
7152     @Override
getKeepUninstalledPackages(ComponentName who, String callerPackage)7153     public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) {
7154         if (!mHasFeature) {
7155             return null;
7156         }
7157         // TODO In split system user mode, allow apps on user 0 to query the list
7158         synchronized (getLockObject()) {
7159             // Ensure the caller is a DO or a keep uninstalled packages delegate.
7160             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7161                     DELEGATION_KEEP_UNINSTALLED_PACKAGES);
7162             return getKeepUninstalledPackagesLocked();
7163         }
7164     }
7165 
getKeepUninstalledPackagesLocked()7166     private List<String> getKeepUninstalledPackagesLocked() {
7167         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7168         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
7169     }
7170 
7171     @Override
setDeviceOwner(ComponentName admin, String ownerName, int userId)7172     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
7173         if (!mHasFeature) {
7174             return false;
7175         }
7176         if (admin == null
7177                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
7178             throw new IllegalArgumentException("Invalid component " + admin
7179                     + " for device owner");
7180         }
7181         final boolean hasIncompatibleAccountsOrNonAdb =
7182                 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin);
7183         synchronized (getLockObject()) {
7184             enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb);
7185             final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId);
7186             if (activeAdmin == null
7187                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
7188                 throw new IllegalArgumentException("Not active admin: " + admin);
7189             }
7190 
7191             // Shutting down backup manager service permanently.
7192             long ident = mInjector.binderClearCallingIdentity();
7193             try {
7194                 if (mInjector.getIBackupManager() != null) {
7195                     mInjector.getIBackupManager()
7196                             .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
7197                 }
7198             } catch (RemoteException e) {
7199                 throw new IllegalStateException("Failed deactivating backup service.", e);
7200             } finally {
7201                 mInjector.binderRestoreCallingIdentity(ident);
7202             }
7203 
7204             if (isAdb()) {
7205                 // Log device owner provisioning was started using adb.
7206                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER);
7207             }
7208 
7209             mOwners.setDeviceOwner(admin, ownerName, userId);
7210             mOwners.writeDeviceOwner();
7211             updateDeviceOwnerLocked();
7212             setDeviceOwnerSystemPropertyLocked();
7213 
7214             final Set<String> restrictions =
7215                     UserRestrictionsUtils.getDefaultEnabledForDeviceOwner();
7216             if (!restrictions.isEmpty()) {
7217                 for (String restriction : restrictions) {
7218                     activeAdmin.ensureUserRestrictions().putBoolean(restriction, true);
7219                 }
7220                 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions);
7221                 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions);
7222 
7223                 saveUserRestrictionsLocked(userId);
7224             }
7225 
7226             ident = mInjector.binderClearCallingIdentity();
7227             try {
7228                 // TODO Send to system too?
7229                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, userId);
7230             } finally {
7231                 mInjector.binderRestoreCallingIdentity(ident);
7232             }
7233             mDeviceAdminServiceController.startServiceForOwner(
7234                     admin.getPackageName(), userId, "set-device-owner");
7235 
7236             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
7237             return true;
7238         }
7239     }
7240 
7241     @Override
hasDeviceOwner()7242     public boolean hasDeviceOwner() {
7243         enforceDeviceOwnerOrManageUsers();
7244         return mOwners.hasDeviceOwner();
7245     }
7246 
isDeviceOwner(ActiveAdmin admin)7247     boolean isDeviceOwner(ActiveAdmin admin) {
7248         return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier());
7249     }
7250 
isDeviceOwner(ComponentName who, int userId)7251     public boolean isDeviceOwner(ComponentName who, int userId) {
7252         synchronized (getLockObject()) {
7253             return mOwners.hasDeviceOwner()
7254                     && mOwners.getDeviceOwnerUserId() == userId
7255                     && mOwners.getDeviceOwnerComponent().equals(who);
7256         }
7257     }
7258 
isDeviceOwnerPackage(String packageName, int userId)7259     private boolean isDeviceOwnerPackage(String packageName, int userId) {
7260         synchronized (getLockObject()) {
7261             return mOwners.hasDeviceOwner()
7262                     && mOwners.getDeviceOwnerUserId() == userId
7263                     && mOwners.getDeviceOwnerPackageName().equals(packageName);
7264         }
7265     }
7266 
isProfileOwnerPackage(String packageName, int userId)7267     private boolean isProfileOwnerPackage(String packageName, int userId) {
7268         synchronized (getLockObject()) {
7269             return mOwners.hasProfileOwner(userId)
7270                     && mOwners.getProfileOwnerPackage(userId).equals(packageName);
7271         }
7272     }
7273 
isProfileOwner(ComponentName who, int userId)7274     public boolean isProfileOwner(ComponentName who, int userId) {
7275         final ComponentName profileOwner = getProfileOwner(userId);
7276         return who != null && who.equals(profileOwner);
7277     }
7278 
7279     @Override
getDeviceOwnerComponent(boolean callingUserOnly)7280     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
7281         if (!mHasFeature) {
7282             return null;
7283         }
7284         if (!callingUserOnly) {
7285             enforceManageUsers();
7286         }
7287         synchronized (getLockObject()) {
7288             if (!mOwners.hasDeviceOwner()) {
7289                 return null;
7290             }
7291             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
7292                     mOwners.getDeviceOwnerUserId()) {
7293                 return null;
7294             }
7295             return mOwners.getDeviceOwnerComponent();
7296         }
7297     }
7298 
7299     @Override
getDeviceOwnerUserId()7300     public int getDeviceOwnerUserId() {
7301         if (!mHasFeature) {
7302             return UserHandle.USER_NULL;
7303         }
7304         enforceManageUsers();
7305         synchronized (getLockObject()) {
7306             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
7307         }
7308     }
7309 
7310     /**
7311      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
7312      * MANAGE_USERS.
7313      */
7314     @Override
getDeviceOwnerName()7315     public String getDeviceOwnerName() {
7316         if (!mHasFeature) {
7317             return null;
7318         }
7319         enforceManageUsers();
7320         synchronized (getLockObject()) {
7321             if (!mOwners.hasDeviceOwner()) {
7322                 return null;
7323             }
7324             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
7325             // Should setDeviceOwner/ProfileOwner still take a name?
7326             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
7327             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
7328         }
7329     }
7330 
7331     /** Returns the active device owner or {@code null} if there is no device owner. */
7332     @VisibleForTesting
getDeviceOwnerAdminLocked()7333     ActiveAdmin getDeviceOwnerAdminLocked() {
7334         ensureLocked();
7335         ComponentName component = mOwners.getDeviceOwnerComponent();
7336         if (component == null) {
7337             return null;
7338         }
7339 
7340         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
7341         final int n = policy.mAdminList.size();
7342         for (int i = 0; i < n; i++) {
7343             ActiveAdmin admin = policy.mAdminList.get(i);
7344             if (component.equals(admin.info.getComponent())) {
7345                 return admin;
7346             }
7347         }
7348         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
7349         return null;
7350     }
7351 
7352     @Override
clearDeviceOwner(String packageName)7353     public void clearDeviceOwner(String packageName) {
7354         Preconditions.checkNotNull(packageName, "packageName is null");
7355         final int callingUid = mInjector.binderGetCallingUid();
7356         try {
7357             int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName,
7358                     UserHandle.getUserId(callingUid));
7359             if (uid != callingUid) {
7360                 throw new SecurityException("Invalid packageName");
7361             }
7362         } catch (NameNotFoundException e) {
7363             throw new SecurityException(e);
7364         }
7365         synchronized (getLockObject()) {
7366             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
7367             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
7368             if (!mOwners.hasDeviceOwner()
7369                     || !deviceOwnerComponent.getPackageName().equals(packageName)
7370                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
7371                 throw new SecurityException(
7372                         "clearDeviceOwner can only be called by the device owner");
7373             }
7374             enforceUserUnlocked(deviceOwnerUserId);
7375 
7376             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
7377             long ident = mInjector.binderClearCallingIdentity();
7378             try {
7379                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
7380                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
7381                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED,
7382                         deviceOwnerUserId);
7383             } finally {
7384                 mInjector.binderRestoreCallingIdentity(ident);
7385             }
7386             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
7387         }
7388     }
7389 
clearOverrideApnUnchecked()7390     private void clearOverrideApnUnchecked() {
7391         // Disable Override APNs and remove them from database.
7392         setOverrideApnsEnabledUnchecked(false);
7393         final List<ApnSetting> apns = getOverrideApnsUnchecked();
7394         for (int i = 0; i < apns.size(); i ++) {
7395             removeOverrideApnUnchecked(apns.get(i).getId());
7396         }
7397     }
7398 
clearDeviceOwnerLocked(ActiveAdmin admin, int userId)7399     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
7400         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner");
7401 
7402         if (admin != null) {
7403             admin.disableCamera = false;
7404             admin.userRestrictions = null;
7405             admin.defaultEnabledRestrictionsAlreadySet.clear();
7406             admin.forceEphemeralUsers = false;
7407             admin.isNetworkLoggingEnabled = false;
7408             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
7409         }
7410         final DevicePolicyData policyData = getUserData(userId);
7411         policyData.mCurrentInputMethodSet = false;
7412         saveSettingsLocked(userId);
7413         final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM);
7414         systemPolicyData.mLastSecurityLogRetrievalTime = -1;
7415         systemPolicyData.mLastBugReportRequestTime = -1;
7416         systemPolicyData.mLastNetworkLogsRetrievalTime = -1;
7417         saveSettingsLocked(UserHandle.USER_SYSTEM);
7418         clearUserPoliciesLocked(userId);
7419         clearOverrideApnUnchecked();
7420 
7421         mOwners.clearDeviceOwner();
7422         mOwners.writeDeviceOwner();
7423         updateDeviceOwnerLocked();
7424 
7425         clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId));
7426         mInjector.securityLogSetLoggingEnabledProperty(false);
7427         mSecurityLogMonitor.stop();
7428         setNetworkLoggingActiveInternal(false);
7429         deleteTransferOwnershipBundleLocked(userId);
7430 
7431         try {
7432             if (mInjector.getIBackupManager() != null) {
7433                 // Reactivate backup service.
7434                 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
7435             }
7436         } catch (RemoteException e) {
7437             throw new IllegalStateException("Failed reactivating backup service.", e);
7438         }
7439     }
7440 
7441     @Override
setProfileOwner(ComponentName who, String ownerName, int userHandle)7442     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
7443         if (!mHasFeature) {
7444             return false;
7445         }
7446         if (who == null
7447                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
7448             throw new IllegalArgumentException("Component " + who
7449                     + " not installed for userId:" + userHandle);
7450         }
7451         final boolean hasIncompatibleAccountsOrNonAdb =
7452                 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who);
7453         synchronized (getLockObject()) {
7454             enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb);
7455 
7456             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7457             if (admin == null || getUserData(userHandle).mRemovingAdmins.contains(who)) {
7458                 throw new IllegalArgumentException("Not active admin: " + who);
7459             }
7460 
7461             if (isAdb()) {
7462                 // Log profile owner provisioning was started using adb.
7463                 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER);
7464             }
7465 
7466             mOwners.setProfileOwner(who, ownerName, userHandle);
7467             mOwners.writeProfileOwner(userHandle);
7468             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
7469 
7470             final long id = mInjector.binderClearCallingIdentity();
7471             try {
7472                 if (mUserManager.isManagedProfile(userHandle)) {
7473                     maybeSetDefaultRestrictionsForAdminLocked(userHandle, admin,
7474                             UserRestrictionsUtils.getDefaultEnabledForManagedProfiles());
7475                     ensureUnknownSourcesRestrictionForProfileOwnerLocked(userHandle, admin,
7476                             true /* newOwner */);
7477                 }
7478                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7479                         userHandle);
7480             } finally {
7481                 mInjector.binderRestoreCallingIdentity(id);
7482             }
7483             mDeviceAdminServiceController.startServiceForOwner(
7484                     who.getPackageName(), userHandle, "set-profile-owner");
7485             return true;
7486         }
7487     }
7488 
7489     @Override
clearProfileOwner(ComponentName who)7490     public void clearProfileOwner(ComponentName who) {
7491         if (!mHasFeature) {
7492             return;
7493         }
7494         Preconditions.checkNotNull(who, "ComponentName is null");
7495 
7496         final int userId = mInjector.userHandleGetCallingUserId();
7497         enforceNotManagedProfile(userId, "clear profile owner");
7498         enforceUserUnlocked(userId);
7499         synchronized (getLockObject()) {
7500             // Check if this is the profile owner who is calling
7501             final ActiveAdmin admin =
7502                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7503 
7504             final long ident = mInjector.binderClearCallingIdentity();
7505             try {
7506                 clearProfileOwnerLocked(admin, userId);
7507                 removeActiveAdminLocked(who, userId);
7508                 sendOwnerChangedBroadcast(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED,
7509                         userId);
7510             } finally {
7511                 mInjector.binderRestoreCallingIdentity(ident);
7512             }
7513             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
7514         }
7515     }
7516 
clearProfileOwnerLocked(ActiveAdmin admin, int userId)7517     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
7518         mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner");
7519 
7520         if (admin != null) {
7521             admin.disableCamera = false;
7522             admin.userRestrictions = null;
7523             admin.defaultEnabledRestrictionsAlreadySet.clear();
7524         }
7525         final DevicePolicyData policyData = getUserData(userId);
7526         policyData.mCurrentInputMethodSet = false;
7527         policyData.mOwnerInstalledCaCerts.clear();
7528         saveSettingsLocked(userId);
7529         clearUserPoliciesLocked(userId);
7530         mOwners.removeProfileOwner(userId);
7531         mOwners.writeProfileOwner(userId);
7532         deleteTransferOwnershipBundleLocked(userId);
7533     }
7534 
7535     @Override
setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info)7536     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
7537         Preconditions.checkNotNull(who, "ComponentName is null");
7538         if (!mHasFeature) {
7539             return;
7540         }
7541 
7542         synchronized (getLockObject()) {
7543             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7544             long token = mInjector.binderClearCallingIdentity();
7545             try {
7546                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
7547             } finally {
7548                 mInjector.binderRestoreCallingIdentity(token);
7549             }
7550         }
7551     }
7552 
7553     @Override
getDeviceOwnerLockScreenInfo()7554     public CharSequence getDeviceOwnerLockScreenInfo() {
7555         return mLockPatternUtils.getDeviceOwnerInfo();
7556     }
7557 
clearUserPoliciesLocked(int userId)7558     private void clearUserPoliciesLocked(int userId) {
7559         // Reset some of the user-specific policies.
7560         final DevicePolicyData policy = getUserData(userId);
7561         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
7562         // Clear delegations.
7563         policy.mDelegationMap.clear();
7564         policy.mStatusBarDisabled = false;
7565         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
7566         policy.mAffiliationIds.clear();
7567         policy.mLockTaskPackages.clear();
7568         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userId);
7569         policy.mLockTaskFeatures = DevicePolicyManager.LOCK_TASK_FEATURE_NONE;
7570         saveSettingsLocked(userId);
7571 
7572         try {
7573             mIPackageManager.updatePermissionFlagsForAllApps(
7574                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
7575                     0  /* flagValues */, userId);
7576             pushUserRestrictions(userId);
7577         } catch (RemoteException re) {
7578             // Shouldn't happen.
7579         }
7580     }
7581 
7582     @Override
hasUserSetupCompleted()7583     public boolean hasUserSetupCompleted() {
7584         return hasUserSetupCompleted(UserHandle.getCallingUserId());
7585     }
7586 
7587     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
7588     // completing Setup Wizard, and pairing involves transferring user data, calling
7589     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
hasUserSetupCompleted(int userHandle)7590     private boolean hasUserSetupCompleted(int userHandle) {
7591         if (!mHasFeature) {
7592             return true;
7593         }
7594         return getUserData(userHandle).mUserSetupComplete;
7595     }
7596 
hasPaired(int userHandle)7597     private boolean hasPaired(int userHandle) {
7598         if (!mHasFeature) {
7599             return true;
7600         }
7601         return getUserData(userHandle).mPaired;
7602     }
7603 
7604     @Override
getUserProvisioningState()7605     public int getUserProvisioningState() {
7606         if (!mHasFeature) {
7607             return DevicePolicyManager.STATE_USER_UNMANAGED;
7608         }
7609         enforceManageUsers();
7610         int userHandle = mInjector.userHandleGetCallingUserId();
7611         return getUserProvisioningState(userHandle);
7612     }
7613 
getUserProvisioningState(int userHandle)7614     private int getUserProvisioningState(int userHandle) {
7615         return getUserData(userHandle).mUserProvisioningState;
7616     }
7617 
7618     @Override
setUserProvisioningState(int newState, int userHandle)7619     public void setUserProvisioningState(int newState, int userHandle) {
7620         if (!mHasFeature) {
7621             return;
7622         }
7623 
7624         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
7625                 && getManagedUserId(userHandle) == -1) {
7626             // No managed device, user or profile, so setting provisioning state makes no sense.
7627             throw new IllegalStateException("Not allowed to change provisioning state unless a "
7628                       + "device or profile owner is set.");
7629         }
7630 
7631         synchronized (getLockObject()) {
7632             boolean transitionCheckNeeded = true;
7633 
7634             // Calling identity/permission checks.
7635             if (isAdb()) {
7636                 // ADB shell can only move directly from un-managed to finalized as part of directly
7637                 // setting profile-owner or device-owner.
7638                 if (getUserProvisioningState(userHandle) !=
7639                         DevicePolicyManager.STATE_USER_UNMANAGED
7640                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7641                     throw new IllegalStateException("Not allowed to change provisioning state "
7642                             + "unless current provisioning state is unmanaged, and new state is "
7643                             + "finalized.");
7644                 }
7645                 transitionCheckNeeded = false;
7646             } else {
7647                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
7648                 enforceCanManageProfileAndDeviceOwners();
7649             }
7650 
7651             final DevicePolicyData policyData = getUserData(userHandle);
7652             if (transitionCheckNeeded) {
7653                 // Optional state transition check for non-ADB case.
7654                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
7655             }
7656             policyData.mUserProvisioningState = newState;
7657             saveSettingsLocked(userHandle);
7658         }
7659     }
7660 
checkUserProvisioningStateTransition(int currentState, int newState)7661     private void checkUserProvisioningStateTransition(int currentState, int newState) {
7662         // Valid transitions for normal use-cases.
7663         switch (currentState) {
7664             case DevicePolicyManager.STATE_USER_UNMANAGED:
7665                 // Can move to any state from unmanaged (except itself as an edge case)..
7666                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
7667                     return;
7668                 }
7669                 break;
7670             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
7671             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
7672                 // Can only move to finalized from these states.
7673                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
7674                     return;
7675                 }
7676                 break;
7677             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
7678                 // Current user has a managed-profile, but current user is not managed, so
7679                 // rather than moving to finalized state, go back to unmanaged once
7680                 // profile provisioning is complete.
7681                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
7682                     return;
7683                 }
7684                 break;
7685             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
7686                 // Cannot transition out of finalized.
7687                 break;
7688         }
7689 
7690         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
7691         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
7692                 + "from state [" + currentState + "]");
7693     }
7694 
7695     @Override
setProfileEnabled(ComponentName who)7696     public void setProfileEnabled(ComponentName who) {
7697         if (!mHasFeature) {
7698             return;
7699         }
7700         Preconditions.checkNotNull(who, "ComponentName is null");
7701         synchronized (getLockObject()) {
7702             // Check if this is the profile owner who is calling
7703             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7704             final int userId = UserHandle.getCallingUserId();
7705             enforceManagedProfile(userId, "enable the profile");
7706             // Check if the profile is already enabled.
7707             UserInfo managedProfile = getUserInfo(userId);
7708             if (managedProfile.isEnabled()) {
7709                 Slog.e(LOG_TAG,
7710                         "setProfileEnabled is called when the profile is already enabled");
7711                 return;
7712             }
7713             long id = mInjector.binderClearCallingIdentity();
7714             try {
7715                 mUserManager.setUserEnabled(userId);
7716                 UserInfo parent = mUserManager.getProfileParent(userId);
7717                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
7718                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
7719                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
7720                         Intent.FLAG_RECEIVER_FOREGROUND);
7721                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
7722             } finally {
7723                 mInjector.binderRestoreCallingIdentity(id);
7724             }
7725         }
7726     }
7727 
7728     @Override
setProfileName(ComponentName who, String profileName)7729     public void setProfileName(ComponentName who, String profileName) {
7730         Preconditions.checkNotNull(who, "ComponentName is null");
7731         int userId = UserHandle.getCallingUserId();
7732         // Check if this is the profile owner (includes device owner).
7733         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7734 
7735         long id = mInjector.binderClearCallingIdentity();
7736         try {
7737             mUserManager.setUserName(userId, profileName);
7738         } finally {
7739             mInjector.binderRestoreCallingIdentity(id);
7740         }
7741     }
7742 
7743     @Override
getProfileOwner(int userHandle)7744     public ComponentName getProfileOwner(int userHandle) {
7745         if (!mHasFeature) {
7746             return null;
7747         }
7748 
7749         synchronized (getLockObject()) {
7750             return mOwners.getProfileOwnerComponent(userHandle);
7751         }
7752     }
7753 
7754     // Returns the active profile owner for this user or null if the current user has no
7755     // profile owner.
7756     @VisibleForTesting
getProfileOwnerAdminLocked(int userHandle)7757     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
7758         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
7759         if (profileOwner == null) {
7760             return null;
7761         }
7762         DevicePolicyData policy = getUserData(userHandle);
7763         final int n = policy.mAdminList.size();
7764         for (int i = 0; i < n; i++) {
7765             ActiveAdmin admin = policy.mAdminList.get(i);
7766             if (profileOwner.equals(admin.info.getComponent())) {
7767                 return admin;
7768             }
7769         }
7770         return null;
7771     }
7772 
7773     @Override
getProfileOwnerName(int userHandle)7774     public String getProfileOwnerName(int userHandle) {
7775         if (!mHasFeature) {
7776             return null;
7777         }
7778         enforceManageUsers();
7779         ComponentName profileOwner = getProfileOwner(userHandle);
7780         if (profileOwner == null) {
7781             return null;
7782         }
7783         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
7784     }
7785 
7786     /**
7787      * Canonical name for a given package.
7788      */
getApplicationLabel(String packageName, int userHandle)7789     private String getApplicationLabel(String packageName, int userHandle) {
7790         long token = mInjector.binderClearCallingIdentity();
7791         try {
7792             final Context userContext;
7793             try {
7794                 UserHandle handle = new UserHandle(userHandle);
7795                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
7796             } catch (PackageManager.NameNotFoundException nnfe) {
7797                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
7798                 return null;
7799             }
7800             ApplicationInfo appInfo = userContext.getApplicationInfo();
7801             CharSequence result = null;
7802             if (appInfo != null) {
7803                 result = appInfo.loadUnsafeLabel(userContext.getPackageManager());
7804             }
7805             return result != null ? result.toString() : null;
7806         } finally {
7807             mInjector.binderRestoreCallingIdentity(token);
7808         }
7809     }
7810 
7811     /**
7812      * Calls wtfStack() if called with the DPMS lock held.
7813      */
wtfIfInLock()7814     private void wtfIfInLock() {
7815         if (Thread.holdsLock(this)) {
7816             Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held");
7817         }
7818     }
7819 
7820     /**
7821      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7822      * permission.
7823      * The profile owner can only be set before the user setup phase has completed,
7824      * except for:
7825      * - SYSTEM_UID
7826      * - adb unless hasIncompatibleAccountsOrNonAdb is true.
7827      */
enforceCanSetProfileOwnerLocked(@ullable ComponentName owner, int userHandle, boolean hasIncompatibleAccountsOrNonAdb)7828     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle,
7829             boolean hasIncompatibleAccountsOrNonAdb) {
7830         UserInfo info = getUserInfo(userHandle);
7831         if (info == null) {
7832             // User doesn't exist.
7833             throw new IllegalArgumentException(
7834                     "Attempted to set profile owner for invalid userId: " + userHandle);
7835         }
7836         if (info.isGuest()) {
7837             throw new IllegalStateException("Cannot set a profile owner on a guest");
7838         }
7839         if (mOwners.hasProfileOwner(userHandle)) {
7840             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
7841                     + "is already set.");
7842         }
7843         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
7844             throw new IllegalStateException("Trying to set the profile owner, but the user "
7845                     + "already has a device owner.");
7846         }
7847         if (isAdb()) {
7848             if ((mIsWatch || hasUserSetupCompleted(userHandle))
7849                     && hasIncompatibleAccountsOrNonAdb) {
7850                 throw new IllegalStateException("Not allowed to set the profile owner because "
7851                         + "there are already some accounts on the profile");
7852             }
7853             return;
7854         }
7855         enforceCanManageProfileAndDeviceOwners();
7856         if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
7857             throw new IllegalStateException("Cannot set the profile owner on a user which is "
7858                     + "already set-up");
7859         }
7860     }
7861 
7862     /**
7863      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
7864      * permission.
7865      */
enforceCanSetDeviceOwnerLocked(@ullable ComponentName owner, int userId, boolean hasIncompatibleAccountsOrNonAdb)7866     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId,
7867             boolean hasIncompatibleAccountsOrNonAdb) {
7868         if (!isAdb()) {
7869             enforceCanManageProfileAndDeviceOwners();
7870         }
7871 
7872         final int code = checkDeviceOwnerProvisioningPreConditionLocked(
7873                 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb);
7874         switch (code) {
7875             case CODE_OK:
7876                 return;
7877             case CODE_HAS_DEVICE_OWNER:
7878                 throw new IllegalStateException(
7879                         "Trying to set the device owner, but device owner is already set.");
7880             case CODE_USER_HAS_PROFILE_OWNER:
7881                 throw new IllegalStateException("Trying to set the device owner, but the user "
7882                         + "already has a profile owner.");
7883             case CODE_USER_NOT_RUNNING:
7884                 throw new IllegalStateException("User not running: " + userId);
7885             case CODE_NOT_SYSTEM_USER:
7886                 throw new IllegalStateException("User is not system user");
7887             case CODE_USER_SETUP_COMPLETED:
7888                 throw new IllegalStateException(
7889                         "Cannot set the device owner if the device is already set-up");
7890             case CODE_NONSYSTEM_USER_EXISTS:
7891                 throw new IllegalStateException("Not allowed to set the device owner because there "
7892                         + "are already several users on the device");
7893             case CODE_ACCOUNTS_NOT_EMPTY:
7894                 throw new IllegalStateException("Not allowed to set the device owner because there "
7895                         + "are already some accounts on the device");
7896             case CODE_HAS_PAIRED:
7897                 throw new IllegalStateException("Not allowed to set the device owner because this "
7898                         + "device has already paired");
7899             default:
7900                 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code);
7901         }
7902     }
7903 
enforceUserUnlocked(int userId)7904     private void enforceUserUnlocked(int userId) {
7905         // Since we're doing this operation on behalf of an app, we only
7906         // want to use the actual "unlocked" state.
7907         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
7908                 "User must be running and unlocked");
7909     }
7910 
enforceUserUnlocked(@serIdInt int userId, boolean parent)7911     private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) {
7912         if (parent) {
7913             enforceUserUnlocked(getProfileParentId(userId));
7914         } else {
7915             enforceUserUnlocked(userId);
7916         }
7917     }
7918 
enforceManageUsers()7919     private void enforceManageUsers() {
7920         final int callingUid = mInjector.binderGetCallingUid();
7921         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
7922             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7923         }
7924     }
7925 
enforceFullCrossUsersPermission(int userHandle)7926     private void enforceFullCrossUsersPermission(int userHandle) {
7927         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7928                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
7929     }
7930 
enforceCrossUsersPermission(int userHandle)7931     private void enforceCrossUsersPermission(int userHandle) {
7932         enforceSystemUserOrPermissionIfCrossUser(userHandle,
7933                 android.Manifest.permission.INTERACT_ACROSS_USERS);
7934     }
7935 
enforceSystemUserOrPermission(String permission)7936     private void enforceSystemUserOrPermission(String permission) {
7937         if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) {
7938             mContext.enforceCallingOrSelfPermission(permission,
7939                     "Must be system or have " + permission + " permission");
7940         }
7941     }
7942 
enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission)7943     private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) {
7944         if (userHandle < 0) {
7945             throw new IllegalArgumentException("Invalid userId " + userHandle);
7946         }
7947         if (userHandle == mInjector.userHandleGetCallingUserId()) {
7948             return;
7949         }
7950         enforceSystemUserOrPermission(permission);
7951     }
7952 
enforceManagedProfile(int userHandle, String message)7953     private void enforceManagedProfile(int userHandle, String message) {
7954         if(!isManagedProfile(userHandle)) {
7955             throw new SecurityException("You can not " + message + " outside a managed profile.");
7956         }
7957     }
7958 
enforceNotManagedProfile(int userHandle, String message)7959     private void enforceNotManagedProfile(int userHandle, String message) {
7960         if(isManagedProfile(userHandle)) {
7961             throw new SecurityException("You can not " + message + " for a managed profile.");
7962         }
7963     }
7964 
enforceDeviceOwnerOrManageUsers()7965     private void enforceDeviceOwnerOrManageUsers() {
7966         synchronized (getLockObject()) {
7967             if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
7968                     mInjector.binderGetCallingUid()) != null) {
7969                 return;
7970             }
7971         }
7972         enforceManageUsers();
7973     }
7974 
enforceProfileOwnerOrSystemUser()7975     private void enforceProfileOwnerOrSystemUser() {
7976         synchronized (getLockObject()) {
7977             if (getActiveAdminWithPolicyForUidLocked(null,
7978                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7979                             != null) {
7980                 return;
7981             }
7982         }
7983         Preconditions.checkState(isCallerWithSystemUid(),
7984                 "Only profile owner, device owner and system may call this method.");
7985     }
7986 
enforceProfileOwnerOrFullCrossUsersPermission(int userId)7987     private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) {
7988         if (userId == mInjector.userHandleGetCallingUserId()) {
7989             synchronized (getLockObject()) {
7990                 if (getActiveAdminWithPolicyForUidLocked(null,
7991                         DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid())
7992                                 != null) {
7993                     // Device Owner/Profile Owner may access the user it runs on.
7994                     return;
7995                 }
7996             }
7997         }
7998         // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required.
7999         enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
8000     }
8001 
canUserUseLockTaskLocked(int userId)8002     private boolean canUserUseLockTaskLocked(int userId) {
8003         if (isUserAffiliatedWithDeviceLocked(userId)) {
8004             return true;
8005         }
8006 
8007         // Unaffiliated profile owners are not allowed to use lock when there is a device owner.
8008         if (mOwners.hasDeviceOwner()) {
8009             return false;
8010         }
8011 
8012         final ComponentName profileOwner = getProfileOwner(userId);
8013         if (profileOwner == null) {
8014             return false;
8015         }
8016 
8017         // Managed profiles are not allowed to use lock task
8018         if (isManagedProfile(userId)) {
8019             return false;
8020         }
8021 
8022         return true;
8023     }
8024 
enforceCanCallLockTaskLocked(ComponentName who)8025     private void enforceCanCallLockTaskLocked(ComponentName who) {
8026         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8027         final int userId =  mInjector.userHandleGetCallingUserId();
8028         if (!canUserUseLockTaskLocked(userId)) {
8029             throw new SecurityException("User " + userId + " is not allowed to use lock task");
8030         }
8031     }
8032 
ensureCallerPackage(@ullable String packageName)8033     private void ensureCallerPackage(@Nullable String packageName) {
8034         if (packageName == null) {
8035             Preconditions.checkState(isCallerWithSystemUid(),
8036                     "Only caller can omit package name");
8037         } else {
8038             final int callingUid = mInjector.binderGetCallingUid();
8039             final int userId = mInjector.userHandleGetCallingUserId();
8040             try {
8041                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
8042                         packageName, 0, userId);
8043                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
8044             } catch (RemoteException e) {
8045                 // Shouldn't happen
8046             }
8047         }
8048     }
8049 
isCallerWithSystemUid()8050     private boolean isCallerWithSystemUid() {
8051         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
8052     }
8053 
getProfileParentId(int userHandle)8054     protected int getProfileParentId(int userHandle) {
8055         final long ident = mInjector.binderClearCallingIdentity();
8056         try {
8057             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
8058             return parentUser != null ? parentUser.id : userHandle;
8059         } finally {
8060             mInjector.binderRestoreCallingIdentity(ident);
8061         }
8062     }
8063 
getCredentialOwner(int userHandle, boolean parent)8064     private int getCredentialOwner(int userHandle, boolean parent) {
8065         final long ident = mInjector.binderClearCallingIdentity();
8066         try {
8067             if (parent) {
8068                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
8069                 if (parentProfile != null) {
8070                     userHandle = parentProfile.id;
8071                 }
8072             }
8073             return mUserManager.getCredentialOwnerProfile(userHandle);
8074         } finally {
8075             mInjector.binderRestoreCallingIdentity(ident);
8076         }
8077     }
8078 
isManagedProfile(int userHandle)8079     private boolean isManagedProfile(int userHandle) {
8080         final UserInfo user = getUserInfo(userHandle);
8081         return user != null && user.isManagedProfile();
8082     }
8083 
enableIfNecessary(String packageName, int userId)8084     private void enableIfNecessary(String packageName, int userId) {
8085         try {
8086             final ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
8087                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS, userId);
8088             if (ai.enabledSetting
8089                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
8090                 mIPackageManager.setApplicationEnabledSetting(packageName,
8091                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
8092                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
8093             }
8094         } catch (RemoteException e) {
8095         }
8096     }
8097 
8098     @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)8099     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
8100         if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return;
8101 
8102         synchronized (getLockObject()) {
8103             pw.println("Current Device Policy Manager state:");
8104 
8105             mOwners.dump("  ", pw);
8106             mDeviceAdminServiceController.dump("  ", pw);
8107             int userCount = mUserData.size();
8108             for (int u = 0; u < userCount; u++) {
8109                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
8110                 pw.println();
8111                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
8112                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
8113                 final int N = policy.mAdminList.size();
8114                 for (int i=0; i<N; i++) {
8115                     ActiveAdmin ap = policy.mAdminList.get(i);
8116                     if (ap != null) {
8117                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
8118                                 pw.println(":");
8119                         ap.dump("      ", pw);
8120                     }
8121                 }
8122                 if (!policy.mRemovingAdmins.isEmpty()) {
8123                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
8124                             + policy.mRemovingAdmins);
8125                 }
8126 
8127                 pw.println(" ");
8128                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
8129             }
8130             pw.println();
8131             mConstants.dump("  ", pw);
8132             pw.println();
8133             mStatLogger.dump(pw, "  ");
8134             pw.println();
8135             pw.println("  Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
8136         }
8137     }
8138 
getEncryptionStatusName(int encryptionStatus)8139     private String getEncryptionStatusName(int encryptionStatus) {
8140         switch (encryptionStatus) {
8141             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
8142                 return "inactive";
8143             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
8144                 return "block default key";
8145             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
8146                 return "block";
8147             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
8148                 return "per-user";
8149             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
8150                 return "unsupported";
8151             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
8152                 return "activating";
8153             default:
8154                 return "unknown";
8155         }
8156     }
8157 
8158     @Override
addPersistentPreferredActivity(ComponentName who, IntentFilter filter, ComponentName activity)8159     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
8160             ComponentName activity) {
8161         Preconditions.checkNotNull(who, "ComponentName is null");
8162         final int userHandle = UserHandle.getCallingUserId();
8163         synchronized (getLockObject()) {
8164             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8165 
8166             long id = mInjector.binderClearCallingIdentity();
8167             try {
8168                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
8169                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8170             } catch (RemoteException re) {
8171                 // Shouldn't happen
8172             } finally {
8173                 mInjector.binderRestoreCallingIdentity(id);
8174             }
8175         }
8176     }
8177 
8178     @Override
clearPackagePersistentPreferredActivities(ComponentName who, String packageName)8179     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
8180         Preconditions.checkNotNull(who, "ComponentName is null");
8181         final int userHandle = UserHandle.getCallingUserId();
8182         synchronized (getLockObject()) {
8183             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8184 
8185             long id = mInjector.binderClearCallingIdentity();
8186             try {
8187                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
8188                 mIPackageManager.flushPackageRestrictionsAsUser(userHandle);
8189             } catch (RemoteException re) {
8190                 // Shouldn't happen
8191             } finally {
8192                 mInjector.binderRestoreCallingIdentity(id);
8193             }
8194         }
8195     }
8196 
8197     @Override
setDefaultSmsApplication(ComponentName admin, String packageName)8198     public void setDefaultSmsApplication(ComponentName admin, String packageName) {
8199         Preconditions.checkNotNull(admin, "ComponentName is null");
8200         synchronized (getLockObject()) {
8201             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8202         }
8203         mInjector.binderWithCleanCallingIdentity(() ->
8204                 SmsApplication.setDefaultApplication(packageName, mContext));
8205     }
8206 
8207     @Override
setApplicationRestrictionsManagingPackage(ComponentName admin, String packageName)8208     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
8209             String packageName) {
8210         try {
8211             setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS);
8212         } catch (IllegalArgumentException e) {
8213             return false;
8214         }
8215         return true;
8216     }
8217 
8218     @Override
getApplicationRestrictionsManagingPackage(ComponentName admin)8219     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
8220         final List<String> delegatePackages = getDelegatePackages(admin,
8221                 DELEGATION_APP_RESTRICTIONS);
8222         return delegatePackages.size() > 0 ? delegatePackages.get(0) : null;
8223     }
8224 
8225     @Override
isCallerApplicationRestrictionsManagingPackage(String callerPackage)8226     public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) {
8227         return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS);
8228     }
8229 
8230     @Override
setApplicationRestrictions(ComponentName who, String callerPackage, String packageName, Bundle settings)8231     public void setApplicationRestrictions(ComponentName who, String callerPackage,
8232             String packageName, Bundle settings) {
8233         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
8234                 DELEGATION_APP_RESTRICTIONS);
8235 
8236         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
8237         final long id = mInjector.binderClearCallingIdentity();
8238         try {
8239             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
8240         } finally {
8241             mInjector.binderRestoreCallingIdentity(id);
8242         }
8243     }
8244 
8245     @Override
setTrustAgentConfiguration(ComponentName admin, ComponentName agent, PersistableBundle args, boolean parent)8246     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
8247             PersistableBundle args, boolean parent) {
8248         if (!mHasFeature) {
8249             return;
8250         }
8251         Preconditions.checkNotNull(admin, "admin is null");
8252         Preconditions.checkNotNull(agent, "agent is null");
8253         final int userHandle = UserHandle.getCallingUserId();
8254         synchronized (getLockObject()) {
8255             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
8256                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
8257             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
8258             saveSettingsLocked(userHandle);
8259         }
8260     }
8261 
8262     @Override
getTrustAgentConfiguration(ComponentName admin, ComponentName agent, int userHandle, boolean parent)8263     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
8264             ComponentName agent, int userHandle, boolean parent) {
8265         if (!mHasFeature) {
8266             return null;
8267         }
8268         Preconditions.checkNotNull(agent, "agent null");
8269         enforceFullCrossUsersPermission(userHandle);
8270 
8271         synchronized (getLockObject()) {
8272             final String componentName = agent.flattenToString();
8273             if (admin != null) {
8274                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
8275                 if (ap == null) return null;
8276                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
8277                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
8278                 List<PersistableBundle> result = new ArrayList<>();
8279                 result.add(trustAgentInfo.options);
8280                 return result;
8281             }
8282 
8283             // Return strictest policy for this user and profiles that are visible from this user.
8284             List<PersistableBundle> result = null;
8285             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
8286             // of the options. If any admin doesn't have options, discard options for the rest
8287             // and return null.
8288             List<ActiveAdmin> admins =
8289                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
8290             boolean allAdminsHaveOptions = true;
8291             final int N = admins.size();
8292             for (int i = 0; i < N; i++) {
8293                 final ActiveAdmin active = admins.get(i);
8294 
8295                 final boolean disablesTrust = (active.disabledKeyguardFeatures
8296                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
8297                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
8298                 if (info != null && info.options != null && !info.options.isEmpty()) {
8299                     if (disablesTrust) {
8300                         if (result == null) {
8301                             result = new ArrayList<>();
8302                         }
8303                         result.add(info.options);
8304                     } else {
8305                         Log.w(LOG_TAG, "Ignoring admin " + active.info
8306                                 + " because it has trust options but doesn't declare "
8307                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
8308                     }
8309                 } else if (disablesTrust) {
8310                     allAdminsHaveOptions = false;
8311                     break;
8312                 }
8313             }
8314             return allAdminsHaveOptions ? result : null;
8315         }
8316     }
8317 
8318     @Override
setRestrictionsProvider(ComponentName who, ComponentName permissionProvider)8319     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
8320         Preconditions.checkNotNull(who, "ComponentName is null");
8321         synchronized (getLockObject()) {
8322             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8323 
8324             int userHandle = UserHandle.getCallingUserId();
8325             DevicePolicyData userData = getUserData(userHandle);
8326             userData.mRestrictionsProvider = permissionProvider;
8327             saveSettingsLocked(userHandle);
8328         }
8329     }
8330 
8331     @Override
getRestrictionsProvider(int userHandle)8332     public ComponentName getRestrictionsProvider(int userHandle) {
8333         synchronized (getLockObject()) {
8334             if (!isCallerWithSystemUid()) {
8335                 throw new SecurityException("Only the system can query the permission provider");
8336             }
8337             DevicePolicyData userData = getUserData(userHandle);
8338             return userData != null ? userData.mRestrictionsProvider : null;
8339         }
8340     }
8341 
8342     @Override
addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags)8343     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
8344         Preconditions.checkNotNull(who, "ComponentName is null");
8345         int callingUserId = UserHandle.getCallingUserId();
8346         synchronized (getLockObject()) {
8347             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8348 
8349             long id = mInjector.binderClearCallingIdentity();
8350             try {
8351                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
8352                 if (parent == null) {
8353                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
8354                             + "parent");
8355                     return;
8356                 }
8357                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
8358                     mIPackageManager.addCrossProfileIntentFilter(
8359                             filter, who.getPackageName(), callingUserId, parent.id, 0);
8360                 }
8361                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
8362                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
8363                             parent.id, callingUserId, 0);
8364                 }
8365             } catch (RemoteException re) {
8366                 // Shouldn't happen
8367             } finally {
8368                 mInjector.binderRestoreCallingIdentity(id);
8369             }
8370         }
8371     }
8372 
8373     @Override
clearCrossProfileIntentFilters(ComponentName who)8374     public void clearCrossProfileIntentFilters(ComponentName who) {
8375         Preconditions.checkNotNull(who, "ComponentName is null");
8376         int callingUserId = UserHandle.getCallingUserId();
8377         synchronized (getLockObject()) {
8378             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8379             long id = mInjector.binderClearCallingIdentity();
8380             try {
8381                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
8382                 if (parent == null) {
8383                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
8384                             + "parent");
8385                     return;
8386                 }
8387                 // Removing those that go from the managed profile to the parent.
8388                 mIPackageManager.clearCrossProfileIntentFilters(
8389                         callingUserId, who.getPackageName());
8390                 // And those that go from the parent to the managed profile.
8391                 // If we want to support multiple managed profiles, we will have to only remove
8392                 // those that have callingUserId as their target.
8393                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
8394             } catch (RemoteException re) {
8395                 // Shouldn't happen
8396             } finally {
8397                 mInjector.binderRestoreCallingIdentity(id);
8398             }
8399         }
8400     }
8401 
8402     /**
8403      * @return true if all packages in enabledPackages are either in the list
8404      * permittedList or are a system app.
8405      */
checkPackagesInPermittedListOrSystem(List<String> enabledPackages, List<String> permittedList, int userIdToCheck)8406     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
8407             List<String> permittedList, int userIdToCheck) {
8408         long id = mInjector.binderClearCallingIdentity();
8409         try {
8410             // If we have an enabled packages list for a managed profile the packages
8411             // we should check are installed for the parent user.
8412             UserInfo user = getUserInfo(userIdToCheck);
8413             if (user.isManagedProfile()) {
8414                 userIdToCheck = user.profileGroupId;
8415             }
8416 
8417             for (String enabledPackage : enabledPackages) {
8418                 boolean systemService = false;
8419                 try {
8420                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
8421                             enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES,
8422                             userIdToCheck);
8423                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
8424                 } catch (RemoteException e) {
8425                     Log.i(LOG_TAG, "Can't talk to package managed", e);
8426                 }
8427                 if (!systemService && !permittedList.contains(enabledPackage)) {
8428                     return false;
8429                 }
8430             }
8431         } finally {
8432             mInjector.binderRestoreCallingIdentity(id);
8433         }
8434         return true;
8435     }
8436 
getAccessibilityManagerForUser(int userId)8437     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
8438         // Not using AccessibilityManager.getInstance because that guesses
8439         // at the user you require based on callingUid and caches for a given
8440         // process.
8441         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
8442         IAccessibilityManager service = iBinder == null
8443                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
8444         return new AccessibilityManager(mContext, service, userId);
8445     }
8446 
8447     @Override
setPermittedAccessibilityServices(ComponentName who, List packageList)8448     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
8449         if (!mHasFeature) {
8450             return false;
8451         }
8452         Preconditions.checkNotNull(who, "ComponentName is null");
8453 
8454         if (packageList != null) {
8455             int userId = UserHandle.getCallingUserId();
8456             List<AccessibilityServiceInfo> enabledServices = null;
8457             long id = mInjector.binderClearCallingIdentity();
8458             try {
8459                 UserInfo user = getUserInfo(userId);
8460                 if (user.isManagedProfile()) {
8461                     userId = user.profileGroupId;
8462                 }
8463                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
8464                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
8465                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
8466             } finally {
8467                 mInjector.binderRestoreCallingIdentity(id);
8468             }
8469 
8470             if (enabledServices != null) {
8471                 List<String> enabledPackages = new ArrayList<String>();
8472                 for (AccessibilityServiceInfo service : enabledServices) {
8473                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
8474                 }
8475                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8476                         userId)) {
8477                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
8478                             + "because it contains already enabled accesibility services.");
8479                     return false;
8480                 }
8481             }
8482         }
8483 
8484         synchronized (getLockObject()) {
8485             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8486                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8487             admin.permittedAccessiblityServices = packageList;
8488             saveSettingsLocked(UserHandle.getCallingUserId());
8489         }
8490         return true;
8491     }
8492 
8493     @Override
getPermittedAccessibilityServices(ComponentName who)8494     public List getPermittedAccessibilityServices(ComponentName who) {
8495         if (!mHasFeature) {
8496             return null;
8497         }
8498         Preconditions.checkNotNull(who, "ComponentName is null");
8499 
8500         synchronized (getLockObject()) {
8501             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8502                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8503             return admin.permittedAccessiblityServices;
8504         }
8505     }
8506 
8507     @Override
getPermittedAccessibilityServicesForUser(int userId)8508     public List getPermittedAccessibilityServicesForUser(int userId) {
8509         if (!mHasFeature) {
8510             return null;
8511         }
8512         enforceManageUsers();
8513         synchronized (getLockObject()) {
8514             List<String> result = null;
8515             // If we have multiple profiles we return the intersection of the
8516             // permitted lists. This can happen in cases where we have a device
8517             // and profile owner.
8518             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8519             for (int profileId : profileIds) {
8520                 // Just loop though all admins, only device or profiles
8521                 // owners can have permitted lists set.
8522                 DevicePolicyData policy = getUserDataUnchecked(profileId);
8523                 final int N = policy.mAdminList.size();
8524                 for (int j = 0; j < N; j++) {
8525                     ActiveAdmin admin = policy.mAdminList.get(j);
8526                     List<String> fromAdmin = admin.permittedAccessiblityServices;
8527                     if (fromAdmin != null) {
8528                         if (result == null) {
8529                             result = new ArrayList<>(fromAdmin);
8530                         } else {
8531                             result.retainAll(fromAdmin);
8532                         }
8533                     }
8534                 }
8535             }
8536 
8537             // If we have a permitted list add all system accessibility services.
8538             if (result != null) {
8539                 long id = mInjector.binderClearCallingIdentity();
8540                 try {
8541                     UserInfo user = getUserInfo(userId);
8542                     if (user.isManagedProfile()) {
8543                         userId = user.profileGroupId;
8544                     }
8545                     AccessibilityManager accessibilityManager =
8546                             getAccessibilityManagerForUser(userId);
8547                     List<AccessibilityServiceInfo> installedServices =
8548                             accessibilityManager.getInstalledAccessibilityServiceList();
8549 
8550                     if (installedServices != null) {
8551                         for (AccessibilityServiceInfo service : installedServices) {
8552                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
8553                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8554                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8555                                 result.add(serviceInfo.packageName);
8556                             }
8557                         }
8558                     }
8559                 } finally {
8560                     mInjector.binderRestoreCallingIdentity(id);
8561                 }
8562             }
8563 
8564             return result;
8565         }
8566     }
8567 
8568     @Override
isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, int userHandle)8569     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
8570             int userHandle) {
8571         if (!mHasFeature) {
8572             return true;
8573         }
8574         Preconditions.checkNotNull(who, "ComponentName is null");
8575         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8576         if (!isCallerWithSystemUid()){
8577             throw new SecurityException(
8578                     "Only the system can query if an accessibility service is disabled by admin");
8579         }
8580         synchronized (getLockObject()) {
8581             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8582             if (admin == null) {
8583                 return false;
8584             }
8585             if (admin.permittedAccessiblityServices == null) {
8586                 return true;
8587             }
8588             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8589                     admin.permittedAccessiblityServices, userHandle);
8590         }
8591     }
8592 
checkCallerIsCurrentUserOrProfile()8593     private boolean checkCallerIsCurrentUserOrProfile() {
8594         final int callingUserId = UserHandle.getCallingUserId();
8595         final long token = mInjector.binderClearCallingIdentity();
8596         try {
8597             UserInfo currentUser;
8598             UserInfo callingUser = getUserInfo(callingUserId);
8599             try {
8600                 currentUser = mInjector.getIActivityManager().getCurrentUser();
8601             } catch (RemoteException e) {
8602                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
8603                 return false;
8604             }
8605 
8606             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
8607                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
8608                         + "of a user that isn't the foreground user.");
8609                 return false;
8610             }
8611             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
8612                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
8613                         + "of a user that isn't the foreground user.");
8614                 return false;
8615             }
8616         } finally {
8617             mInjector.binderRestoreCallingIdentity(token);
8618         }
8619         return true;
8620     }
8621 
8622     @Override
setPermittedInputMethods(ComponentName who, List packageList)8623     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
8624         if (!mHasFeature) {
8625             return false;
8626         }
8627         Preconditions.checkNotNull(who, "ComponentName is null");
8628 
8629         // TODO When InputMethodManager supports per user calls remove
8630         //      this restriction.
8631         if (!checkCallerIsCurrentUserOrProfile()) {
8632             return false;
8633         }
8634 
8635         final int callingUserId = mInjector.userHandleGetCallingUserId();
8636         if (packageList != null) {
8637             // InputMethodManager fetches input methods for current user.
8638             // So this can only be set when calling user is the current user
8639             // or parent is current user in case of managed profiles.
8640             InputMethodManager inputMethodManager =
8641                     mContext.getSystemService(InputMethodManager.class);
8642             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
8643 
8644             if (enabledImes != null) {
8645                 List<String> enabledPackages = new ArrayList<String>();
8646                 for (InputMethodInfo ime : enabledImes) {
8647                     enabledPackages.add(ime.getPackageName());
8648                 }
8649                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
8650                         callingUserId)) {
8651                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
8652                             + "because it contains already enabled input method.");
8653                     return false;
8654                 }
8655             }
8656         }
8657 
8658         synchronized (getLockObject()) {
8659             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8660                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8661             admin.permittedInputMethods = packageList;
8662             saveSettingsLocked(callingUserId);
8663         }
8664         return true;
8665     }
8666 
8667     @Override
getPermittedInputMethods(ComponentName who)8668     public List getPermittedInputMethods(ComponentName who) {
8669         if (!mHasFeature) {
8670             return null;
8671         }
8672         Preconditions.checkNotNull(who, "ComponentName is null");
8673 
8674         synchronized (getLockObject()) {
8675             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8676                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8677             return admin.permittedInputMethods;
8678         }
8679     }
8680 
8681     @Override
getPermittedInputMethodsForCurrentUser()8682     public List getPermittedInputMethodsForCurrentUser() {
8683         enforceManageUsers();
8684         UserInfo currentUser;
8685         try {
8686             currentUser = mInjector.getIActivityManager().getCurrentUser();
8687         } catch (RemoteException e) {
8688             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
8689             // Activity managed is dead, just allow all IMEs
8690             return null;
8691         }
8692 
8693         int userId = currentUser.id;
8694         synchronized (getLockObject()) {
8695             List<String> result = null;
8696             // If we have multiple profiles we return the intersection of the
8697             // permitted lists. This can happen in cases where we have a device
8698             // and profile owner.
8699             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
8700             for (int profileId : profileIds) {
8701                 // Just loop though all admins, only device or profiles
8702                 // owners can have permitted lists set.
8703                 DevicePolicyData policy = getUserDataUnchecked(profileId);
8704                 final int N = policy.mAdminList.size();
8705                 for (int j = 0; j < N; j++) {
8706                     ActiveAdmin admin = policy.mAdminList.get(j);
8707                     List<String> fromAdmin = admin.permittedInputMethods;
8708                     if (fromAdmin != null) {
8709                         if (result == null) {
8710                             result = new ArrayList<String>(fromAdmin);
8711                         } else {
8712                             result.retainAll(fromAdmin);
8713                         }
8714                     }
8715                 }
8716             }
8717 
8718             // If we have a permitted list add all system input methods.
8719             if (result != null) {
8720                 InputMethodManager inputMethodManager =
8721                         mContext.getSystemService(InputMethodManager.class);
8722                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
8723                 long id = mInjector.binderClearCallingIdentity();
8724                 try {
8725                     if (imes != null) {
8726                         for (InputMethodInfo ime : imes) {
8727                             ServiceInfo serviceInfo = ime.getServiceInfo();
8728                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
8729                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8730                                 result.add(serviceInfo.packageName);
8731                             }
8732                         }
8733                     }
8734                 } finally {
8735                     mInjector.binderRestoreCallingIdentity(id);
8736                 }
8737             }
8738             return result;
8739         }
8740     }
8741 
8742     @Override
isInputMethodPermittedByAdmin(ComponentName who, String packageName, int userHandle)8743     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
8744             int userHandle) {
8745         if (!mHasFeature) {
8746             return true;
8747         }
8748         Preconditions.checkNotNull(who, "ComponentName is null");
8749         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
8750         if (!isCallerWithSystemUid()) {
8751             throw new SecurityException(
8752                     "Only the system can query if an input method is disabled by admin");
8753         }
8754         synchronized (getLockObject()) {
8755             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8756             if (admin == null) {
8757                 return false;
8758             }
8759             if (admin.permittedInputMethods == null) {
8760                 return true;
8761             }
8762             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8763                     admin.permittedInputMethods, userHandle);
8764         }
8765     }
8766 
8767     @Override
setPermittedCrossProfileNotificationListeners( ComponentName who, List<String> packageList)8768     public boolean setPermittedCrossProfileNotificationListeners(
8769             ComponentName who, List<String> packageList) {
8770         if (!mHasFeature) {
8771             return false;
8772         }
8773         Preconditions.checkNotNull(who, "ComponentName is null");
8774 
8775         final int callingUserId = mInjector.userHandleGetCallingUserId();
8776         if (!isManagedProfile(callingUserId)) {
8777             return false;
8778         }
8779 
8780         synchronized (getLockObject()) {
8781             ActiveAdmin admin = getActiveAdminForCallerLocked(
8782                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8783             admin.permittedNotificationListeners = packageList;
8784             saveSettingsLocked(callingUserId);
8785         }
8786         return true;
8787     }
8788 
8789     @Override
getPermittedCrossProfileNotificationListeners(ComponentName who)8790     public List<String> getPermittedCrossProfileNotificationListeners(ComponentName who) {
8791         if (!mHasFeature) {
8792             return null;
8793         }
8794         Preconditions.checkNotNull(who, "ComponentName is null");
8795 
8796         synchronized (getLockObject()) {
8797             ActiveAdmin admin = getActiveAdminForCallerLocked(
8798                     who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8799             return admin.permittedNotificationListeners;
8800         }
8801     }
8802 
8803     @Override
isNotificationListenerServicePermitted(String packageName, int userId)8804     public boolean isNotificationListenerServicePermitted(String packageName, int userId) {
8805         if (!mHasFeature) {
8806             return true;
8807         }
8808 
8809         Preconditions.checkStringNotEmpty(packageName, "packageName is null or empty");
8810         if (!isCallerWithSystemUid()) {
8811             throw new SecurityException(
8812                     "Only the system can query if a notification listener service is permitted");
8813         }
8814         synchronized (getLockObject()) {
8815             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
8816             if (profileOwner == null || profileOwner.permittedNotificationListeners == null) {
8817                 return true;
8818             }
8819             return checkPackagesInPermittedListOrSystem(Collections.singletonList(packageName),
8820                     profileOwner.permittedNotificationListeners, userId);
8821 
8822         }
8823     }
8824 
maybeSendAdminEnabledBroadcastLocked(int userHandle)8825     private void maybeSendAdminEnabledBroadcastLocked(int userHandle) {
8826         DevicePolicyData policyData = getUserData(userHandle);
8827         if (policyData.mAdminBroadcastPending) {
8828             // Send the initialization data to profile owner and delete the data
8829             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
8830             boolean clearInitBundle = true;
8831             if (admin != null) {
8832                 PersistableBundle initBundle = policyData.mInitBundle;
8833                 clearInitBundle = sendAdminCommandLocked(admin,
8834                         DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
8835                         initBundle == null ? null : new Bundle(initBundle),
8836                         null /* result receiver */,
8837                         true /* send in foreground */);
8838             }
8839             if (clearInitBundle) {
8840                 // If there's no admin or we've successfully called the admin, clear the init bundle
8841                 // otherwise, keep it around
8842                 policyData.mInitBundle = null;
8843                 policyData.mAdminBroadcastPending = false;
8844                 saveSettingsLocked(userHandle);
8845             }
8846         }
8847     }
8848 
8849     @Override
createAndManageUser(ComponentName admin, String name, ComponentName profileOwner, PersistableBundle adminExtras, int flags)8850     public UserHandle createAndManageUser(ComponentName admin, String name,
8851             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
8852         Preconditions.checkNotNull(admin, "admin is null");
8853         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
8854         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
8855             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
8856                     + admin + " are not in the same package");
8857         }
8858         // Only allow the system user to use this method
8859         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
8860             throw new SecurityException("createAndManageUser was called from non-system user");
8861         }
8862         final boolean ephemeral = (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0;
8863         final boolean demo = (flags & DevicePolicyManager.MAKE_USER_DEMO) != 0
8864                 && UserManager.isDeviceInDemoMode(mContext);
8865         final boolean leaveAllSystemAppsEnabled = (flags & LEAVE_ALL_SYSTEM_APPS_ENABLED) != 0;
8866         final int targetSdkVersion;
8867 
8868         // Create user.
8869         UserHandle user = null;
8870         synchronized (getLockObject()) {
8871             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8872 
8873             final int callingUid = mInjector.binderGetCallingUid();
8874             final long id = mInjector.binderClearCallingIdentity();
8875             try {
8876                 targetSdkVersion = mInjector.getPackageManagerInternal().getUidTargetSdkVersion(
8877                         callingUid);
8878 
8879                 // Return detail error code for checks inside
8880                 // UserManagerService.createUserInternalUnchecked.
8881                 DeviceStorageMonitorInternal deviceStorageMonitorInternal =
8882                         LocalServices.getService(DeviceStorageMonitorInternal.class);
8883                 if (deviceStorageMonitorInternal.isMemoryLow()) {
8884                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
8885                         throw new ServiceSpecificException(
8886                                 UserManager.USER_OPERATION_ERROR_LOW_STORAGE, "low device storage");
8887                     } else {
8888                         return null;
8889                     }
8890                 }
8891                 if (!mUserManager.canAddMoreUsers()) {
8892                     if (targetSdkVersion >= Build.VERSION_CODES.P) {
8893                         throw new ServiceSpecificException(
8894                                 UserManager.USER_OPERATION_ERROR_MAX_USERS, "user limit reached");
8895                     } else {
8896                         return null;
8897                     }
8898                 }
8899 
8900                 int userInfoFlags = 0;
8901                 if (ephemeral) {
8902                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
8903                 }
8904                 if (demo) {
8905                     userInfoFlags |= UserInfo.FLAG_DEMO;
8906                 }
8907                 String[] disallowedPackages = null;
8908                 if (!leaveAllSystemAppsEnabled) {
8909                     disallowedPackages = mOverlayPackagesProvider.getNonRequiredApps(admin,
8910                             UserHandle.myUserId(), ACTION_PROVISION_MANAGED_USER).toArray(
8911                             new String[0]);
8912                 }
8913                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
8914                         userInfoFlags, disallowedPackages);
8915                 if (userInfo != null) {
8916                     user = userInfo.getUserHandle();
8917                 }
8918             } finally {
8919                 mInjector.binderRestoreCallingIdentity(id);
8920             }
8921         }
8922         if (user == null) {
8923             if (targetSdkVersion >= Build.VERSION_CODES.P) {
8924                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
8925                         "failed to create user");
8926             } else {
8927                 return null;
8928             }
8929         }
8930 
8931         final int userHandle = user.getIdentifier();
8932         final Intent intent = new Intent(DevicePolicyManager.ACTION_MANAGED_USER_CREATED)
8933                 .putExtra(Intent.EXTRA_USER_HANDLE, userHandle)
8934                 .putExtra(
8935                         DevicePolicyManager.EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED,
8936                         leaveAllSystemAppsEnabled)
8937                 .setPackage(getManagedProvisioningPackage(mContext))
8938                 .addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
8939         mContext.sendBroadcastAsUser(intent, UserHandle.SYSTEM);
8940 
8941         final long id = mInjector.binderClearCallingIdentity();
8942         try {
8943             final String adminPkg = admin.getPackageName();
8944             try {
8945                 // Install the profile owner if not present.
8946                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
8947                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle,
8948                             0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
8949                 }
8950             } catch (RemoteException e) {
8951                 // Does not happen, same process
8952             }
8953 
8954             // Set admin.
8955             setActiveAdmin(profileOwner, true, userHandle);
8956             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
8957             setProfileOwner(profileOwner, ownerName, userHandle);
8958 
8959             synchronized (getLockObject()) {
8960                 DevicePolicyData policyData = getUserData(userHandle);
8961                 policyData.mInitBundle = adminExtras;
8962                 policyData.mAdminBroadcastPending = true;
8963                 saveSettingsLocked(userHandle);
8964             }
8965 
8966             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
8967                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
8968                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
8969             }
8970 
8971             return user;
8972         } catch (Throwable re) {
8973             mUserManager.removeUser(userHandle);
8974             if (targetSdkVersion >= Build.VERSION_CODES.P) {
8975                 throw new ServiceSpecificException(UserManager.USER_OPERATION_ERROR_UNKNOWN,
8976                         re.getMessage());
8977             } else {
8978                 return null;
8979             }
8980         } finally {
8981             mInjector.binderRestoreCallingIdentity(id);
8982         }
8983     }
8984 
8985     @Override
removeUser(ComponentName who, UserHandle userHandle)8986     public boolean removeUser(ComponentName who, UserHandle userHandle) {
8987         Preconditions.checkNotNull(who, "ComponentName is null");
8988         Preconditions.checkNotNull(userHandle, "UserHandle is null");
8989 
8990         synchronized (getLockObject()) {
8991             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8992         }
8993 
8994         final int callingUserId = mInjector.userHandleGetCallingUserId();
8995         final long id = mInjector.binderClearCallingIdentity();
8996         try {
8997             String restriction = isManagedProfile(userHandle.getIdentifier())
8998                     ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE
8999                     : UserManager.DISALLOW_REMOVE_USER;
9000             if (isAdminAffectedByRestriction(who, restriction, callingUserId)) {
9001                 Log.w(LOG_TAG, "The device owner cannot remove a user because "
9002                         + restriction + " is enabled, and was not set by the device owner");
9003                 return false;
9004             }
9005             return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier());
9006         } finally {
9007             mInjector.binderRestoreCallingIdentity(id);
9008         }
9009     }
9010 
isAdminAffectedByRestriction( ComponentName admin, String userRestriction, int userId)9011     private boolean isAdminAffectedByRestriction(
9012             ComponentName admin, String userRestriction, int userId) {
9013         switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) {
9014             case UserManager.RESTRICTION_NOT_SET:
9015                 return false;
9016             case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER:
9017                 return !isDeviceOwner(admin, userId);
9018             case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER:
9019                 return !isProfileOwner(admin, userId);
9020             default:
9021                 return true;
9022         }
9023     }
9024 
9025     @Override
switchUser(ComponentName who, UserHandle userHandle)9026     public boolean switchUser(ComponentName who, UserHandle userHandle) {
9027         Preconditions.checkNotNull(who, "ComponentName is null");
9028 
9029         synchronized (getLockObject()) {
9030             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9031 
9032             long id = mInjector.binderClearCallingIdentity();
9033             try {
9034                 int userId = UserHandle.USER_SYSTEM;
9035                 if (userHandle != null) {
9036                     userId = userHandle.getIdentifier();
9037                 }
9038                 return mInjector.getIActivityManager().switchUser(userId);
9039             } catch (RemoteException e) {
9040                 Log.e(LOG_TAG, "Couldn't switch user", e);
9041                 return false;
9042             } finally {
9043                 mInjector.binderRestoreCallingIdentity(id);
9044             }
9045         }
9046     }
9047 
9048     @Override
startUserInBackground(ComponentName who, UserHandle userHandle)9049     public int startUserInBackground(ComponentName who, UserHandle userHandle) {
9050         Preconditions.checkNotNull(who, "ComponentName is null");
9051         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9052 
9053         synchronized (getLockObject()) {
9054             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9055         }
9056 
9057         final int userId = userHandle.getIdentifier();
9058         if (isManagedProfile(userId)) {
9059             Log.w(LOG_TAG, "Managed profile cannot be started in background");
9060             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9061         }
9062 
9063         final long id = mInjector.binderClearCallingIdentity();
9064         try {
9065             if (!mInjector.getActivityManagerInternal().canStartMoreUsers()) {
9066                 Log.w(LOG_TAG, "Cannot start more users in background");
9067                 return UserManager.USER_OPERATION_ERROR_MAX_RUNNING_USERS;
9068             }
9069 
9070             if (mInjector.getIActivityManager().startUserInBackground(userId)) {
9071                 return UserManager.USER_OPERATION_SUCCESS;
9072             } else {
9073                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9074             }
9075         } catch (RemoteException e) {
9076             // Same process, should not happen.
9077             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9078         } finally {
9079             mInjector.binderRestoreCallingIdentity(id);
9080         }
9081     }
9082 
9083     @Override
stopUser(ComponentName who, UserHandle userHandle)9084     public int stopUser(ComponentName who, UserHandle userHandle) {
9085         Preconditions.checkNotNull(who, "ComponentName is null");
9086         Preconditions.checkNotNull(userHandle, "UserHandle is null");
9087 
9088         synchronized (getLockObject()) {
9089             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9090         }
9091 
9092         final int userId = userHandle.getIdentifier();
9093         if (isManagedProfile(userId)) {
9094             Log.w(LOG_TAG, "Managed profile cannot be stopped");
9095             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9096         }
9097 
9098         return stopUserUnchecked(userId);
9099     }
9100 
9101     @Override
logoutUser(ComponentName who)9102     public int logoutUser(ComponentName who) {
9103         Preconditions.checkNotNull(who, "ComponentName is null");
9104 
9105         final int callingUserId = mInjector.userHandleGetCallingUserId();
9106         synchronized (getLockObject()) {
9107             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9108             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9109                 throw new SecurityException("Admin " + who +
9110                         " is neither the device owner or affiliated user's profile owner.");
9111             }
9112         }
9113 
9114         if (isManagedProfile(callingUserId)) {
9115             Log.w(LOG_TAG, "Managed profile cannot be logout");
9116             return UserManager.USER_OPERATION_ERROR_MANAGED_PROFILE;
9117         }
9118 
9119         final long id = mInjector.binderClearCallingIdentity();
9120         try {
9121             if (!mInjector.getIActivityManager().switchUser(UserHandle.USER_SYSTEM)) {
9122                 Log.w(LOG_TAG, "Failed to switch to primary user");
9123                 // This should never happen as target user is UserHandle.USER_SYSTEM
9124                 return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9125             }
9126         } catch (RemoteException e) {
9127             // Same process, should not happen.
9128             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9129         } finally {
9130             mInjector.binderRestoreCallingIdentity(id);
9131         }
9132 
9133         return stopUserUnchecked(callingUserId);
9134     }
9135 
stopUserUnchecked(int userId)9136     private int stopUserUnchecked(int userId) {
9137         final long id = mInjector.binderClearCallingIdentity();
9138         try {
9139             switch (mInjector.getIActivityManager().stopUser(userId, true /*force*/, null)) {
9140                 case ActivityManager.USER_OP_SUCCESS:
9141                     return UserManager.USER_OPERATION_SUCCESS;
9142                 case ActivityManager.USER_OP_IS_CURRENT:
9143                     return UserManager.USER_OPERATION_ERROR_CURRENT_USER;
9144                 default:
9145                     return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9146             }
9147         } catch (RemoteException e) {
9148             // Same process, should not happen.
9149             return UserManager.USER_OPERATION_ERROR_UNKNOWN;
9150         } finally {
9151             mInjector.binderRestoreCallingIdentity(id);
9152         }
9153     }
9154 
9155     @Override
getSecondaryUsers(ComponentName who)9156     public List<UserHandle> getSecondaryUsers(ComponentName who) {
9157         Preconditions.checkNotNull(who, "ComponentName is null");
9158         synchronized (getLockObject()) {
9159             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9160         }
9161 
9162         final long id = mInjector.binderClearCallingIdentity();
9163         try {
9164             final List<UserInfo> userInfos = mInjector.getUserManager().getUsers(true
9165                     /*excludeDying*/);
9166             final List<UserHandle> userHandles = new ArrayList<>();
9167             for (UserInfo userInfo : userInfos) {
9168                 UserHandle userHandle = userInfo.getUserHandle();
9169                 if (!userHandle.isSystem() && !isManagedProfile(userHandle.getIdentifier())) {
9170                     userHandles.add(userInfo.getUserHandle());
9171                 }
9172             }
9173             return userHandles;
9174         } finally {
9175             mInjector.binderRestoreCallingIdentity(id);
9176         }
9177     }
9178 
9179     @Override
isEphemeralUser(ComponentName who)9180     public boolean isEphemeralUser(ComponentName who) {
9181         Preconditions.checkNotNull(who, "ComponentName is null");
9182         synchronized (getLockObject()) {
9183             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9184         }
9185 
9186         final int callingUserId = mInjector.userHandleGetCallingUserId();
9187         final long id = mInjector.binderClearCallingIdentity();
9188         try {
9189             return mInjector.getUserManager().isUserEphemeral(callingUserId);
9190         } finally {
9191             mInjector.binderRestoreCallingIdentity(id);
9192         }
9193     }
9194 
9195     @Override
getApplicationRestrictions(ComponentName who, String callerPackage, String packageName)9196     public Bundle getApplicationRestrictions(ComponentName who, String callerPackage,
9197             String packageName) {
9198         enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9199                 DELEGATION_APP_RESTRICTIONS);
9200 
9201         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
9202         final long id = mInjector.binderClearCallingIdentity();
9203         try {
9204            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
9205            // if no restrictions were saved, mUserManager.getApplicationRestrictions
9206            // returns null, but DPM method should return an empty Bundle as per JavaDoc
9207            return bundle != null ? bundle : Bundle.EMPTY;
9208         } finally {
9209             mInjector.binderRestoreCallingIdentity(id);
9210         }
9211     }
9212 
9213     @Override
setPackagesSuspended(ComponentName who, String callerPackage, String[] packageNames, boolean suspended)9214     public String[] setPackagesSuspended(ComponentName who, String callerPackage,
9215             String[] packageNames, boolean suspended) {
9216         int callingUserId = UserHandle.getCallingUserId();
9217         synchronized (getLockObject()) {
9218             // Ensure the caller is a DO/PO or a package access delegate.
9219             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9220                     DELEGATION_PACKAGE_ACCESS);
9221 
9222             long id = mInjector.binderClearCallingIdentity();
9223             try {
9224                 return mIPackageManager.setPackagesSuspendedAsUser(packageNames, suspended,
9225                         null, null, null, PLATFORM_PACKAGE_NAME, callingUserId);
9226             } catch (RemoteException re) {
9227                 // Shouldn't happen.
9228                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9229             } finally {
9230                 mInjector.binderRestoreCallingIdentity(id);
9231             }
9232             return packageNames;
9233         }
9234     }
9235 
9236     @Override
isPackageSuspended(ComponentName who, String callerPackage, String packageName)9237     public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) {
9238         int callingUserId = UserHandle.getCallingUserId();
9239         synchronized (getLockObject()) {
9240             // Ensure the caller is a DO/PO or a package access delegate.
9241             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9242                     DELEGATION_PACKAGE_ACCESS);
9243 
9244             long id = mInjector.binderClearCallingIdentity();
9245             try {
9246                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
9247             } catch (RemoteException re) {
9248                 // Shouldn't happen.
9249                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
9250             } finally {
9251                 mInjector.binderRestoreCallingIdentity(id);
9252             }
9253             return false;
9254         }
9255     }
9256 
9257     @Override
setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner)9258     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
9259         Preconditions.checkNotNull(who, "ComponentName is null");
9260         if (!UserRestrictionsUtils.isValidRestriction(key)) {
9261             return;
9262         }
9263 
9264         final int userHandle = mInjector.userHandleGetCallingUserId();
9265         synchronized (getLockObject()) {
9266             final ActiveAdmin activeAdmin =
9267                     getActiveAdminForCallerLocked(who,
9268                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9269             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
9270             if (isDeviceOwner) {
9271                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
9272                     throw new SecurityException("Device owner cannot set user restriction " + key);
9273                 }
9274             } else { // profile owner
9275                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
9276                     throw new SecurityException("Profile owner cannot set user restriction " + key);
9277                 }
9278             }
9279 
9280             // Save the restriction to ActiveAdmin.
9281             final Bundle restrictions = activeAdmin.ensureUserRestrictions();
9282             if (enabledFromThisOwner) {
9283                 restrictions.putBoolean(key, true);
9284             } else {
9285                 restrictions.remove(key);
9286             }
9287             saveUserRestrictionsLocked(userHandle);
9288         }
9289         if (SecurityLog.isLoggingEnabled()) {
9290             final int eventTag = enabledFromThisOwner
9291                     ? SecurityLog.TAG_USER_RESTRICTION_ADDED
9292                     : SecurityLog.TAG_USER_RESTRICTION_REMOVED;
9293             SecurityLog.writeEvent(eventTag, who.getPackageName(), userHandle, key);
9294         }
9295     }
9296 
saveUserRestrictionsLocked(int userId)9297     private void saveUserRestrictionsLocked(int userId) {
9298         saveSettingsLocked(userId);
9299         pushUserRestrictions(userId);
9300         sendChangedNotification(userId);
9301     }
9302 
pushUserRestrictions(int userId)9303     private void pushUserRestrictions(int userId) {
9304         synchronized (getLockObject()) {
9305             final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId);
9306             final Bundle userRestrictions;
9307             // Whether device owner enforces camera restriction.
9308             boolean disallowCameraGlobally = false;
9309 
9310             if (isDeviceOwner) {
9311                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
9312                 if (deviceOwner == null) {
9313                     return; // Shouldn't happen.
9314                 }
9315                 userRestrictions = deviceOwner.userRestrictions;
9316                 // DO can disable camera globally.
9317                 disallowCameraGlobally = deviceOwner.disableCamera;
9318             } else {
9319                 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
9320                 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null;
9321             }
9322 
9323             // Whether any admin enforces camera restriction.
9324             final int cameraRestrictionScope =
9325                     getCameraRestrictionScopeLocked(userId, disallowCameraGlobally);
9326 
9327             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions,
9328                     isDeviceOwner, cameraRestrictionScope);
9329         }
9330     }
9331 
9332     /**
9333      * Get the scope of camera restriction for a given user if any.
9334      */
getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally)9335     private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) {
9336         if (disallowCameraGlobally) {
9337             return UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
9338         } else if (getCameraDisabled(
9339                 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) {
9340             return UserManagerInternal.CAMERA_DISABLED_LOCALLY;
9341         }
9342         return UserManagerInternal.CAMERA_NOT_DISABLED;
9343     }
9344 
9345     @Override
getUserRestrictions(ComponentName who)9346     public Bundle getUserRestrictions(ComponentName who) {
9347         if (!mHasFeature) {
9348             return null;
9349         }
9350         Preconditions.checkNotNull(who, "ComponentName is null");
9351         synchronized (getLockObject()) {
9352             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
9353                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9354             return activeAdmin.userRestrictions;
9355         }
9356     }
9357 
9358     @Override
setApplicationHidden(ComponentName who, String callerPackage, String packageName, boolean hidden)9359     public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName,
9360             boolean hidden) {
9361         int callingUserId = UserHandle.getCallingUserId();
9362         synchronized (getLockObject()) {
9363             // Ensure the caller is a DO/PO or a package access delegate.
9364             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9365                     DELEGATION_PACKAGE_ACCESS);
9366 
9367             long id = mInjector.binderClearCallingIdentity();
9368             try {
9369                 return mIPackageManager.setApplicationHiddenSettingAsUser(
9370                         packageName, hidden, callingUserId);
9371             } catch (RemoteException re) {
9372                 // shouldn't happen
9373                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
9374             } finally {
9375                 mInjector.binderRestoreCallingIdentity(id);
9376             }
9377             return false;
9378         }
9379     }
9380 
9381     @Override
isApplicationHidden(ComponentName who, String callerPackage, String packageName)9382     public boolean isApplicationHidden(ComponentName who, String callerPackage,
9383             String packageName) {
9384         int callingUserId = UserHandle.getCallingUserId();
9385         synchronized (getLockObject()) {
9386             // Ensure the caller is a DO/PO or a package access delegate.
9387             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9388                     DELEGATION_PACKAGE_ACCESS);
9389 
9390             long id = mInjector.binderClearCallingIdentity();
9391             try {
9392                 return mIPackageManager.getApplicationHiddenSettingAsUser(
9393                         packageName, callingUserId);
9394             } catch (RemoteException re) {
9395                 // shouldn't happen
9396                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
9397             } finally {
9398                 mInjector.binderRestoreCallingIdentity(id);
9399             }
9400             return false;
9401         }
9402     }
9403 
9404     @Override
enableSystemApp(ComponentName who, String callerPackage, String packageName)9405     public void enableSystemApp(ComponentName who, String callerPackage, String packageName) {
9406         synchronized (getLockObject()) {
9407             // Ensure the caller is a DO/PO or an enable system app delegate.
9408             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9409                     DELEGATION_ENABLE_SYSTEM_APP);
9410 
9411             final boolean isDemo = isCurrentUserDemo();
9412 
9413             int userId = UserHandle.getCallingUserId();
9414             long id = mInjector.binderClearCallingIdentity();
9415 
9416             try {
9417                 if (VERBOSE_LOG) {
9418                     Slog.v(LOG_TAG, "installing " + packageName + " for "
9419                             + userId);
9420                 }
9421 
9422                 int parentUserId = getProfileParentId(userId);
9423                 if (!isDemo && !isSystemApp(mIPackageManager, packageName, parentUserId)) {
9424                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
9425                 }
9426 
9427                 // Install the app.
9428                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
9429                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9430                 if (isDemo) {
9431                     // Ensure the app is also ENABLED for demo users.
9432                     mIPackageManager.setApplicationEnabledSetting(packageName,
9433                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
9434                             PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
9435                 }
9436             } catch (RemoteException re) {
9437                 // shouldn't happen
9438                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
9439             } finally {
9440                 mInjector.binderRestoreCallingIdentity(id);
9441             }
9442         }
9443     }
9444 
9445     @Override
enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent)9446     public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) {
9447         synchronized (getLockObject()) {
9448             // Ensure the caller is a DO/PO or an enable system app delegate.
9449             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9450                     DELEGATION_ENABLE_SYSTEM_APP);
9451 
9452             int userId = UserHandle.getCallingUserId();
9453             long id = mInjector.binderClearCallingIdentity();
9454 
9455             try {
9456                 int parentUserId = getProfileParentId(userId);
9457                 List<ResolveInfo> activitiesToEnable = mIPackageManager
9458                         .queryIntentActivities(intent,
9459                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
9460                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
9461                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
9462                                 parentUserId)
9463                         .getList();
9464 
9465                 if (VERBOSE_LOG) {
9466                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
9467                 }
9468                 int numberOfAppsInstalled = 0;
9469                 if (activitiesToEnable != null) {
9470                     for (ResolveInfo info : activitiesToEnable) {
9471                         if (info.activityInfo != null) {
9472                             String packageName = info.activityInfo.packageName;
9473                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
9474                                 numberOfAppsInstalled++;
9475                                 mIPackageManager.installExistingPackageAsUser(packageName, userId,
9476                                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY);
9477                             } else {
9478                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
9479                                         + " system app");
9480                             }
9481                         }
9482                     }
9483                 }
9484                 return numberOfAppsInstalled;
9485             } catch (RemoteException e) {
9486                 // shouldn't happen
9487                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
9488                 return 0;
9489             } finally {
9490                 mInjector.binderRestoreCallingIdentity(id);
9491             }
9492         }
9493     }
9494 
isSystemApp(IPackageManager pm, String packageName, int userId)9495     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
9496             throws RemoteException {
9497         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES,
9498                 userId);
9499         if (appInfo == null) {
9500             throw new IllegalArgumentException("The application " + packageName +
9501                     " is not present on this device");
9502         }
9503         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
9504     }
9505 
9506     @Override
installExistingPackage(ComponentName who, String callerPackage, String packageName)9507     public boolean installExistingPackage(ComponentName who, String callerPackage,
9508             String packageName) {
9509         synchronized (getLockObject()) {
9510             // Ensure the caller is a PO or an install existing package delegate
9511             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9512                     DELEGATION_INSTALL_EXISTING_PACKAGE);
9513             final int callingUserId = mInjector.userHandleGetCallingUserId();
9514             if (!isUserAffiliatedWithDeviceLocked(callingUserId)) {
9515                 throw new SecurityException("Admin " + who +
9516                         " is neither the device owner or affiliated user's profile owner.");
9517             }
9518 
9519             final long id = mInjector.binderClearCallingIdentity();
9520             try {
9521                 if (VERBOSE_LOG) {
9522                     Slog.v(LOG_TAG, "installing " + packageName + " for "
9523                             + callingUserId);
9524                 }
9525 
9526                 // Install the package.
9527                 return mIPackageManager.installExistingPackageAsUser(packageName, callingUserId,
9528                         0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY)
9529                         == PackageManager.INSTALL_SUCCEEDED;
9530             } catch (RemoteException re) {
9531                 // shouldn't happen
9532                 return false;
9533             } finally {
9534                 mInjector.binderRestoreCallingIdentity(id);
9535             }
9536         }
9537     }
9538 
9539     @Override
setAccountManagementDisabled(ComponentName who, String accountType, boolean disabled)9540     public void setAccountManagementDisabled(ComponentName who, String accountType,
9541             boolean disabled) {
9542         if (!mHasFeature) {
9543             return;
9544         }
9545         Preconditions.checkNotNull(who, "ComponentName is null");
9546         synchronized (getLockObject()) {
9547             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
9548                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9549             if (disabled) {
9550                 ap.accountTypesWithManagementDisabled.add(accountType);
9551             } else {
9552                 ap.accountTypesWithManagementDisabled.remove(accountType);
9553             }
9554             saveSettingsLocked(UserHandle.getCallingUserId());
9555         }
9556     }
9557 
9558     @Override
getAccountTypesWithManagementDisabled()9559     public String[] getAccountTypesWithManagementDisabled() {
9560         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
9561     }
9562 
9563     @Override
getAccountTypesWithManagementDisabledAsUser(int userId)9564     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
9565         enforceFullCrossUsersPermission(userId);
9566         if (!mHasFeature) {
9567             return null;
9568         }
9569         synchronized (getLockObject()) {
9570             DevicePolicyData policy = getUserData(userId);
9571             final int N = policy.mAdminList.size();
9572             ArraySet<String> resultSet = new ArraySet<>();
9573             for (int i = 0; i < N; i++) {
9574                 ActiveAdmin admin = policy.mAdminList.get(i);
9575                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
9576             }
9577             return resultSet.toArray(new String[resultSet.size()]);
9578         }
9579     }
9580 
9581     @Override
setUninstallBlocked(ComponentName who, String callerPackage, String packageName, boolean uninstallBlocked)9582     public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName,
9583             boolean uninstallBlocked) {
9584         final int userId = UserHandle.getCallingUserId();
9585         synchronized (getLockObject()) {
9586             // Ensure the caller is a DO/PO or a block uninstall delegate
9587             enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
9588                     DELEGATION_BLOCK_UNINSTALL);
9589 
9590             long id = mInjector.binderClearCallingIdentity();
9591             try {
9592                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
9593             } catch (RemoteException re) {
9594                 // Shouldn't happen.
9595                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
9596             } finally {
9597                 mInjector.binderRestoreCallingIdentity(id);
9598             }
9599         }
9600     }
9601 
9602     @Override
isUninstallBlocked(ComponentName who, String packageName)9603     public boolean isUninstallBlocked(ComponentName who, String packageName) {
9604         // This function should return true if and only if the package is blocked by
9605         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
9606         // when the package is a system app, or when it is an active device admin.
9607         final int userId = UserHandle.getCallingUserId();
9608 
9609         synchronized (getLockObject()) {
9610             if (who != null) {
9611                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9612             }
9613 
9614             long id = mInjector.binderClearCallingIdentity();
9615             try {
9616                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
9617             } catch (RemoteException re) {
9618                 // Shouldn't happen.
9619                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
9620             } finally {
9621                 mInjector.binderRestoreCallingIdentity(id);
9622             }
9623         }
9624         return false;
9625     }
9626 
9627     @Override
setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled)9628     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
9629         if (!mHasFeature) {
9630             return;
9631         }
9632         Preconditions.checkNotNull(who, "ComponentName is null");
9633         synchronized (getLockObject()) {
9634             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9635                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9636             if (admin.disableCallerId != disabled) {
9637                 admin.disableCallerId = disabled;
9638                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9639             }
9640         }
9641     }
9642 
9643     @Override
getCrossProfileCallerIdDisabled(ComponentName who)9644     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
9645         if (!mHasFeature) {
9646             return false;
9647         }
9648         Preconditions.checkNotNull(who, "ComponentName is null");
9649         synchronized (getLockObject()) {
9650             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9651                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9652             return admin.disableCallerId;
9653         }
9654     }
9655 
9656     @Override
getCrossProfileCallerIdDisabledForUser(int userId)9657     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
9658         enforceCrossUsersPermission(userId);
9659         synchronized (getLockObject()) {
9660             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9661             return (admin != null) ? admin.disableCallerId : false;
9662         }
9663     }
9664 
9665     @Override
setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled)9666     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
9667         if (!mHasFeature) {
9668             return;
9669         }
9670         Preconditions.checkNotNull(who, "ComponentName is null");
9671         synchronized (getLockObject()) {
9672             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9673                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9674             if (admin.disableContactsSearch != disabled) {
9675                 admin.disableContactsSearch = disabled;
9676                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
9677             }
9678         }
9679     }
9680 
9681     @Override
getCrossProfileContactsSearchDisabled(ComponentName who)9682     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
9683         if (!mHasFeature) {
9684             return false;
9685         }
9686         Preconditions.checkNotNull(who, "ComponentName is null");
9687         synchronized (getLockObject()) {
9688             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9689                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9690             return admin.disableContactsSearch;
9691         }
9692     }
9693 
9694     @Override
getCrossProfileContactsSearchDisabledForUser(int userId)9695     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
9696         enforceCrossUsersPermission(userId);
9697         synchronized (getLockObject()) {
9698             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9699             return (admin != null) ? admin.disableContactsSearch : false;
9700         }
9701     }
9702 
9703     @Override
startManagedQuickContact(String actualLookupKey, long actualContactId, boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent)9704     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
9705             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
9706         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
9707                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
9708         final int callingUserId = UserHandle.getCallingUserId();
9709 
9710         final long ident = mInjector.binderClearCallingIdentity();
9711         try {
9712             synchronized (getLockObject()) {
9713                 final int managedUserId = getManagedUserId(callingUserId);
9714                 if (managedUserId < 0) {
9715                     return;
9716                 }
9717                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
9718                     if (VERBOSE_LOG) {
9719                         Log.v(LOG_TAG,
9720                                 "Cross-profile contacts access disabled for user " + managedUserId);
9721                     }
9722                     return;
9723                 }
9724                 ContactsInternal.startQuickContactWithErrorToastForUser(
9725                         mContext, intent, new UserHandle(managedUserId));
9726             }
9727         } finally {
9728             mInjector.binderRestoreCallingIdentity(ident);
9729         }
9730     }
9731 
9732     /**
9733      * @return true if cross-profile QuickContact is disabled
9734      */
isCrossProfileQuickContactDisabled(int userId)9735     private boolean isCrossProfileQuickContactDisabled(int userId) {
9736         return getCrossProfileCallerIdDisabledForUser(userId)
9737                 && getCrossProfileContactsSearchDisabledForUser(userId);
9738     }
9739 
9740     /**
9741      * @return the user ID of the managed user that is linked to the current user, if any.
9742      * Otherwise -1.
9743      */
getManagedUserId(int callingUserId)9744     public int getManagedUserId(int callingUserId) {
9745         if (VERBOSE_LOG) {
9746             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
9747         }
9748 
9749         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
9750             if (ui.id == callingUserId || !ui.isManagedProfile()) {
9751                 continue; // Caller user self, or not a managed profile.  Skip.
9752             }
9753             if (VERBOSE_LOG) {
9754                 Log.v(LOG_TAG, "Managed user=" + ui.id);
9755             }
9756             return ui.id;
9757         }
9758         if (VERBOSE_LOG) {
9759             Log.v(LOG_TAG, "Managed user not found.");
9760         }
9761         return -1;
9762     }
9763 
9764     @Override
setBluetoothContactSharingDisabled(ComponentName who, boolean disabled)9765     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
9766         if (!mHasFeature) {
9767             return;
9768         }
9769         Preconditions.checkNotNull(who, "ComponentName is null");
9770         synchronized (getLockObject()) {
9771             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9772                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9773             if (admin.disableBluetoothContactSharing != disabled) {
9774                 admin.disableBluetoothContactSharing = disabled;
9775                 saveSettingsLocked(UserHandle.getCallingUserId());
9776             }
9777         }
9778     }
9779 
9780     @Override
getBluetoothContactSharingDisabled(ComponentName who)9781     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
9782         if (!mHasFeature) {
9783             return false;
9784         }
9785         Preconditions.checkNotNull(who, "ComponentName is null");
9786         synchronized (getLockObject()) {
9787             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9788                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9789             return admin.disableBluetoothContactSharing;
9790         }
9791     }
9792 
9793     @Override
getBluetoothContactSharingDisabledForUser(int userId)9794     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
9795         // TODO: Should there be a check to make sure this relationship is
9796         // within a profile group?
9797         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
9798         synchronized (getLockObject()) {
9799             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
9800             return (admin != null) ? admin.disableBluetoothContactSharing : false;
9801         }
9802     }
9803 
9804     @Override
setLockTaskPackages(ComponentName who, String[] packages)9805     public void setLockTaskPackages(ComponentName who, String[] packages)
9806             throws SecurityException {
9807         Preconditions.checkNotNull(who, "ComponentName is null");
9808         Preconditions.checkNotNull(packages, "packages is null");
9809 
9810         synchronized (getLockObject()) {
9811             enforceCanCallLockTaskLocked(who);
9812             final int userHandle = mInjector.userHandleGetCallingUserId();
9813             setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
9814         }
9815     }
9816 
setLockTaskPackagesLocked(int userHandle, List<String> packages)9817     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
9818         DevicePolicyData policy = getUserData(userHandle);
9819         policy.mLockTaskPackages = packages;
9820 
9821         // Store the settings persistently.
9822         saveSettingsLocked(userHandle);
9823         updateLockTaskPackagesLocked(packages, userHandle);
9824     }
9825 
9826     @Override
getLockTaskPackages(ComponentName who)9827     public String[] getLockTaskPackages(ComponentName who) {
9828         Preconditions.checkNotNull(who, "ComponentName is null");
9829 
9830         final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
9831         synchronized (getLockObject()) {
9832             enforceCanCallLockTaskLocked(who);
9833             final List<String> packages = getUserData(userHandle).mLockTaskPackages;
9834             return packages.toArray(new String[packages.size()]);
9835         }
9836     }
9837 
9838     @Override
isLockTaskPermitted(String pkg)9839     public boolean isLockTaskPermitted(String pkg) {
9840         final int userHandle = mInjector.userHandleGetCallingUserId();
9841         synchronized (getLockObject()) {
9842             return getUserData(userHandle).mLockTaskPackages.contains(pkg);
9843         }
9844     }
9845 
9846     @Override
setLockTaskFeatures(ComponentName who, int flags)9847     public void setLockTaskFeatures(ComponentName who, int flags) {
9848         Preconditions.checkNotNull(who, "ComponentName is null");
9849 
9850         // Throw if Overview is used without Home.
9851         boolean hasHome = (flags & LOCK_TASK_FEATURE_HOME) != 0;
9852         boolean hasOverview = (flags & LOCK_TASK_FEATURE_OVERVIEW) != 0;
9853         Preconditions.checkArgument(hasHome || !hasOverview,
9854                 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME");
9855         boolean hasNotification = (flags & LOCK_TASK_FEATURE_NOTIFICATIONS) != 0;
9856         Preconditions.checkArgument(hasHome || !hasNotification,
9857             "Cannot use LOCK_TASK_FEATURE_NOTIFICATIONS without LOCK_TASK_FEATURE_HOME");
9858 
9859         final int userHandle = mInjector.userHandleGetCallingUserId();
9860         synchronized (getLockObject()) {
9861             enforceCanCallLockTaskLocked(who);
9862             setLockTaskFeaturesLocked(userHandle, flags);
9863         }
9864     }
9865 
setLockTaskFeaturesLocked(int userHandle, int flags)9866     private void setLockTaskFeaturesLocked(int userHandle, int flags) {
9867         DevicePolicyData policy = getUserData(userHandle);
9868         policy.mLockTaskFeatures = flags;
9869         saveSettingsLocked(userHandle);
9870         updateLockTaskFeaturesLocked(flags, userHandle);
9871     }
9872 
9873     @Override
getLockTaskFeatures(ComponentName who)9874     public int getLockTaskFeatures(ComponentName who) {
9875         Preconditions.checkNotNull(who, "ComponentName is null");
9876         final int userHandle = mInjector.userHandleGetCallingUserId();
9877         synchronized (getLockObject()) {
9878             enforceCanCallLockTaskLocked(who);
9879             return getUserData(userHandle).mLockTaskFeatures;
9880         }
9881     }
9882 
maybeClearLockTaskPolicyLocked()9883     private void maybeClearLockTaskPolicyLocked() {
9884         final long ident = mInjector.binderClearCallingIdentity();
9885         try {
9886             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
9887             for (int i = userInfos.size() - 1; i >= 0; i--) {
9888                 int userId = userInfos.get(i).id;
9889                 if (canUserUseLockTaskLocked(userId)) {
9890                     continue;
9891                 }
9892 
9893                 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages;
9894                 if (!lockTaskPackages.isEmpty()) {
9895                     Slog.d(LOG_TAG,
9896                             "User id " + userId + " not affiliated. Clearing lock task packages");
9897                     setLockTaskPackagesLocked(userId, Collections.<String>emptyList());
9898                 }
9899                 final int lockTaskFeatures = getUserData(userId).mLockTaskFeatures;
9900                 if (lockTaskFeatures != DevicePolicyManager.LOCK_TASK_FEATURE_NONE){
9901                     Slog.d(LOG_TAG,
9902                             "User id " + userId + " not affiliated. Clearing lock task features");
9903                     setLockTaskFeaturesLocked(userId, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
9904                 }
9905             }
9906         } finally {
9907             mInjector.binderRestoreCallingIdentity(ident);
9908         }
9909     }
9910 
9911     @Override
notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle)9912     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
9913         if (!isCallerWithSystemUid()) {
9914             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
9915         }
9916         synchronized (getLockObject()) {
9917             final DevicePolicyData policy = getUserData(userHandle);
9918 
9919             if (policy.mStatusBarDisabled) {
9920                 // Status bar is managed by LockTaskController during LockTask, so we cancel this
9921                 // policy when LockTask starts, and reapply it when LockTask ends
9922                 setStatusBarDisabledInternal(!isEnabled, userHandle);
9923             }
9924 
9925             Bundle adminExtras = new Bundle();
9926             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
9927             for (ActiveAdmin admin : policy.mAdminList) {
9928                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
9929                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
9930                 if (ownsDevice || ownsProfile) {
9931                     if (isEnabled) {
9932                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
9933                                 adminExtras, null);
9934                     } else {
9935                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
9936                     }
9937                 }
9938             }
9939         }
9940     }
9941 
9942     @Override
setGlobalSetting(ComponentName who, String setting, String value)9943     public void setGlobalSetting(ComponentName who, String setting, String value) {
9944         Preconditions.checkNotNull(who, "ComponentName is null");
9945 
9946         synchronized (getLockObject()) {
9947             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9948 
9949             // Some settings are no supported any more. However we do not want to throw a
9950             // SecurityException to avoid breaking apps.
9951             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
9952                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
9953                 return;
9954             }
9955 
9956             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)
9957                     && !UserManager.isDeviceInDemoMode(mContext)) {
9958                 throw new SecurityException(String.format(
9959                         "Permission denial: device owners cannot update %1$s", setting));
9960             }
9961 
9962             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
9963                 // ignore if it contradicts an existing policy
9964                 long timeMs = getMaximumTimeToLock(
9965                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
9966                 if (timeMs > 0 && timeMs < Long.MAX_VALUE) {
9967                     return;
9968                 }
9969             }
9970 
9971             long id = mInjector.binderClearCallingIdentity();
9972             try {
9973                 mInjector.settingsGlobalPutString(setting, value);
9974             } finally {
9975                 mInjector.binderRestoreCallingIdentity(id);
9976             }
9977         }
9978     }
9979 
9980     @Override
setSystemSetting(ComponentName who, String setting, String value)9981     public void setSystemSetting(ComponentName who, String setting, String value) {
9982         Preconditions.checkNotNull(who, "ComponentName is null");
9983         Preconditions.checkStringNotEmpty(setting, "String setting is null or empty");
9984 
9985         synchronized (getLockObject()) {
9986             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9987 
9988             if (!SYSTEM_SETTINGS_WHITELIST.contains(setting)) {
9989                 throw new SecurityException(String.format(
9990                         "Permission denial: device owners cannot update %1$s", setting));
9991             }
9992 
9993             final int callingUserId = mInjector.userHandleGetCallingUserId();
9994 
9995             mInjector.binderWithCleanCallingIdentity(() ->
9996                 mInjector.settingsSystemPutStringForUser(setting, value, callingUserId));
9997         }
9998     }
9999 
10000     @Override
setTime(ComponentName who, long millis)10001     public boolean setTime(ComponentName who, long millis) {
10002         Preconditions.checkNotNull(who, "ComponentName is null in setTime");
10003         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10004         // Don't allow set time when auto time is on.
10005         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME, 0) == 1) {
10006             return false;
10007         }
10008         mInjector.binderWithCleanCallingIdentity(() -> mInjector.getAlarmManager().setTime(millis));
10009         return true;
10010     }
10011 
10012     @Override
setTimeZone(ComponentName who, String timeZone)10013     public boolean setTimeZone(ComponentName who, String timeZone) {
10014         Preconditions.checkNotNull(who, "ComponentName is null in setTimeZone");
10015         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10016         // Don't allow set timezone when auto timezone is on.
10017         if (mInjector.settingsGlobalGetInt(Global.AUTO_TIME_ZONE, 0) == 1) {
10018             return false;
10019         }
10020         mInjector.binderWithCleanCallingIdentity(() ->
10021             mInjector.getAlarmManager().setTimeZone(timeZone));
10022         return true;
10023     }
10024 
10025     @Override
setSecureSetting(ComponentName who, String setting, String value)10026     public void setSecureSetting(ComponentName who, String setting, String value) {
10027         Preconditions.checkNotNull(who, "ComponentName is null");
10028         int callingUserId = mInjector.userHandleGetCallingUserId();
10029 
10030         synchronized (getLockObject()) {
10031             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10032 
10033             if (isDeviceOwner(who, callingUserId)) {
10034                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)
10035                         && !isCurrentUserDemo()) {
10036                     throw new SecurityException(String.format(
10037                             "Permission denial: Device owners cannot update %1$s", setting));
10038                 }
10039             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting) && !isCurrentUserDemo()) {
10040                 throw new SecurityException(String.format(
10041                         "Permission denial: Profile owners cannot update %1$s", setting));
10042             }
10043             if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) {
10044                 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) {
10045                     throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS
10046                             + " is deprecated. Please use the user restriction "
10047                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead.");
10048                 }
10049                 if (!mUserManager.isManagedProfile(callingUserId)) {
10050                     Slog.e(LOG_TAG, "Ignoring setSecureSetting request for "
10051                             + setting + ". User restriction "
10052                             + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES
10053                             + " should be used instead.");
10054                 } else {
10055                     try {
10056                         setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
10057                                 (Integer.parseInt(value) == 0) ? true : false);
10058                     } catch (NumberFormatException exc) {
10059                         Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting);
10060                     }
10061                 }
10062                 return;
10063             }
10064             long id = mInjector.binderClearCallingIdentity();
10065             try {
10066                 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) {
10067                     final String currentValue = mInjector.settingsSecureGetStringForUser(
10068                             Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId);
10069                     if (!TextUtils.equals(currentValue, value)) {
10070                         // Tell the content observer that the next change will be due to the owner
10071                         // changing the value. There is a small race condition here that we cannot
10072                         // avoid: Change notifications are sent asynchronously, so it is possible
10073                         // that there are prior notifications queued up before the one we are about
10074                         // to trigger. This is a corner case that will have no impact in practice.
10075                         mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId);
10076                     }
10077                     getUserData(callingUserId).mCurrentInputMethodSet = true;
10078                     saveSettingsLocked(callingUserId);
10079                 }
10080                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
10081             } finally {
10082                 mInjector.binderRestoreCallingIdentity(id);
10083             }
10084         }
10085     }
10086 
10087     @Override
setMasterVolumeMuted(ComponentName who, boolean on)10088     public void setMasterVolumeMuted(ComponentName who, boolean on) {
10089         Preconditions.checkNotNull(who, "ComponentName is null");
10090         synchronized (getLockObject()) {
10091             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10092             setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on);
10093         }
10094     }
10095 
10096     @Override
isMasterVolumeMuted(ComponentName who)10097     public boolean isMasterVolumeMuted(ComponentName who) {
10098         Preconditions.checkNotNull(who, "ComponentName is null");
10099         synchronized (getLockObject()) {
10100             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10101 
10102             AudioManager audioManager =
10103                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
10104             return audioManager.isMasterMute();
10105         }
10106     }
10107 
10108     @Override
setUserIcon(ComponentName who, Bitmap icon)10109     public void setUserIcon(ComponentName who, Bitmap icon) {
10110         synchronized (getLockObject()) {
10111             Preconditions.checkNotNull(who, "ComponentName is null");
10112             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10113 
10114             int userId = UserHandle.getCallingUserId();
10115             long id = mInjector.binderClearCallingIdentity();
10116             try {
10117                 mUserManagerInternal.setUserIcon(userId, icon);
10118             } finally {
10119                 mInjector.binderRestoreCallingIdentity(id);
10120             }
10121         }
10122     }
10123 
10124     @Override
setKeyguardDisabled(ComponentName who, boolean disabled)10125     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
10126         Preconditions.checkNotNull(who, "ComponentName is null");
10127         final int userId = mInjector.userHandleGetCallingUserId();
10128         synchronized (getLockObject()) {
10129             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10130             if (!isUserAffiliatedWithDeviceLocked(userId)) {
10131                 throw new SecurityException("Admin " + who +
10132                         " is neither the device owner or affiliated user's profile owner.");
10133             }
10134         }
10135         if (isManagedProfile(userId)) {
10136             throw new SecurityException("Managed profile cannot disable keyguard");
10137         }
10138 
10139         long ident = mInjector.binderClearCallingIdentity();
10140         try {
10141             // disallow disabling the keyguard if a password is currently set
10142             if (disabled && mLockPatternUtils.isSecure(userId)) {
10143                 return false;
10144             }
10145             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
10146             mInjector.getIWindowManager().dismissKeyguard(null /* callback */, null /* message */);
10147         } catch (RemoteException e) {
10148             // Same process, does not happen.
10149         } finally {
10150             mInjector.binderRestoreCallingIdentity(ident);
10151         }
10152         return true;
10153     }
10154 
10155     @Override
setStatusBarDisabled(ComponentName who, boolean disabled)10156     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
10157         int userId = UserHandle.getCallingUserId();
10158         synchronized (getLockObject()) {
10159             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
10160             if (!isUserAffiliatedWithDeviceLocked(userId)) {
10161                 throw new SecurityException("Admin " + who +
10162                         " is neither the device owner or affiliated user's profile owner.");
10163             }
10164             if (isManagedProfile(userId)) {
10165                 throw new SecurityException("Managed profile cannot disable status bar");
10166             }
10167             DevicePolicyData policy = getUserData(userId);
10168             if (policy.mStatusBarDisabled != disabled) {
10169                 boolean isLockTaskMode = false;
10170                 try {
10171                     isLockTaskMode = mInjector.getIActivityManager().getLockTaskModeState()
10172                             != LOCK_TASK_MODE_NONE;
10173                 } catch (RemoteException e) {
10174                     Slog.e(LOG_TAG, "Failed to get LockTask mode");
10175                 }
10176                 if (!isLockTaskMode) {
10177                     if (!setStatusBarDisabledInternal(disabled, userId)) {
10178                         return false;
10179                     }
10180                 }
10181                 policy.mStatusBarDisabled = disabled;
10182                 saveSettingsLocked(userId);
10183             }
10184         }
10185         return true;
10186     }
10187 
setStatusBarDisabledInternal(boolean disabled, int userId)10188     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
10189         long ident = mInjector.binderClearCallingIdentity();
10190         try {
10191             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
10192                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
10193             if (statusBarService != null) {
10194                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
10195                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
10196                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
10197                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
10198                 return true;
10199             }
10200         } catch (RemoteException e) {
10201             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
10202         } finally {
10203             mInjector.binderRestoreCallingIdentity(ident);
10204         }
10205         return false;
10206     }
10207 
10208     /**
10209      * We need to update the internal state of whether a user has completed setup or a
10210      * device has paired once. After that, we ignore any changes that reset the
10211      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
10212      * as we don't trust any apps that might try to reset them.
10213      * <p>
10214      * Unfortunately, we don't know which user's setup state was changed, so we write all of
10215      * them.
10216      */
updateUserSetupCompleteAndPaired()10217     void updateUserSetupCompleteAndPaired() {
10218         List<UserInfo> users = mUserManager.getUsers(true);
10219         final int N = users.size();
10220         for (int i = 0; i < N; i++) {
10221             int userHandle = users.get(i).id;
10222             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
10223                     userHandle) != 0) {
10224                 DevicePolicyData policy = getUserData(userHandle);
10225                 if (!policy.mUserSetupComplete) {
10226                     policy.mUserSetupComplete = true;
10227                     synchronized (getLockObject()) {
10228                         saveSettingsLocked(userHandle);
10229                     }
10230                 }
10231             }
10232             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
10233                     userHandle) != 0) {
10234                 DevicePolicyData policy = getUserData(userHandle);
10235                 if (!policy.mPaired) {
10236                     policy.mPaired = true;
10237                     synchronized (getLockObject()) {
10238                         saveSettingsLocked(userHandle);
10239                     }
10240                 }
10241             }
10242         }
10243     }
10244 
10245     private class SetupContentObserver extends ContentObserver {
10246         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
10247                 Settings.Secure.USER_SETUP_COMPLETE);
10248         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
10249                 Settings.Global.DEVICE_PROVISIONED);
10250         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
10251         private final Uri mDefaultImeChanged = Settings.Secure.getUriFor(
10252                 Settings.Secure.DEFAULT_INPUT_METHOD);
10253 
10254         @GuardedBy("getLockObject()")
10255         private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>();
10256 
SetupContentObserver(Handler handler)10257         public SetupContentObserver(Handler handler) {
10258             super(handler);
10259         }
10260 
register()10261         void register() {
10262             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
10263             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
10264             if (mIsWatch) {
10265                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
10266             }
10267             mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL);
10268         }
10269 
10270         @GuardedBy("getLockObject()")
addPendingChangeByOwnerLocked(int userId)10271         private void addPendingChangeByOwnerLocked(int userId) {
10272             mUserIdsWithPendingChangesByOwner.add(userId);
10273         }
10274 
10275         @Override
onChange(boolean selfChange, Uri uri, int userId)10276         public void onChange(boolean selfChange, Uri uri, int userId) {
10277             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
10278                 updateUserSetupCompleteAndPaired();
10279             } else if (mDeviceProvisioned.equals(uri)) {
10280                 synchronized (getLockObject()) {
10281                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
10282                     // is delayed until device is marked as provisioned.
10283                     setDeviceOwnerSystemPropertyLocked();
10284                 }
10285             } else if (mDefaultImeChanged.equals(uri)) {
10286                 synchronized (getLockObject()) {
10287                     if (mUserIdsWithPendingChangesByOwner.contains(userId)) {
10288                         // This change notification was triggered by the owner changing the current
10289                         // IME. Ignore it.
10290                         mUserIdsWithPendingChangesByOwner.remove(userId);
10291                     } else {
10292                         // This change notification was triggered by the user manually changing the
10293                         // current IME.
10294                         getUserData(userId).mCurrentInputMethodSet = false;
10295                         saveSettingsLocked(userId);
10296                     }
10297                 }
10298             }
10299         }
10300     }
10301 
10302     @VisibleForTesting
10303     final class LocalService extends DevicePolicyManagerInternal {
10304         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
10305 
10306         @Override
getCrossProfileWidgetProviders(int profileId)10307         public List<String> getCrossProfileWidgetProviders(int profileId) {
10308             synchronized (getLockObject()) {
10309                 if (mOwners == null) {
10310                     return Collections.emptyList();
10311                 }
10312                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
10313                 if (ownerComponent == null) {
10314                     return Collections.emptyList();
10315                 }
10316 
10317                 DevicePolicyData policy = getUserDataUnchecked(profileId);
10318                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
10319 
10320                 if (admin == null || admin.crossProfileWidgetProviders == null
10321                         || admin.crossProfileWidgetProviders.isEmpty()) {
10322                     return Collections.emptyList();
10323                 }
10324 
10325                 return admin.crossProfileWidgetProviders;
10326             }
10327         }
10328 
10329         @Override
addOnCrossProfileWidgetProvidersChangeListener( OnCrossProfileWidgetProvidersChangeListener listener)10330         public void addOnCrossProfileWidgetProvidersChangeListener(
10331                 OnCrossProfileWidgetProvidersChangeListener listener) {
10332             synchronized (getLockObject()) {
10333                 if (mWidgetProviderListeners == null) {
10334                     mWidgetProviderListeners = new ArrayList<>();
10335                 }
10336                 if (!mWidgetProviderListeners.contains(listener)) {
10337                     mWidgetProviderListeners.add(listener);
10338                 }
10339             }
10340         }
10341 
10342         @Override
isActiveAdminWithPolicy(int uid, int reqPolicy)10343         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
10344             synchronized (getLockObject()) {
10345                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
10346             }
10347         }
10348 
notifyCrossProfileProvidersChanged(int userId, List<String> packages)10349         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
10350             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
10351             synchronized (getLockObject()) {
10352                 listeners = new ArrayList<>(mWidgetProviderListeners);
10353             }
10354             final int listenerCount = listeners.size();
10355             for (int i = 0; i < listenerCount; i++) {
10356                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
10357                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
10358             }
10359         }
10360 
10361         @Override
createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin)10362         public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) {
10363             // This method is called from AM with its lock held, so don't take the DPMS lock.
10364             // b/29242568
10365 
10366             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10367             if (profileOwner != null) {
10368                 return DevicePolicyManagerService.this
10369                         .createShowAdminSupportIntent(profileOwner, userId);
10370             }
10371 
10372             final Pair<Integer, ComponentName> deviceOwner =
10373                     mOwners.getDeviceOwnerUserIdAndComponent();
10374             if (deviceOwner != null && deviceOwner.first == userId) {
10375                 return DevicePolicyManagerService.this
10376                         .createShowAdminSupportIntent(deviceOwner.second, userId);
10377             }
10378 
10379             // We're not specifying the device admin because there isn't one.
10380             if (useDefaultIfNoAdmin) {
10381                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10382             }
10383             return null;
10384         }
10385 
10386         @Override
createUserRestrictionSupportIntent(int userId, String userRestriction)10387         public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) {
10388             int source;
10389             long ident = mInjector.binderClearCallingIdentity();
10390             try {
10391                 source = mUserManager.getUserRestrictionSource(userRestriction,
10392                         UserHandle.of(userId));
10393             } finally {
10394                 mInjector.binderRestoreCallingIdentity(ident);
10395             }
10396             if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) {
10397                 /*
10398                  * In this case, the user restriction is enforced by the system.
10399                  * So we won't show an admin support intent, even if it is also
10400                  * enforced by a profile/device owner.
10401                  */
10402                 return null;
10403             }
10404             boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0;
10405             boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0;
10406             if (enforcedByDo && enforcedByPo) {
10407                 // In this case, we'll show an admin support dialog that does not
10408                 // specify the admin.
10409                 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId);
10410             } else if (enforcedByPo) {
10411                 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
10412                 if (profileOwner != null) {
10413                     return DevicePolicyManagerService.this
10414                             .createShowAdminSupportIntent(profileOwner, userId);
10415                 }
10416                 // This could happen if another thread has changed the profile owner since we called
10417                 // getUserRestrictionSource
10418                 return null;
10419             } else if (enforcedByDo) {
10420                 final Pair<Integer, ComponentName> deviceOwner
10421                         = mOwners.getDeviceOwnerUserIdAndComponent();
10422                 if (deviceOwner != null) {
10423                     return DevicePolicyManagerService.this
10424                             .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first);
10425                 }
10426                 // This could happen if another thread has changed the device owner since we called
10427                 // getUserRestrictionSource
10428                 return null;
10429             }
10430             return null;
10431         }
10432 
10433         @Override
isUserAffiliatedWithDevice(int userId)10434         public boolean isUserAffiliatedWithDevice(int userId) {
10435             return DevicePolicyManagerService.this.isUserAffiliatedWithDeviceLocked(userId);
10436         }
10437 
10438         @Override
reportSeparateProfileChallengeChanged(@serIdInt int userId)10439         public void reportSeparateProfileChallengeChanged(@UserIdInt int userId) {
10440             synchronized (getLockObject()) {
10441                 updateMaximumTimeToLockLocked(userId);
10442             }
10443         }
10444 
10445         @Override
canUserHaveUntrustedCredentialReset(@serIdInt int userId)10446         public boolean canUserHaveUntrustedCredentialReset(@UserIdInt int userId) {
10447             return DevicePolicyManagerService.this.canUserHaveUntrustedCredentialReset(userId);
10448         }
10449 
10450         @Override
getPrintingDisabledReasonForUser(@serIdInt int userId)10451         public CharSequence getPrintingDisabledReasonForUser(@UserIdInt int userId) {
10452             synchronized (getLockObject()) {
10453                 DevicePolicyData policy = getUserData(userId);
10454                 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_PRINTING,
10455                         UserHandle.of(userId))) {
10456                     Log.e(LOG_TAG, "printing is enabled");
10457                     return null;
10458                 }
10459                 String ownerPackage = mOwners.getProfileOwnerPackage(userId);
10460                 if (ownerPackage == null) {
10461                     ownerPackage = mOwners.getDeviceOwnerPackageName();
10462                 }
10463                 PackageManager pm = mInjector.getPackageManager();
10464                 PackageInfo packageInfo;
10465                 try {
10466                     packageInfo = pm.getPackageInfo(ownerPackage, 0);
10467                 } catch (NameNotFoundException e) {
10468                     Log.e(LOG_TAG, "getPackageInfo error", e);
10469                     return null;
10470                 }
10471                 if (packageInfo == null) {
10472                     Log.e(LOG_TAG, "packageInfo is inexplicably null");
10473                     return null;
10474                 }
10475                 ApplicationInfo appInfo = packageInfo.applicationInfo;
10476                 if (appInfo == null) {
10477                     Log.e(LOG_TAG, "appInfo is inexplicably null");
10478                     return null;
10479                 }
10480                 CharSequence appLabel = pm.getApplicationLabel(appInfo);
10481                 if (appLabel == null) {
10482                     Log.e(LOG_TAG, "appLabel is inexplicably null");
10483                     return null;
10484                 }
10485                 return ((Context) ActivityThread.currentActivityThread().getSystemUiContext())
10486                         .getResources().getString(R.string.printing_disabled_by, appLabel);
10487             }
10488         }
10489 
10490         @Override
getDevicePolicyCache()10491         protected DevicePolicyCache getDevicePolicyCache() {
10492             return mPolicyCache;
10493         }
10494     }
10495 
createShowAdminSupportIntent(ComponentName admin, int userId)10496     private Intent createShowAdminSupportIntent(ComponentName admin, int userId) {
10497         // This method is called with AMS lock held, so don't take DPMS lock
10498         final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
10499         intent.putExtra(Intent.EXTRA_USER_ID, userId);
10500         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
10501         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
10502         return intent;
10503     }
10504 
10505     @Override
createAdminSupportIntent(String restriction)10506     public Intent createAdminSupportIntent(String restriction) {
10507         Preconditions.checkNotNull(restriction);
10508         final int uid = mInjector.binderGetCallingUid();
10509         final int userId = UserHandle.getUserId(uid);
10510         Intent intent = null;
10511         if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) ||
10512                 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction) ||
10513                 DevicePolicyManager.POLICY_MANDATORY_BACKUPS.equals(restriction)) {
10514             synchronized (getLockObject()) {
10515                 final DevicePolicyData policy = getUserData(userId);
10516                 final int N = policy.mAdminList.size();
10517                 for (int i = 0; i < N; i++) {
10518                     final ActiveAdmin admin = policy.mAdminList.get(i);
10519                     if ((admin.disableCamera &&
10520                                 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) ||
10521                         (admin.disableScreenCapture && DevicePolicyManager
10522                                 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) ||
10523                         (admin.mandatoryBackupTransport != null && DevicePolicyManager
10524                                 .POLICY_MANDATORY_BACKUPS.equals(restriction))) {
10525                         intent = createShowAdminSupportIntent(admin.info.getComponent(), userId);
10526                         break;
10527                     }
10528                 }
10529                 // For the camera, a device owner on a different user can disable it globally,
10530                 // so we need an additional check.
10531                 if (intent == null
10532                         && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) {
10533                     final ActiveAdmin admin = getDeviceOwnerAdminLocked();
10534                     if (admin != null && admin.disableCamera) {
10535                         intent = createShowAdminSupportIntent(admin.info.getComponent(),
10536                                 mOwners.getDeviceOwnerUserId());
10537                     }
10538                 }
10539             }
10540         } else {
10541             // if valid, |restriction| can only be a user restriction
10542             intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction);
10543         }
10544         if (intent != null) {
10545             intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction);
10546         }
10547         return intent;
10548     }
10549 
10550     /**
10551      * Returns true if specified admin is allowed to limit passwords and has a
10552      * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality}
10553      */
isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality)10554     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
10555         if (admin.minimumPasswordMetrics.quality < minPasswordQuality) {
10556             return false;
10557         }
10558         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
10559     }
10560 
10561     @Override
setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy)10562     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
10563         if (policy != null) {
10564             // throws exception if policy type is invalid
10565             policy.validateType();
10566             // throws exception if freeze period is invalid
10567             policy.validateFreezePeriods();
10568             Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
10569             // throws exception if freeze period is incompatible with previous freeze period record
10570             policy.validateAgainstPreviousFreezePeriod(record.first, record.second,
10571                     LocalDate.now());
10572         }
10573         synchronized (getLockObject()) {
10574             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
10575             if (policy == null) {
10576                 mOwners.clearSystemUpdatePolicy();
10577             } else {
10578                 mOwners.setSystemUpdatePolicy(policy);
10579                 updateSystemUpdateFreezePeriodsRecord(/* saveIfChanged */ false);
10580             }
10581             mOwners.writeDeviceOwner();
10582         }
10583         mContext.sendBroadcastAsUser(
10584                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
10585                 UserHandle.SYSTEM);
10586     }
10587 
10588     @Override
getSystemUpdatePolicy()10589     public SystemUpdatePolicy getSystemUpdatePolicy() {
10590         synchronized (getLockObject()) {
10591             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
10592             if (policy != null && !policy.isValid()) {
10593                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
10594                 return null;
10595             }
10596             return policy;
10597         }
10598     }
10599 
withinRange(Pair<LocalDate, LocalDate> range, LocalDate date)10600     private static boolean withinRange(Pair<LocalDate, LocalDate> range, LocalDate date) {
10601         return (!date.isBefore(range.first) && !date.isAfter(range.second));
10602     }
10603 
10604     /**
10605      * keeps track of the last continuous period when the system is under OTA freeze.
10606      *
10607      * DPMS keeps track of the previous dates during which OTA was freezed as a result of an
10608      * system update policy with freeze periods in effect. This is needed to make robust
10609      * validation on new system update polices, for example to prevent the OTA from being
10610      * frozen for more than 90 days if the DPC keeps resetting a new 24-hour freeze period
10611      * on midnight everyday, or having freeze periods closer than 60 days apart by DPC resetting
10612      * a new freeze period after a few days.
10613      *
10614      * @param saveIfChanged whether to persist the result on disk if freeze period record is
10615      *            updated. This should only be set to {@code false} if there is a guaranteed
10616      *            mOwners.writeDeviceOwner() later in the control flow to reduce the number of
10617      *            disk writes. Otherwise you risk inconsistent on-disk state.
10618      *
10619      * @see SystemUpdatePolicy#validateAgainstPreviousFreezePeriod
10620      */
updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged)10621     private void updateSystemUpdateFreezePeriodsRecord(boolean saveIfChanged) {
10622         Slog.d(LOG_TAG, "updateSystemUpdateFreezePeriodsRecord");
10623         synchronized (getLockObject()) {
10624             final SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy();
10625             if (policy == null) {
10626                 return;
10627             }
10628             final LocalDate now = LocalDate.now();
10629             final Pair<LocalDate, LocalDate> currentPeriod = policy.getCurrentFreezePeriod(now);
10630             if (currentPeriod == null) {
10631                 return;
10632             }
10633             final Pair<LocalDate, LocalDate> record = mOwners.getSystemUpdateFreezePeriodRecord();
10634             final LocalDate start = record.first;
10635             final LocalDate end = record.second;
10636             final boolean changed;
10637             if (end == null || start == null) {
10638                 // Start a new period if there is none at the moment
10639                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10640             } else if (now.equals(end.plusDays(1))) {
10641                 // Extend the existing period
10642                 changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
10643             } else if (now.isAfter(end.plusDays(1))) {
10644                 if (withinRange(currentPeriod, start) && withinRange(currentPeriod, end)) {
10645                     // The device might be off for some period. If the past freeze record
10646                     // is within range of the current freeze period, assume the device was off
10647                     // during the period [end, now] and extend the freeze record to [start, now].
10648                     changed = mOwners.setSystemUpdateFreezePeriodRecord(start, now);
10649                 } else {
10650                     changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10651                 }
10652             } else if (now.isBefore(start)) {
10653                 // Systm clock was adjusted backwards, restart record
10654                 changed = mOwners.setSystemUpdateFreezePeriodRecord(now, now);
10655             } else /* start <= now <= end */ {
10656                 changed = false;
10657             }
10658             if (changed && saveIfChanged) {
10659                 mOwners.writeDeviceOwner();
10660             }
10661         }
10662     }
10663 
10664     @Override
clearSystemUpdatePolicyFreezePeriodRecord()10665     public void clearSystemUpdatePolicyFreezePeriodRecord() {
10666         enforceShell("clearSystemUpdatePolicyFreezePeriodRecord");
10667         synchronized (getLockObject()) {
10668             // Print out current record to help diagnosed CTS failures
10669             Slog.i(LOG_TAG, "Clear freeze period record: "
10670                     + mOwners.getSystemUpdateFreezePeriodRecordAsString());
10671             if (mOwners.setSystemUpdateFreezePeriodRecord(null, null)) {
10672                 mOwners.writeDeviceOwner();
10673             }
10674         }
10675     }
10676 
10677     /**
10678      * Checks if the caller of the method is the device owner app.
10679      *
10680      * @param callerUid UID of the caller.
10681      * @return true if the caller is the device owner app
10682      */
10683     @VisibleForTesting
isCallerDeviceOwner(int callerUid)10684     boolean isCallerDeviceOwner(int callerUid) {
10685         synchronized (getLockObject()) {
10686             if (!mOwners.hasDeviceOwner()) {
10687                 return false;
10688             }
10689             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
10690                 return false;
10691             }
10692             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
10693                     .getPackageName();
10694                 try {
10695                     String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid);
10696                     for (String pkg : pkgs) {
10697                         if (deviceOwnerPackageName.equals(pkg)) {
10698                             return true;
10699                         }
10700                     }
10701                 } catch (RemoteException e) {
10702                     return false;
10703                 }
10704         }
10705 
10706         return false;
10707     }
10708 
10709     @Override
notifyPendingSystemUpdate(@ullable SystemUpdateInfo info)10710     public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) {
10711         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
10712                 "Only the system update service can broadcast update information");
10713 
10714         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
10715             Slog.w(LOG_TAG, "Only the system update service in the system user " +
10716                     "can broadcast update information.");
10717             return;
10718         }
10719 
10720         if (!mOwners.saveSystemUpdateInfo(info)) {
10721             // Pending system update hasn't changed, don't send duplicate notification.
10722             return;
10723         }
10724 
10725         final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE)
10726                 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
10727                         info == null ? -1 : info.getReceivedTime());
10728 
10729         final long ident = mInjector.binderClearCallingIdentity();
10730         try {
10731             synchronized (getLockObject()) {
10732                 // Broadcast to device owner first if there is one.
10733                 if (mOwners.hasDeviceOwner()) {
10734                     final UserHandle deviceOwnerUser =
10735                             UserHandle.of(mOwners.getDeviceOwnerUserId());
10736                     intent.setComponent(mOwners.getDeviceOwnerComponent());
10737                     mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
10738                 }
10739             }
10740             // Get running users.
10741             final int runningUserIds[];
10742             try {
10743                 runningUserIds = mInjector.getIActivityManager().getRunningUserIds();
10744             } catch (RemoteException e) {
10745                 // Shouldn't happen.
10746                 Log.e(LOG_TAG, "Could not retrieve the list of running users", e);
10747                 return;
10748             }
10749             // Send broadcasts to corresponding profile owners if any.
10750             for (final int userId : runningUserIds) {
10751                 synchronized (getLockObject()) {
10752                     final ComponentName profileOwnerPackage =
10753                             mOwners.getProfileOwnerComponent(userId);
10754                     if (profileOwnerPackage != null) {
10755                         intent.setComponent(profileOwnerPackage);
10756                         mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
10757                     }
10758                 }
10759             }
10760         } finally {
10761             mInjector.binderRestoreCallingIdentity(ident);
10762         }
10763     }
10764 
10765     @Override
getPendingSystemUpdate(ComponentName admin)10766     public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) {
10767         Preconditions.checkNotNull(admin, "ComponentName is null");
10768         enforceProfileOrDeviceOwner(admin);
10769 
10770         return mOwners.getSystemUpdateInfo();
10771     }
10772 
10773     @Override
setPermissionPolicy(ComponentName admin, String callerPackage, int policy)10774     public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy)
10775             throws RemoteException {
10776         int userId = UserHandle.getCallingUserId();
10777         synchronized (getLockObject()) {
10778             // Ensure the caller is a DO/PO or a permission grant state delegate.
10779             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10780                     DELEGATION_PERMISSION_GRANT);
10781             DevicePolicyData userPolicy = getUserData(userId);
10782             if (userPolicy.mPermissionPolicy != policy) {
10783                 userPolicy.mPermissionPolicy = policy;
10784                 saveSettingsLocked(userId);
10785             }
10786         }
10787     }
10788 
10789     @Override
getPermissionPolicy(ComponentName admin)10790     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
10791         int userId = UserHandle.getCallingUserId();
10792         synchronized (getLockObject()) {
10793             DevicePolicyData userPolicy = getUserData(userId);
10794             return userPolicy.mPermissionPolicy;
10795         }
10796     }
10797 
10798     @Override
setPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission, int grantState)10799     public boolean setPermissionGrantState(ComponentName admin, String callerPackage,
10800             String packageName, String permission, int grantState) throws RemoteException {
10801         UserHandle user = mInjector.binderGetCallingUserHandle();
10802         synchronized (getLockObject()) {
10803             // Ensure the caller is a DO/PO or a permission grant state delegate.
10804             enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER,
10805                     DELEGATION_PERMISSION_GRANT);
10806             long ident = mInjector.binderClearCallingIdentity();
10807             try {
10808                 if (getTargetSdk(packageName, user.getIdentifier())
10809                         < android.os.Build.VERSION_CODES.M) {
10810                     return false;
10811                 }
10812                 if (!isRuntimePermission(permission)) {
10813                     return false;
10814                 }
10815                 final PackageManager packageManager = mInjector.getPackageManager();
10816                 switch (grantState) {
10817                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
10818                         mInjector.getPackageManagerInternal().grantRuntimePermission(packageName,
10819                                 permission, user.getIdentifier(), true /* override policy */);
10820                         packageManager.updatePermissionFlags(permission, packageName,
10821                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10822                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10823                     } break;
10824 
10825                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
10826                         mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName,
10827                                 permission, user.getIdentifier(), true /* override policy */);
10828                         packageManager.updatePermissionFlags(permission, packageName,
10829                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
10830                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
10831                     } break;
10832 
10833                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
10834                         packageManager.updatePermissionFlags(permission, packageName,
10835                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
10836                     } break;
10837                 }
10838                 return true;
10839             } catch (SecurityException se) {
10840                 return false;
10841             } catch (NameNotFoundException e) {
10842                 return false;
10843             } finally {
10844                 mInjector.binderRestoreCallingIdentity(ident);
10845             }
10846         }
10847     }
10848 
10849     @Override
getPermissionGrantState(ComponentName admin, String callerPackage, String packageName, String permission)10850     public int getPermissionGrantState(ComponentName admin, String callerPackage,
10851             String packageName, String permission) throws RemoteException {
10852         PackageManager packageManager = mInjector.getPackageManager();
10853 
10854         UserHandle user = mInjector.binderGetCallingUserHandle();
10855         if (!isCallerWithSystemUid()) {
10856             // Ensure the caller is a DO/PO or a permission grant state delegate.
10857             enforceCanManageScope(admin, callerPackage,
10858                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT);
10859         }
10860         synchronized (getLockObject()) {
10861             long ident = mInjector.binderClearCallingIdentity();
10862             try {
10863                 int granted = mIPackageManager.checkPermission(permission,
10864                         packageName, user.getIdentifier());
10865                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
10866                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
10867                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
10868                     // Not controlled by policy
10869                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
10870                 } else {
10871                     // Policy controlled so return result based on permission grant state
10872                     return granted == PackageManager.PERMISSION_GRANTED
10873                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
10874                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
10875                 }
10876             } finally {
10877                 mInjector.binderRestoreCallingIdentity(ident);
10878             }
10879         }
10880     }
10881 
isPackageInstalledForUser(String packageName, int userHandle)10882     boolean isPackageInstalledForUser(String packageName, int userHandle) {
10883         try {
10884             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
10885                     userHandle);
10886             return (pi != null) && (pi.applicationInfo.flags != 0);
10887         } catch (RemoteException re) {
10888             throw new RuntimeException("Package manager has died", re);
10889         }
10890     }
10891 
isRuntimePermission(String permissionName)10892     public boolean isRuntimePermission(String permissionName) throws NameNotFoundException {
10893         final PackageManager packageManager = mInjector.getPackageManager();
10894         PermissionInfo permissionInfo = packageManager.getPermissionInfo(permissionName, 0);
10895         return (permissionInfo.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
10896                 == PermissionInfo.PROTECTION_DANGEROUS;
10897     }
10898 
10899     @Override
isProvisioningAllowed(String action, String packageName)10900     public boolean isProvisioningAllowed(String action, String packageName) {
10901         Preconditions.checkNotNull(packageName);
10902 
10903         final int callingUid = mInjector.binderGetCallingUid();
10904         final long ident = mInjector.binderClearCallingIdentity();
10905         try {
10906             final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser(
10907                     packageName, UserHandle.getUserId(callingUid));
10908             Preconditions.checkArgument(callingUid == uidForPackage,
10909                     "Caller uid doesn't match the one for the provided package.");
10910         } catch (NameNotFoundException e) {
10911             throw new IllegalArgumentException("Invalid package provided " + packageName, e);
10912         } finally {
10913             mInjector.binderRestoreCallingIdentity(ident);
10914         }
10915 
10916         return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK;
10917     }
10918 
10919     @Override
checkProvisioningPreCondition(String action, String packageName)10920     public int checkProvisioningPreCondition(String action, String packageName) {
10921         Preconditions.checkNotNull(packageName);
10922         enforceCanManageProfileAndDeviceOwners();
10923         return checkProvisioningPreConditionSkipPermission(action, packageName);
10924     }
10925 
checkProvisioningPreConditionSkipPermission(String action, String packageName)10926     private int checkProvisioningPreConditionSkipPermission(String action, String packageName) {
10927         if (!mHasFeature) {
10928             return CODE_DEVICE_ADMIN_NOT_SUPPORTED;
10929         }
10930 
10931         final int callingUserId = mInjector.userHandleGetCallingUserId();
10932         if (action != null) {
10933             switch (action) {
10934                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE:
10935                     return checkManagedProfileProvisioningPreCondition(packageName, callingUserId);
10936                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE:
10937                     return checkDeviceOwnerProvisioningPreCondition(callingUserId);
10938                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER:
10939                     return checkManagedUserProvisioningPreCondition(callingUserId);
10940                 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE:
10941                     return checkManagedShareableDeviceProvisioningPreCondition(callingUserId);
10942             }
10943         }
10944         throw new IllegalArgumentException("Unknown provisioning action " + action);
10945     }
10946 
10947     /**
10948      * The device owner can only be set before the setup phase of the primary user has completed,
10949      * except for adb command if no accounts or additional users are present on the device.
10950      */
checkDeviceOwnerProvisioningPreConditionLocked(@ullable ComponentName owner, int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb)10951     private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner,
10952             int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) {
10953         if (mOwners.hasDeviceOwner()) {
10954             return CODE_HAS_DEVICE_OWNER;
10955         }
10956         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
10957             return CODE_USER_HAS_PROFILE_OWNER;
10958         }
10959         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
10960             return CODE_USER_NOT_RUNNING;
10961         }
10962         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
10963             return CODE_HAS_PAIRED;
10964         }
10965         if (isAdb) {
10966             // if shell command runs after user setup completed check device status. Otherwise, OK.
10967             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10968                 if (!mInjector.userManagerIsSplitSystemUser()) {
10969                     if (mUserManager.getUserCount() > 1) {
10970                         return CODE_NONSYSTEM_USER_EXISTS;
10971                     }
10972                     if (hasIncompatibleAccountsOrNonAdb) {
10973                         return CODE_ACCOUNTS_NOT_EMPTY;
10974                     }
10975                 } else {
10976                     // STOPSHIP Do proper check in split user mode
10977                 }
10978             }
10979             return CODE_OK;
10980         } else {
10981             if (!mInjector.userManagerIsSplitSystemUser()) {
10982                 // In non-split user mode, DO has to be user 0
10983                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
10984                     return CODE_NOT_SYSTEM_USER;
10985                 }
10986                 // In non-split user mode, only provision DO before setup wizard completes
10987                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
10988                     return CODE_USER_SETUP_COMPLETED;
10989                 }
10990             } else {
10991                 // STOPSHIP Do proper check in split user mode
10992             }
10993             return CODE_OK;
10994         }
10995     }
10996 
checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId)10997     private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) {
10998         synchronized (getLockObject()) {
10999             // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb.
11000             return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null,
11001                     deviceOwnerUserId, /* isAdb= */ false,
11002                     /* hasIncompatibleAccountsOrNonAdb=*/ true);
11003         }
11004     }
11005 
checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId)11006     private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) {
11007         if (!hasFeatureManagedUsers()) {
11008             return CODE_MANAGED_USERS_NOT_SUPPORTED;
11009         }
11010         if (callingUserId == UserHandle.USER_SYSTEM
11011                 && mInjector.userManagerIsSplitSystemUser()) {
11012             // Managed-profiles cannot be setup on the system user.
11013             return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER;
11014         }
11015         if (getProfileOwner(callingUserId) != null) {
11016             // Managed user cannot have a managed profile.
11017             return CODE_USER_HAS_PROFILE_OWNER;
11018         }
11019 
11020         final long ident = mInjector.binderClearCallingIdentity();
11021         try {
11022             final UserHandle callingUserHandle = UserHandle.of(callingUserId);
11023             final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId);
11024             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE,
11025                     callingUserHandle)) {
11026                 // An admin can initiate provisioning if it has set the restriction.
11027                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
11028                         UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) {
11029                     return CODE_ADD_MANAGED_PROFILE_DISALLOWED;
11030                 }
11031             }
11032             boolean canRemoveProfile = true;
11033             if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
11034                     callingUserHandle)) {
11035                 // We can remove a profile if the admin itself has set the restriction.
11036                 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin,
11037                         UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
11038                         callingUserId)) {
11039                     canRemoveProfile = false;
11040                 }
11041             }
11042             if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) {
11043                 return CODE_CANNOT_ADD_MANAGED_PROFILE;
11044             }
11045         } finally {
11046             mInjector.binderRestoreCallingIdentity(ident);
11047         }
11048         return CODE_OK;
11049     }
11050 
getOwnerComponent(String packageName, int userId)11051     private ComponentName getOwnerComponent(String packageName, int userId) {
11052         if (isDeviceOwnerPackage(packageName, userId)) {
11053             return mOwners.getDeviceOwnerComponent();
11054         }
11055         if (isProfileOwnerPackage(packageName, userId)) {
11056             return mOwners.getProfileOwnerComponent(userId);
11057         }
11058         return null;
11059     }
11060 
11061     /**
11062      * Return device owner or profile owner set on a given user.
11063      */
getOwnerComponent(int userId)11064     private @Nullable ComponentName getOwnerComponent(int userId) {
11065         synchronized (getLockObject()) {
11066             if (mOwners.getDeviceOwnerUserId() == userId) {
11067                 return mOwners.getDeviceOwnerComponent();
11068             }
11069             if (mOwners.hasProfileOwner(userId)) {
11070                 return mOwners.getProfileOwnerComponent(userId);
11071             }
11072         }
11073         return null;
11074     }
11075 
checkManagedUserProvisioningPreCondition(int callingUserId)11076     private int checkManagedUserProvisioningPreCondition(int callingUserId) {
11077         if (!hasFeatureManagedUsers()) {
11078             return CODE_MANAGED_USERS_NOT_SUPPORTED;
11079         }
11080         if (!mInjector.userManagerIsSplitSystemUser()) {
11081             // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
11082             return CODE_NOT_SYSTEM_USER_SPLIT;
11083         }
11084         if (callingUserId == UserHandle.USER_SYSTEM) {
11085             // System user cannot be a managed user.
11086             return CODE_SYSTEM_USER;
11087         }
11088         if (hasUserSetupCompleted(callingUserId)) {
11089             return CODE_USER_SETUP_COMPLETED;
11090         }
11091         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
11092             return CODE_HAS_PAIRED;
11093         }
11094         return CODE_OK;
11095     }
11096 
checkManagedShareableDeviceProvisioningPreCondition(int callingUserId)11097     private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) {
11098         if (!mInjector.userManagerIsSplitSystemUser()) {
11099             // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
11100             return CODE_NOT_SYSTEM_USER_SPLIT;
11101         }
11102         return checkDeviceOwnerProvisioningPreCondition(callingUserId);
11103     }
11104 
hasFeatureManagedUsers()11105     private boolean hasFeatureManagedUsers() {
11106         try {
11107             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
11108         } catch (RemoteException e) {
11109             return false;
11110         }
11111     }
11112 
11113     @Override
getWifiMacAddress(ComponentName admin)11114     public String getWifiMacAddress(ComponentName admin) {
11115         // Make sure caller has DO.
11116         synchronized (getLockObject()) {
11117             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11118         }
11119 
11120         final long ident = mInjector.binderClearCallingIdentity();
11121         try {
11122             final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
11123             if (wifiInfo == null) {
11124                 return null;
11125             }
11126             return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
11127         } finally {
11128             mInjector.binderRestoreCallingIdentity(ident);
11129         }
11130     }
11131 
11132     /**
11133      * Returns the target sdk version number that the given packageName was built for
11134      * in the given user.
11135      */
getTargetSdk(String packageName, int userId)11136     private int getTargetSdk(String packageName, int userId) {
11137         final ApplicationInfo ai;
11138         try {
11139             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
11140             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
11141             return targetSdkVersion;
11142         } catch (RemoteException e) {
11143             // Shouldn't happen
11144             return 0;
11145         }
11146     }
11147 
11148     @Override
isManagedProfile(ComponentName admin)11149     public boolean isManagedProfile(ComponentName admin) {
11150         enforceProfileOrDeviceOwner(admin);
11151         return isManagedProfile(mInjector.userHandleGetCallingUserId());
11152     }
11153 
11154     @Override
isSystemOnlyUser(ComponentName admin)11155     public boolean isSystemOnlyUser(ComponentName admin) {
11156         synchronized (getLockObject()) {
11157             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11158         }
11159         final int callingUserId = mInjector.userHandleGetCallingUserId();
11160         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
11161     }
11162 
11163     @Override
reboot(ComponentName admin)11164     public void reboot(ComponentName admin) {
11165         Preconditions.checkNotNull(admin);
11166         // Make sure caller has DO.
11167         synchronized (getLockObject()) {
11168             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11169         }
11170         long ident = mInjector.binderClearCallingIdentity();
11171         try {
11172             // Make sure there are no ongoing calls on the device.
11173             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
11174                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
11175             }
11176             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
11177         } finally {
11178             mInjector.binderRestoreCallingIdentity(ident);
11179         }
11180     }
11181 
11182     @Override
setShortSupportMessage(@onNull ComponentName who, CharSequence message)11183     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
11184         if (!mHasFeature) {
11185             return;
11186         }
11187         Preconditions.checkNotNull(who, "ComponentName is null");
11188         final int userHandle = mInjector.userHandleGetCallingUserId();
11189         synchronized (getLockObject()) {
11190             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11191                     mInjector.binderGetCallingUid());
11192             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
11193                 admin.shortSupportMessage = message;
11194                 saveSettingsLocked(userHandle);
11195             }
11196         }
11197     }
11198 
11199     @Override
getShortSupportMessage(@onNull ComponentName who)11200     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
11201         if (!mHasFeature) {
11202             return null;
11203         }
11204         Preconditions.checkNotNull(who, "ComponentName is null");
11205         synchronized (getLockObject()) {
11206             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11207                     mInjector.binderGetCallingUid());
11208             return admin.shortSupportMessage;
11209         }
11210     }
11211 
11212     @Override
setLongSupportMessage(@onNull ComponentName who, CharSequence message)11213     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
11214         if (!mHasFeature) {
11215             return;
11216         }
11217         Preconditions.checkNotNull(who, "ComponentName is null");
11218         final int userHandle = mInjector.userHandleGetCallingUserId();
11219         synchronized (getLockObject()) {
11220             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11221                     mInjector.binderGetCallingUid());
11222             if (!TextUtils.equals(admin.longSupportMessage, message)) {
11223                 admin.longSupportMessage = message;
11224                 saveSettingsLocked(userHandle);
11225             }
11226         }
11227     }
11228 
11229     @Override
getLongSupportMessage(@onNull ComponentName who)11230     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
11231         if (!mHasFeature) {
11232             return null;
11233         }
11234         Preconditions.checkNotNull(who, "ComponentName is null");
11235         synchronized (getLockObject()) {
11236             ActiveAdmin admin = getActiveAdminForUidLocked(who,
11237                     mInjector.binderGetCallingUid());
11238             return admin.longSupportMessage;
11239         }
11240     }
11241 
11242     @Override
getShortSupportMessageForUser(@onNull ComponentName who, int userHandle)11243     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11244         if (!mHasFeature) {
11245             return null;
11246         }
11247         Preconditions.checkNotNull(who, "ComponentName is null");
11248         if (!isCallerWithSystemUid()) {
11249             throw new SecurityException("Only the system can query support message for user");
11250         }
11251         synchronized (getLockObject()) {
11252             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11253             if (admin != null) {
11254                 return admin.shortSupportMessage;
11255             }
11256         }
11257         return null;
11258     }
11259 
11260     @Override
getLongSupportMessageForUser(@onNull ComponentName who, int userHandle)11261     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
11262         if (!mHasFeature) {
11263             return null;
11264         }
11265         Preconditions.checkNotNull(who, "ComponentName is null");
11266         if (!isCallerWithSystemUid()) {
11267             throw new SecurityException("Only the system can query support message for user");
11268         }
11269         synchronized (getLockObject()) {
11270             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
11271             if (admin != null) {
11272                 return admin.longSupportMessage;
11273             }
11274         }
11275         return null;
11276     }
11277 
11278     @Override
setOrganizationColor(@onNull ComponentName who, int color)11279     public void setOrganizationColor(@NonNull ComponentName who, int color) {
11280         if (!mHasFeature) {
11281             return;
11282         }
11283         Preconditions.checkNotNull(who, "ComponentName is null");
11284         final int userHandle = mInjector.userHandleGetCallingUserId();
11285         enforceManagedProfile(userHandle, "set organization color");
11286         synchronized (getLockObject()) {
11287             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11288                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11289             admin.organizationColor = color;
11290             saveSettingsLocked(userHandle);
11291         }
11292     }
11293 
11294     @Override
setOrganizationColorForUser(int color, int userId)11295     public void setOrganizationColorForUser(int color, int userId) {
11296         if (!mHasFeature) {
11297             return;
11298         }
11299         enforceFullCrossUsersPermission(userId);
11300         enforceManageUsers();
11301         enforceManagedProfile(userId, "set organization color");
11302         synchronized (getLockObject()) {
11303             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
11304             admin.organizationColor = color;
11305             saveSettingsLocked(userId);
11306         }
11307     }
11308 
11309     @Override
getOrganizationColor(@onNull ComponentName who)11310     public int getOrganizationColor(@NonNull ComponentName who) {
11311         if (!mHasFeature) {
11312             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11313         }
11314         Preconditions.checkNotNull(who, "ComponentName is null");
11315         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
11316         synchronized (getLockObject()) {
11317             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11318                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11319             return admin.organizationColor;
11320         }
11321     }
11322 
11323     @Override
getOrganizationColorForUser(int userHandle)11324     public int getOrganizationColorForUser(int userHandle) {
11325         if (!mHasFeature) {
11326             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
11327         }
11328         enforceFullCrossUsersPermission(userHandle);
11329         enforceManagedProfile(userHandle, "get organization color");
11330         synchronized (getLockObject()) {
11331             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11332             return (profileOwner != null)
11333                     ? profileOwner.organizationColor
11334                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
11335         }
11336     }
11337 
11338     @Override
setOrganizationName(@onNull ComponentName who, CharSequence text)11339     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
11340         if (!mHasFeature) {
11341             return;
11342         }
11343         Preconditions.checkNotNull(who, "ComponentName is null");
11344         final int userHandle = mInjector.userHandleGetCallingUserId();
11345 
11346         synchronized (getLockObject()) {
11347             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11348                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11349             if (!TextUtils.equals(admin.organizationName, text)) {
11350                 admin.organizationName = (text == null || text.length() == 0)
11351                         ? null : text.toString();
11352                 saveSettingsLocked(userHandle);
11353             }
11354         }
11355     }
11356 
11357     @Override
getOrganizationName(@onNull ComponentName who)11358     public CharSequence getOrganizationName(@NonNull ComponentName who) {
11359         if (!mHasFeature) {
11360             return null;
11361         }
11362         Preconditions.checkNotNull(who, "ComponentName is null");
11363         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
11364         synchronized (getLockObject()) {
11365             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11366                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11367             return admin.organizationName;
11368         }
11369     }
11370 
11371     @Override
getDeviceOwnerOrganizationName()11372     public CharSequence getDeviceOwnerOrganizationName() {
11373         if (!mHasFeature) {
11374             return null;
11375         }
11376         enforceDeviceOwnerOrManageUsers();
11377         synchronized (getLockObject()) {
11378             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
11379             return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName;
11380         }
11381     }
11382 
11383     @Override
getOrganizationNameForUser(int userHandle)11384     public CharSequence getOrganizationNameForUser(int userHandle) {
11385         if (!mHasFeature) {
11386             return null;
11387         }
11388         enforceFullCrossUsersPermission(userHandle);
11389         enforceManagedProfile(userHandle, "get organization name");
11390         synchronized (getLockObject()) {
11391             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
11392             return (profileOwner != null)
11393                     ? profileOwner.organizationName
11394                     : null;
11395         }
11396     }
11397 
11398     @Override
setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames)11399     public List<String> setMeteredDataDisabledPackages(ComponentName who, List<String> packageNames) {
11400         Preconditions.checkNotNull(who);
11401         Preconditions.checkNotNull(packageNames);
11402 
11403         if (!mHasFeature) {
11404             return packageNames;
11405         }
11406         synchronized (getLockObject()) {
11407             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11408                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11409             final int callingUserId = mInjector.userHandleGetCallingUserId();
11410             final long identity = mInjector.binderClearCallingIdentity();
11411             try {
11412                 final List<String> excludedPkgs
11413                         = removeInvalidPkgsForMeteredDataRestriction(callingUserId, packageNames);
11414                 admin.meteredDisabledPackages = packageNames;
11415                 pushMeteredDisabledPackagesLocked(callingUserId);
11416                 saveSettingsLocked(callingUserId);
11417                 return excludedPkgs;
11418             } finally {
11419                 mInjector.binderRestoreCallingIdentity(identity);
11420             }
11421         }
11422     }
11423 
removeInvalidPkgsForMeteredDataRestriction( int userId, List<String> pkgNames)11424     private List<String> removeInvalidPkgsForMeteredDataRestriction(
11425             int userId, List<String> pkgNames) {
11426         final Set<String> activeAdmins = getActiveAdminPackagesLocked(userId);
11427         final List<String> excludedPkgs = new ArrayList<>();
11428         for (int i = pkgNames.size() - 1; i >= 0; --i) {
11429             final String pkgName = pkgNames.get(i);
11430             // If the package is an active admin, don't restrict it.
11431             if (activeAdmins.contains(pkgName)) {
11432                 excludedPkgs.add(pkgName);
11433                 continue;
11434             }
11435             // If the package doesn't exist, don't restrict it.
11436             try {
11437                 if (!mInjector.getIPackageManager().isPackageAvailable(pkgName, userId)) {
11438                     excludedPkgs.add(pkgName);
11439                 }
11440             } catch (RemoteException e) {
11441                 // Should not happen
11442             }
11443         }
11444         pkgNames.removeAll(excludedPkgs);
11445         return excludedPkgs;
11446     }
11447 
11448     @Override
getMeteredDataDisabledPackages(ComponentName who)11449     public List<String> getMeteredDataDisabledPackages(ComponentName who) {
11450         Preconditions.checkNotNull(who);
11451 
11452         if (!mHasFeature) {
11453             return new ArrayList<>();
11454         }
11455         synchronized (getLockObject()) {
11456             final ActiveAdmin admin = getActiveAdminForCallerLocked(who,
11457                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11458             return admin.meteredDisabledPackages == null
11459                     ? new ArrayList<>() : admin.meteredDisabledPackages;
11460         }
11461     }
11462 
11463     @Override
isMeteredDataDisabledPackageForUser(ComponentName who, String packageName, int userId)11464     public boolean isMeteredDataDisabledPackageForUser(ComponentName who,
11465             String packageName, int userId) {
11466         Preconditions.checkNotNull(who);
11467 
11468         if (!mHasFeature) {
11469             return false;
11470         }
11471         if (!isCallerWithSystemUid()) {
11472             throw new SecurityException(
11473                     "Only the system can query restricted pkgs for a specific user");
11474         }
11475         synchronized (getLockObject()) {
11476             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
11477             if (admin != null && admin.meteredDisabledPackages != null) {
11478                 return admin.meteredDisabledPackages.contains(packageName);
11479             }
11480         }
11481         return false;
11482     }
11483 
pushMeteredDisabledPackagesLocked(int userId)11484     private void pushMeteredDisabledPackagesLocked(int userId) {
11485         mInjector.getNetworkPolicyManagerInternal().setMeteredRestrictedPackages(
11486                 getMeteredDisabledPackagesLocked(userId), userId);
11487     }
11488 
getMeteredDisabledPackagesLocked(int userId)11489     private Set<String> getMeteredDisabledPackagesLocked(int userId) {
11490         final ComponentName who = getOwnerComponent(userId);
11491         final Set<String> restrictedPkgs = new ArraySet<>();
11492         if (who != null) {
11493             final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId);
11494             if (admin != null && admin.meteredDisabledPackages != null) {
11495                 restrictedPkgs.addAll(admin.meteredDisabledPackages);
11496             }
11497         }
11498         return restrictedPkgs;
11499     }
11500 
11501     @Override
setAffiliationIds(ComponentName admin, List<String> ids)11502     public void setAffiliationIds(ComponentName admin, List<String> ids) {
11503         if (!mHasFeature) {
11504             return;
11505         }
11506         if (ids == null) {
11507             throw new IllegalArgumentException("ids must not be null");
11508         }
11509         for (String id : ids) {
11510             if (TextUtils.isEmpty(id)) {
11511                 throw new IllegalArgumentException("ids must not contain empty string");
11512             }
11513         }
11514 
11515         final Set<String> affiliationIds = new ArraySet<>(ids);
11516         final int callingUserId = mInjector.userHandleGetCallingUserId();
11517         synchronized (getLockObject()) {
11518             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11519             getUserData(callingUserId).mAffiliationIds = affiliationIds;
11520             saveSettingsLocked(callingUserId);
11521             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
11522                 // Affiliation ids specified by the device owner are additionally stored in
11523                 // UserHandle.USER_SYSTEM's DevicePolicyData.
11524                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
11525                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11526             }
11527 
11528             // Affiliation status for any user, not just the calling user, might have changed.
11529             // The device owner user will still be affiliated after changing its affiliation ids,
11530             // but as a result of that other users might become affiliated or un-affiliated.
11531             maybePauseDeviceWideLoggingLocked();
11532             maybeResumeDeviceWideLoggingLocked();
11533             maybeClearLockTaskPolicyLocked();
11534         }
11535     }
11536 
11537     @Override
getAffiliationIds(ComponentName admin)11538     public List<String> getAffiliationIds(ComponentName admin) {
11539         if (!mHasFeature) {
11540             return Collections.emptyList();
11541         }
11542 
11543         Preconditions.checkNotNull(admin);
11544         synchronized (getLockObject()) {
11545             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
11546             return new ArrayList<String>(
11547                     getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds);
11548         }
11549     }
11550 
11551     @Override
isAffiliatedUser()11552     public boolean isAffiliatedUser() {
11553         if (!mHasFeature) {
11554             return false;
11555         }
11556 
11557         synchronized (getLockObject()) {
11558             return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId());
11559         }
11560     }
11561 
isUserAffiliatedWithDeviceLocked(int userId)11562     private boolean isUserAffiliatedWithDeviceLocked(int userId) {
11563         if (!mOwners.hasDeviceOwner()) {
11564             return false;
11565         }
11566         if (userId == mOwners.getDeviceOwnerUserId()) {
11567             // The user that the DO is installed on is always affiliated with the device.
11568             return true;
11569         }
11570         if (userId == UserHandle.USER_SYSTEM) {
11571             // The system user is always affiliated in a DO device, even if the DO is set on a
11572             // different user. This could be the case if the DO is set in the primary user
11573             // of a split user device.
11574             return true;
11575         }
11576 
11577         final ComponentName profileOwner = getProfileOwner(userId);
11578         if (profileOwner == null) {
11579             return false;
11580         }
11581 
11582         final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds;
11583         final Set<String> deviceAffiliationIds =
11584                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
11585         for (String id : userAffiliationIds) {
11586             if (deviceAffiliationIds.contains(id)) {
11587                 return true;
11588             }
11589         }
11590         return false;
11591     }
11592 
areAllUsersAffiliatedWithDeviceLocked()11593     private boolean areAllUsersAffiliatedWithDeviceLocked() {
11594         final long ident = mInjector.binderClearCallingIdentity();
11595         try {
11596             final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
11597             for (int i = 0; i < userInfos.size(); i++) {
11598                 int userId = userInfos.get(i).id;
11599                 if (!isUserAffiliatedWithDeviceLocked(userId)) {
11600                     Slog.d(LOG_TAG, "User id " + userId + " not affiliated.");
11601                     return false;
11602                 }
11603             }
11604         } finally {
11605             mInjector.binderRestoreCallingIdentity(ident);
11606         }
11607 
11608         return true;
11609     }
11610 
11611     @Override
setSecurityLoggingEnabled(ComponentName admin, boolean enabled)11612     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
11613         if (!mHasFeature) {
11614             return;
11615         }
11616         Preconditions.checkNotNull(admin);
11617 
11618         synchronized (getLockObject()) {
11619             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11620             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
11621                 return;
11622             }
11623             mInjector.securityLogSetLoggingEnabledProperty(enabled);
11624             if (enabled) {
11625                 mSecurityLogMonitor.start();
11626                 maybePauseDeviceWideLoggingLocked();
11627             } else {
11628                 mSecurityLogMonitor.stop();
11629             }
11630         }
11631     }
11632 
11633     @Override
isSecurityLoggingEnabled(ComponentName admin)11634     public boolean isSecurityLoggingEnabled(ComponentName admin) {
11635         if (!mHasFeature) {
11636             return false;
11637         }
11638 
11639         synchronized (getLockObject()) {
11640             if (!isCallerWithSystemUid()) {
11641                 Preconditions.checkNotNull(admin);
11642                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11643             }
11644             return mInjector.securityLogGetLoggingEnabledProperty();
11645         }
11646     }
11647 
recordSecurityLogRetrievalTime()11648     private void recordSecurityLogRetrievalTime() {
11649         synchronized (getLockObject()) {
11650             final long currentTime = System.currentTimeMillis();
11651             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
11652             if (currentTime > policyData.mLastSecurityLogRetrievalTime) {
11653                 policyData.mLastSecurityLogRetrievalTime = currentTime;
11654                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11655             }
11656         }
11657     }
11658 
11659     @Override
retrievePreRebootSecurityLogs(ComponentName admin)11660     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
11661         if (!mHasFeature) {
11662             return null;
11663         }
11664 
11665         Preconditions.checkNotNull(admin);
11666         ensureDeviceOwnerAndAllUsersAffiliated(admin);
11667 
11668         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)
11669                 || !mInjector.securityLogGetLoggingEnabledProperty()) {
11670             return null;
11671         }
11672 
11673         recordSecurityLogRetrievalTime();
11674 
11675         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
11676         try {
11677             SecurityLog.readPreviousEvents(output);
11678             return new ParceledListSlice<SecurityEvent>(output);
11679         } catch (IOException e) {
11680             Slog.w(LOG_TAG, "Fail to read previous events" , e);
11681             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
11682         }
11683     }
11684 
11685     @Override
retrieveSecurityLogs(ComponentName admin)11686     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
11687         if (!mHasFeature) {
11688             return null;
11689         }
11690 
11691         Preconditions.checkNotNull(admin);
11692         ensureDeviceOwnerAndAllUsersAffiliated(admin);
11693 
11694         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
11695             return null;
11696         }
11697 
11698         recordSecurityLogRetrievalTime();
11699 
11700         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
11701         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
11702     }
11703 
11704     @Override
forceSecurityLogs()11705     public long forceSecurityLogs() {
11706         enforceShell("forceSecurityLogs");
11707         if (!mInjector.securityLogGetLoggingEnabledProperty()) {
11708             throw new IllegalStateException("logging is not available");
11709         }
11710         return mSecurityLogMonitor.forceLogs();
11711     }
11712 
enforceCanManageDeviceAdmin()11713     private void enforceCanManageDeviceAdmin() {
11714         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
11715                 null);
11716     }
11717 
enforceCanManageProfileAndDeviceOwners()11718     private void enforceCanManageProfileAndDeviceOwners() {
11719         mContext.enforceCallingOrSelfPermission(
11720                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
11721     }
11722 
enforceCallerSystemUserHandle()11723     private void enforceCallerSystemUserHandle() {
11724         final int callingUid = mInjector.binderGetCallingUid();
11725         final int userId = UserHandle.getUserId(callingUid);
11726         if (userId != UserHandle.USER_SYSTEM) {
11727             throw new SecurityException("Caller has to be in user 0");
11728         }
11729     }
11730 
11731     @Override
isUninstallInQueue(final String packageName)11732     public boolean isUninstallInQueue(final String packageName) {
11733         enforceCanManageDeviceAdmin();
11734         final int userId = mInjector.userHandleGetCallingUserId();
11735         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11736         synchronized (getLockObject()) {
11737             return mPackagesToRemove.contains(packageUserPair);
11738         }
11739     }
11740 
11741     @Override
uninstallPackageWithActiveAdmins(final String packageName)11742     public void uninstallPackageWithActiveAdmins(final String packageName) {
11743         enforceCanManageDeviceAdmin();
11744         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
11745 
11746         final int userId = mInjector.userHandleGetCallingUserId();
11747 
11748         enforceUserUnlocked(userId);
11749 
11750         final ComponentName profileOwner = getProfileOwner(userId);
11751         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
11752             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
11753         }
11754 
11755         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
11756         if (getDeviceOwnerUserId() == userId && deviceOwner != null
11757                 && packageName.equals(deviceOwner.getPackageName())) {
11758             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
11759         }
11760 
11761         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11762         synchronized (getLockObject()) {
11763             mPackagesToRemove.add(packageUserPair);
11764         }
11765 
11766         // All active admins on the user.
11767         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
11768 
11769         // Active admins in the target package.
11770         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
11771         if (allActiveAdmins != null) {
11772             for (ComponentName activeAdmin : allActiveAdmins) {
11773                 if (packageName.equals(activeAdmin.getPackageName())) {
11774                     packageActiveAdmins.add(activeAdmin);
11775                     removeActiveAdmin(activeAdmin, userId);
11776                 }
11777             }
11778         }
11779         if (packageActiveAdmins.size() == 0) {
11780             startUninstallIntent(packageName, userId);
11781         } else {
11782             mHandler.postDelayed(new Runnable() {
11783                 @Override
11784                 public void run() {
11785                     for (ComponentName activeAdmin : packageActiveAdmins) {
11786                         removeAdminArtifacts(activeAdmin, userId);
11787                     }
11788                     startUninstallIntent(packageName, userId);
11789                 }
11790             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
11791         }
11792     }
11793 
11794     @Override
isDeviceProvisioned()11795     public boolean isDeviceProvisioned() {
11796         enforceManageUsers();
11797         synchronized (getLockObject()) {
11798             return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete;
11799         }
11800     }
11801 
isCurrentUserDemo()11802     private boolean isCurrentUserDemo() {
11803         if (UserManager.isDeviceInDemoMode(mContext)) {
11804             final int userId = mInjector.userHandleGetCallingUserId();
11805             final long callingIdentity = mInjector.binderClearCallingIdentity();
11806             try {
11807                 return mUserManager.getUserInfo(userId).isDemo();
11808             } finally {
11809                 mInjector.binderRestoreCallingIdentity(callingIdentity);
11810             }
11811         }
11812         return false;
11813     }
11814 
removePackageIfRequired(final String packageName, final int userId)11815     private void removePackageIfRequired(final String packageName, final int userId) {
11816         if (!packageHasActiveAdmins(packageName, userId)) {
11817             // Will not do anything if uninstall was not requested or was already started.
11818             startUninstallIntent(packageName, userId);
11819         }
11820     }
11821 
startUninstallIntent(final String packageName, final int userId)11822     private void startUninstallIntent(final String packageName, final int userId) {
11823         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
11824         synchronized (getLockObject()) {
11825             if (!mPackagesToRemove.contains(packageUserPair)) {
11826                 // Do nothing if uninstall was not requested or was already started.
11827                 return;
11828             }
11829             mPackagesToRemove.remove(packageUserPair);
11830         }
11831         try {
11832             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
11833                 // Package does not exist. Nothing to do.
11834                 return;
11835             }
11836         } catch (RemoteException re) {
11837             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
11838         }
11839 
11840         try { // force stop the package before uninstalling
11841             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
11842         } catch (RemoteException re) {
11843             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
11844         }
11845         final Uri packageURI = Uri.parse("package:" + packageName);
11846         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
11847         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
11848         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
11849     }
11850 
11851     /**
11852      * Removes the admin from the policy. Ideally called after the admin's
11853      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
11854      *
11855      * @param adminReceiver The admin to remove
11856      * @param userHandle The user for which this admin has to be removed.
11857      */
removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle)11858     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
11859         synchronized (getLockObject()) {
11860             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
11861             if (admin == null) {
11862                 return;
11863             }
11864             final DevicePolicyData policy = getUserData(userHandle);
11865             final boolean doProxyCleanup = admin.info.usesPolicy(
11866                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
11867             policy.mAdminList.remove(admin);
11868             policy.mAdminMap.remove(adminReceiver);
11869             validatePasswordOwnerLocked(policy);
11870             if (doProxyCleanup) {
11871                 resetGlobalProxyLocked(policy);
11872             }
11873             pushActiveAdminPackagesLocked(userHandle);
11874             pushMeteredDisabledPackagesLocked(userHandle);
11875             saveSettingsLocked(userHandle);
11876             updateMaximumTimeToLockLocked(userHandle);
11877             policy.mRemovingAdmins.remove(adminReceiver);
11878 
11879             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
11880         }
11881         // The removed admin might have disabled camera, so update user
11882         // restrictions.
11883         pushUserRestrictions(userHandle);
11884     }
11885 
11886     @Override
setDeviceProvisioningConfigApplied()11887     public void setDeviceProvisioningConfigApplied() {
11888         enforceManageUsers();
11889         synchronized (getLockObject()) {
11890             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11891             policy.mDeviceProvisioningConfigApplied = true;
11892             saveSettingsLocked(UserHandle.USER_SYSTEM);
11893         }
11894     }
11895 
11896     @Override
isDeviceProvisioningConfigApplied()11897     public boolean isDeviceProvisioningConfigApplied() {
11898         enforceManageUsers();
11899         synchronized (getLockObject()) {
11900             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
11901             return policy.mDeviceProvisioningConfigApplied;
11902         }
11903     }
11904 
11905     /**
11906      * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE.
11907      *
11908      * It's added for testing only. Please use this API carefully if it's used by other system app
11909      * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system
11910      * apps.
11911      */
11912     @Override
forceUpdateUserSetupComplete()11913     public void forceUpdateUserSetupComplete() {
11914         enforceCanManageProfileAndDeviceOwners();
11915         enforceCallerSystemUserHandle();
11916         // no effect if it's called from user build
11917         if (!mInjector.isBuildDebuggable()) {
11918             return;
11919         }
11920         final int userId = UserHandle.USER_SYSTEM;
11921         boolean isUserCompleted = mInjector.settingsSecureGetIntForUser(
11922                 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0;
11923         DevicePolicyData policy = getUserData(userId);
11924         policy.mUserSetupComplete = isUserCompleted;
11925         synchronized (getLockObject()) {
11926             saveSettingsLocked(userId);
11927         }
11928     }
11929 
11930     // TODO(b/22388012): When backup is available for secondary users and profiles, consider
11931     // whether there are any privacy/security implications of enabling the backup service here
11932     // if there are other users or profiles unmanaged or managed by a different entity (i.e. not
11933     // affiliated).
11934     @Override
setBackupServiceEnabled(ComponentName admin, boolean enabled)11935     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
11936         if (!mHasFeature) {
11937             return;
11938         }
11939         Preconditions.checkNotNull(admin);
11940         synchronized (getLockObject()) {
11941             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(
11942                     admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11943             if (!enabled) {
11944                 activeAdmin.mandatoryBackupTransport = null;
11945                 saveSettingsLocked(UserHandle.USER_SYSTEM);
11946             }
11947         }
11948 
11949         final long ident = mInjector.binderClearCallingIdentity();
11950         try {
11951             IBackupManager ibm = mInjector.getIBackupManager();
11952             if (ibm != null) {
11953                 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
11954             }
11955         } catch (RemoteException e) {
11956             throw new IllegalStateException(
11957                 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
11958         } finally {
11959             mInjector.binderRestoreCallingIdentity(ident);
11960         }
11961     }
11962 
11963     @Override
isBackupServiceEnabled(ComponentName admin)11964     public boolean isBackupServiceEnabled(ComponentName admin) {
11965         Preconditions.checkNotNull(admin);
11966         if (!mHasFeature) {
11967             return true;
11968         }
11969         synchronized (getLockObject()) {
11970             try {
11971                 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11972                 IBackupManager ibm = mInjector.getIBackupManager();
11973                 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
11974             } catch (RemoteException e) {
11975                 throw new IllegalStateException("Failed requesting backup service state.", e);
11976             }
11977         }
11978     }
11979 
11980     @Override
setMandatoryBackupTransport( ComponentName admin, ComponentName backupTransportComponent)11981     public boolean setMandatoryBackupTransport(
11982             ComponentName admin,
11983             ComponentName backupTransportComponent) {
11984         if (!mHasFeature) {
11985             return false;
11986         }
11987         Preconditions.checkNotNull(admin);
11988         synchronized (getLockObject()) {
11989             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
11990         }
11991 
11992         final int callingUid = mInjector.binderGetCallingUid();
11993         final AtomicBoolean success = new AtomicBoolean(false);
11994         final CountDownLatch countDownLatch = new CountDownLatch(1);
11995         final ISelectBackupTransportCallback selectBackupTransportCallbackInternal =
11996                 new ISelectBackupTransportCallback.Stub() {
11997                     public void onSuccess(String transportName) {
11998                         saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent);
11999                         success.set(true);
12000                         countDownLatch.countDown();
12001                     }
12002 
12003                     public void onFailure(int reason) {
12004                         countDownLatch.countDown();
12005                     }
12006                 };
12007         final long identity = mInjector.binderClearCallingIdentity();
12008         try {
12009             IBackupManager ibm = mInjector.getIBackupManager();
12010             if (ibm != null && backupTransportComponent != null) {
12011                 if (!ibm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
12012                     ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, true);
12013                 }
12014                 ibm.selectBackupTransportAsync(
12015                         backupTransportComponent, selectBackupTransportCallbackInternal);
12016                 countDownLatch.await();
12017                 if (success.get()) {
12018                     ibm.setBackupEnabled(true);
12019                 }
12020             } else if (backupTransportComponent == null) {
12021                 saveMandatoryBackupTransport(admin, callingUid, backupTransportComponent);
12022                 success.set(true);
12023             }
12024         } catch (RemoteException e) {
12025             throw new IllegalStateException("Failed to set mandatory backup transport.", e);
12026         } catch (InterruptedException e) {
12027             throw new IllegalStateException("Failed to set mandatory backup transport.", e);
12028         } finally {
12029             mInjector.binderRestoreCallingIdentity(identity);
12030         }
12031         return success.get();
12032     }
12033 
saveMandatoryBackupTransport( ComponentName admin, int callingUid, ComponentName backupTransportComponent)12034     private void saveMandatoryBackupTransport(
12035             ComponentName admin, int callingUid, ComponentName backupTransportComponent) {
12036         synchronized (getLockObject()) {
12037             ActiveAdmin activeAdmin =
12038                     getActiveAdminWithPolicyForUidLocked(
12039                             admin,
12040                             DeviceAdminInfo.USES_POLICY_DEVICE_OWNER,
12041                             callingUid);
12042             if (!Objects.equals(backupTransportComponent,
12043                     activeAdmin.mandatoryBackupTransport)) {
12044                 activeAdmin.mandatoryBackupTransport =
12045                         backupTransportComponent;
12046                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12047             }
12048         }
12049     }
12050 
12051     @Override
getMandatoryBackupTransport()12052     public ComponentName getMandatoryBackupTransport() {
12053         if (!mHasFeature) {
12054             return null;
12055         }
12056         synchronized (getLockObject()) {
12057             ActiveAdmin activeAdmin = getDeviceOwnerAdminLocked();
12058             return activeAdmin == null ? null : activeAdmin.mandatoryBackupTransport;
12059         }
12060     }
12061 
12062 
12063     @Override
bindDeviceAdminServiceAsUser( @onNull ComponentName admin, @NonNull IApplicationThread caller, @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId)12064     public boolean bindDeviceAdminServiceAsUser(
12065             @NonNull ComponentName admin, @NonNull IApplicationThread caller,
12066             @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent,
12067             @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) {
12068         if (!mHasFeature) {
12069             return false;
12070         }
12071         Preconditions.checkNotNull(admin);
12072         Preconditions.checkNotNull(caller);
12073         Preconditions.checkNotNull(serviceIntent);
12074         Preconditions.checkArgument(
12075                 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null,
12076                 "Service intent must be explicit (with a package name or component): "
12077                         + serviceIntent);
12078         Preconditions.checkNotNull(connection);
12079         Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId,
12080                 "target user id must be different from the calling user id");
12081 
12082         if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) {
12083             throw new SecurityException("Not allowed to bind to target user id");
12084         }
12085 
12086         final String targetPackage;
12087         synchronized (getLockObject()) {
12088             targetPackage = getOwnerPackageNameForUserLocked(targetUserId);
12089         }
12090 
12091         final long callingIdentity = mInjector.binderClearCallingIdentity();
12092         try {
12093             // Validate and sanitize the incoming service intent.
12094             final Intent sanitizedIntent =
12095                     createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId);
12096             if (sanitizedIntent == null) {
12097                 // Fail, cannot lookup the target service.
12098                 return false;
12099             }
12100             // Ask ActivityManager to bind it. Notice that we are binding the service with the
12101             // caller app instead of DevicePolicyManagerService.
12102             return mInjector.getIActivityManager().bindService(
12103                     caller, activtiyToken, serviceIntent,
12104                     serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
12105                     connection, flags, mContext.getOpPackageName(),
12106                     targetUserId) != 0;
12107         } catch (RemoteException ex) {
12108             // Same process, should not happen.
12109         } finally {
12110             mInjector.binderRestoreCallingIdentity(callingIdentity);
12111         }
12112 
12113         // Failed to bind.
12114         return false;
12115     }
12116 
12117     @Override
getBindDeviceAdminTargetUsers(@onNull ComponentName admin)12118     public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) {
12119         if (!mHasFeature) {
12120             return Collections.emptyList();
12121         }
12122         Preconditions.checkNotNull(admin);
12123 
12124         synchronized (getLockObject()) {
12125             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12126 
12127             final int callingUserId = mInjector.userHandleGetCallingUserId();
12128             final long callingIdentity = mInjector.binderClearCallingIdentity();
12129             try {
12130                 ArrayList<UserHandle> targetUsers = new ArrayList<>();
12131                 if (!isDeviceOwner(admin, callingUserId)) {
12132                     // Profile owners can only bind to the device owner.
12133                     if (canUserBindToDeviceOwnerLocked(callingUserId)) {
12134                         targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId()));
12135                     }
12136                 } else {
12137                     // Caller is the device owner: Look for profile owners that it can bind to.
12138                     final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true);
12139                     for (int i = 0; i < userInfos.size(); i++) {
12140                         final int userId = userInfos.get(i).id;
12141                         if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) {
12142                             targetUsers.add(UserHandle.of(userId));
12143                         }
12144                     }
12145                 }
12146 
12147                 return targetUsers;
12148             } finally {
12149                 mInjector.binderRestoreCallingIdentity(callingIdentity);
12150             }
12151         }
12152     }
12153 
canUserBindToDeviceOwnerLocked(int userId)12154     private boolean canUserBindToDeviceOwnerLocked(int userId) {
12155         // There has to be a device owner, under another user id.
12156         if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) {
12157             return false;
12158         }
12159 
12160         // The user must have a profile owner that belongs to the same package as the device owner.
12161         if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals(
12162                 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) {
12163             return false;
12164         }
12165 
12166         // The user must be affiliated.
12167         return isUserAffiliatedWithDeviceLocked(userId);
12168     }
12169 
12170     /**
12171      * Return true if a given user has any accounts that'll prevent installing a device or profile
12172      * owner {@code owner}.
12173      * - If the user has no accounts, then return false.
12174      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
12175      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
12176      *   ..._DISALLOWED, return true.
12177      * - Otherwise return false.
12178      *
12179      * If the caller is *not* ADB, it also returns true.  The returned value shouldn't be used
12180      * when the caller is not ADB.
12181      *
12182      * DO NOT CALL IT WITH THE DPMS LOCK HELD.
12183      */
hasIncompatibleAccountsOrNonAdbNoLock( int userId, @Nullable ComponentName owner)12184     private boolean hasIncompatibleAccountsOrNonAdbNoLock(
12185             int userId, @Nullable ComponentName owner) {
12186         if (!isAdb()) {
12187             return true;
12188         }
12189         wtfIfInLock();
12190 
12191         final long token = mInjector.binderClearCallingIdentity();
12192         try {
12193             final AccountManager am = AccountManager.get(mContext);
12194             final Account accounts[] = am.getAccountsAsUser(userId);
12195             if (accounts.length == 0) {
12196                 return false;
12197             }
12198             synchronized (getLockObject()) {
12199                 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) {
12200                     Log.w(LOG_TAG,
12201                             "Non test-only owner can't be installed with existing accounts.");
12202                     return true;
12203                 }
12204             }
12205 
12206             final String[] feature_allow =
12207                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
12208             final String[] feature_disallow =
12209                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
12210 
12211             boolean compatible = true;
12212             for (Account account : accounts) {
12213                 if (hasAccountFeatures(am, account, feature_disallow)) {
12214                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
12215                     compatible = false;
12216                     break;
12217                 }
12218                 if (!hasAccountFeatures(am, account, feature_allow)) {
12219                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
12220                     compatible = false;
12221                     break;
12222                 }
12223             }
12224             if (compatible) {
12225                 Log.w(LOG_TAG, "All accounts are compatible");
12226             } else {
12227                 Log.e(LOG_TAG, "Found incompatible accounts");
12228             }
12229             return !compatible;
12230         } finally {
12231             mInjector.binderRestoreCallingIdentity(token);
12232         }
12233     }
12234 
hasAccountFeatures(AccountManager am, Account account, String[] features)12235     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
12236         try {
12237             return am.hasFeatures(account, features, null, null).getResult();
12238         } catch (Exception e) {
12239             Log.w(LOG_TAG, "Failed to get account feature", e);
12240             return false;
12241         }
12242     }
12243 
isAdb()12244     private boolean isAdb() {
12245         final int callingUid = mInjector.binderGetCallingUid();
12246         return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
12247     }
12248 
12249     @Override
setNetworkLoggingEnabled(ComponentName admin, boolean enabled)12250     public void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) {
12251         if (!mHasFeature) {
12252             return;
12253         }
12254         synchronized (getLockObject()) {
12255             Preconditions.checkNotNull(admin);
12256             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12257 
12258             if (enabled == isNetworkLoggingEnabledInternalLocked()) {
12259                 // already in the requested state
12260                 return;
12261             }
12262             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12263             deviceOwner.isNetworkLoggingEnabled = enabled;
12264             if (!enabled) {
12265                 deviceOwner.numNetworkLoggingNotifications = 0;
12266                 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
12267             }
12268             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12269 
12270             setNetworkLoggingActiveInternal(enabled);
12271         }
12272     }
12273 
setNetworkLoggingActiveInternal(boolean active)12274     private void setNetworkLoggingActiveInternal(boolean active) {
12275         synchronized (getLockObject()) {
12276             final long callingIdentity = mInjector.binderClearCallingIdentity();
12277             try {
12278                 if (active) {
12279                     mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal());
12280                     if (!mNetworkLogger.startNetworkLogging()) {
12281                         mNetworkLogger = null;
12282                         Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging"
12283                                 + " service not being available yet.");
12284                     }
12285                     maybePauseDeviceWideLoggingLocked();
12286                     sendNetworkLoggingNotificationLocked();
12287                 } else {
12288                     if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) {
12289                         Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging"
12290                                 + " service not being available yet.");
12291                     }
12292                     mNetworkLogger = null;
12293                     mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING);
12294                 }
12295             } finally {
12296                 mInjector.binderRestoreCallingIdentity(callingIdentity);
12297             }
12298         }
12299     }
12300 
12301     /** Pauses security and network logging if there are unaffiliated users on the device */
maybePauseDeviceWideLoggingLocked()12302     private void maybePauseDeviceWideLoggingLocked() {
12303         if (!areAllUsersAffiliatedWithDeviceLocked()) {
12304             Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be "
12305                     + "paused if enabled.");
12306             mSecurityLogMonitor.pause();
12307             if (mNetworkLogger != null) {
12308                 mNetworkLogger.pause();
12309             }
12310         }
12311     }
12312 
12313     /** Resumes security and network logging (if they are enabled) if all users are affiliated */
maybeResumeDeviceWideLoggingLocked()12314     private void maybeResumeDeviceWideLoggingLocked() {
12315         if (areAllUsersAffiliatedWithDeviceLocked()) {
12316             final long ident = mInjector.binderClearCallingIdentity();
12317             try {
12318                 mSecurityLogMonitor.resume();
12319                 if (mNetworkLogger != null) {
12320                     mNetworkLogger.resume();
12321                 }
12322             } finally {
12323                 mInjector.binderRestoreCallingIdentity(ident);
12324             }
12325         }
12326     }
12327 
12328     /** Deletes any security and network logs that might have been collected so far */
discardDeviceWideLogsLocked()12329     private void discardDeviceWideLogsLocked() {
12330         mSecurityLogMonitor.discardLogs();
12331         if (mNetworkLogger != null) {
12332             mNetworkLogger.discardLogs();
12333         }
12334         // TODO: We should discard pre-boot security logs here too, as otherwise those
12335         // logs (which might contain data from the user just removed) will be
12336         // available after next boot.
12337     }
12338 
12339     @Override
isNetworkLoggingEnabled(ComponentName admin)12340     public boolean isNetworkLoggingEnabled(ComponentName admin) {
12341         if (!mHasFeature) {
12342             return false;
12343         }
12344         synchronized (getLockObject()) {
12345             enforceDeviceOwnerOrManageUsers();
12346             return isNetworkLoggingEnabledInternalLocked();
12347         }
12348     }
12349 
isNetworkLoggingEnabledInternalLocked()12350     private boolean isNetworkLoggingEnabledInternalLocked() {
12351         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12352         return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled;
12353     }
12354 
12355     /*
12356      * A maximum of 1200 events are returned, and the total marshalled size is in the order of
12357      * 100kB, so returning a List instead of ParceledListSlice is acceptable.
12358      * Ideally this would be done with ParceledList, however it only supports homogeneous types.
12359      *
12360      * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH
12361      */
12362     @Override
retrieveNetworkLogs(ComponentName admin, long batchToken)12363     public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) {
12364         if (!mHasFeature) {
12365             return null;
12366         }
12367         Preconditions.checkNotNull(admin);
12368         ensureDeviceOwnerAndAllUsersAffiliated(admin);
12369 
12370         synchronized (getLockObject()) {
12371             if (mNetworkLogger == null
12372                     || !isNetworkLoggingEnabledInternalLocked()) {
12373                 return null;
12374             }
12375 
12376             final long currentTime = System.currentTimeMillis();
12377             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
12378             if (currentTime > policyData.mLastNetworkLogsRetrievalTime) {
12379                 policyData.mLastNetworkLogsRetrievalTime = currentTime;
12380                 saveSettingsLocked(UserHandle.USER_SYSTEM);
12381             }
12382             return mNetworkLogger.retrieveLogs(batchToken);
12383         }
12384     }
12385 
sendNetworkLoggingNotificationLocked()12386     private void sendNetworkLoggingNotificationLocked() {
12387         final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12388         if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) {
12389             return;
12390         }
12391         if (deviceOwner.numNetworkLoggingNotifications >=
12392                 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12393             return;
12394         }
12395         final long now = System.currentTimeMillis();
12396         if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) {
12397             return;
12398         }
12399         deviceOwner.numNetworkLoggingNotifications++;
12400         if (deviceOwner.numNetworkLoggingNotifications
12401                 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) {
12402             deviceOwner.lastNetworkLoggingNotificationTimeMs = 0;
12403         } else {
12404             deviceOwner.lastNetworkLoggingNotificationTimeMs = now;
12405         }
12406         final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG);
12407         intent.setPackage("com.android.systemui");
12408         final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0,
12409                 UserHandle.CURRENT);
12410         Notification notification =
12411                 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN)
12412                 .setSmallIcon(R.drawable.ic_info_outline)
12413                 .setContentTitle(mContext.getString(R.string.network_logging_notification_title))
12414                 .setContentText(mContext.getString(R.string.network_logging_notification_text))
12415                 .setTicker(mContext.getString(R.string.network_logging_notification_title))
12416                 .setShowWhen(true)
12417                 .setContentIntent(pendingIntent)
12418                 .setStyle(new Notification.BigTextStyle()
12419                         .bigText(mContext.getString(R.string.network_logging_notification_text)))
12420                 .build();
12421         mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification);
12422         saveSettingsLocked(mOwners.getDeviceOwnerUserId());
12423     }
12424 
12425     /**
12426      * Return the package name of owner in a given user.
12427      */
getOwnerPackageNameForUserLocked(int userId)12428     private String getOwnerPackageNameForUserLocked(int userId) {
12429         return mOwners.getDeviceOwnerUserId() == userId
12430                 ? mOwners.getDeviceOwnerPackageName()
12431                 : mOwners.getProfileOwnerPackage(userId);
12432     }
12433 
12434     /**
12435      * @param rawIntent Original service intent specified by caller. It must be explicit.
12436      * @param expectedPackageName The expected package name of the resolved service.
12437      * @return Intent that have component explicitly set. {@code null} if no service is resolved
12438      *     with the given intent.
12439      * @throws SecurityException if the intent is resolved to an invalid service.
12440      */
createCrossUserServiceIntent( @onNull Intent rawIntent, @NonNull String expectedPackageName, @UserIdInt int targetUserId)12441     private Intent createCrossUserServiceIntent(
12442             @NonNull Intent rawIntent, @NonNull String expectedPackageName,
12443             @UserIdInt int targetUserId) throws RemoteException, SecurityException {
12444         ResolveInfo info = mIPackageManager.resolveService(
12445                 rawIntent,
12446                 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()),
12447                 0,  // flags
12448                 targetUserId);
12449         if (info == null || info.serviceInfo == null) {
12450             Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent
12451                     + " or user " + targetUserId + " is not running");
12452             return null;
12453         }
12454         if (!expectedPackageName.equals(info.serviceInfo.packageName)) {
12455             throw new SecurityException("Only allow to bind service in " + expectedPackageName);
12456         }
12457         // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release.
12458         if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) {
12459             throw new SecurityException(
12460                     "Service must be protected by BIND_DEVICE_ADMIN permission");
12461         }
12462         // It is the system server to bind the service, it would be extremely dangerous if it
12463         // can be exploited to bind any service. Set the component explicitly to make sure we
12464         // do not bind anything accidentally.
12465         rawIntent.setComponent(info.serviceInfo.getComponentName());
12466         return rawIntent;
12467     }
12468 
12469     @Override
getLastSecurityLogRetrievalTime()12470     public long getLastSecurityLogRetrievalTime() {
12471         enforceDeviceOwnerOrManageUsers();
12472         return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime;
12473      }
12474 
12475     @Override
getLastBugReportRequestTime()12476     public long getLastBugReportRequestTime() {
12477         enforceDeviceOwnerOrManageUsers();
12478         return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime;
12479      }
12480 
12481     @Override
getLastNetworkLogRetrievalTime()12482     public long getLastNetworkLogRetrievalTime() {
12483         enforceDeviceOwnerOrManageUsers();
12484         return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime;
12485     }
12486 
12487     @Override
setResetPasswordToken(ComponentName admin, byte[] token)12488     public boolean setResetPasswordToken(ComponentName admin, byte[] token) {
12489         if (!mHasFeature) {
12490             return false;
12491         }
12492         if (token == null || token.length < 32) {
12493             throw new IllegalArgumentException("token must be at least 32-byte long");
12494         }
12495         synchronized (getLockObject()) {
12496             final int userHandle = mInjector.userHandleGetCallingUserId();
12497             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12498 
12499             DevicePolicyData policy = getUserData(userHandle);
12500             long ident = mInjector.binderClearCallingIdentity();
12501             try {
12502                 if (policy.mPasswordTokenHandle != 0) {
12503                     mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle);
12504                 }
12505 
12506                 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle);
12507                 saveSettingsLocked(userHandle);
12508                 return policy.mPasswordTokenHandle != 0;
12509             } finally {
12510                 mInjector.binderRestoreCallingIdentity(ident);
12511             }
12512         }
12513     }
12514 
12515     @Override
clearResetPasswordToken(ComponentName admin)12516     public boolean clearResetPasswordToken(ComponentName admin) {
12517         if (!mHasFeature) {
12518             return false;
12519         }
12520         synchronized (getLockObject()) {
12521             final int userHandle = mInjector.userHandleGetCallingUserId();
12522             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12523 
12524             DevicePolicyData policy = getUserData(userHandle);
12525             if (policy.mPasswordTokenHandle != 0) {
12526                 long ident = mInjector.binderClearCallingIdentity();
12527                 try {
12528                     boolean result = mLockPatternUtils.removeEscrowToken(
12529                             policy.mPasswordTokenHandle, userHandle);
12530                     policy.mPasswordTokenHandle = 0;
12531                     saveSettingsLocked(userHandle);
12532                     return result;
12533                 } finally {
12534                     mInjector.binderRestoreCallingIdentity(ident);
12535                 }
12536             }
12537         }
12538         return false;
12539     }
12540 
12541     @Override
isResetPasswordTokenActive(ComponentName admin)12542     public boolean isResetPasswordTokenActive(ComponentName admin) {
12543         synchronized (getLockObject()) {
12544             final int userHandle = mInjector.userHandleGetCallingUserId();
12545             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12546 
12547             DevicePolicyData policy = getUserData(userHandle);
12548             if (policy.mPasswordTokenHandle != 0) {
12549                 long ident = mInjector.binderClearCallingIdentity();
12550                 try {
12551                     return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle,
12552                             userHandle);
12553                 } finally {
12554                     mInjector.binderRestoreCallingIdentity(ident);
12555                 }
12556             }
12557         }
12558         return false;
12559     }
12560 
12561     @Override
resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, int flags)12562     public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token,
12563             int flags) {
12564         Preconditions.checkNotNull(token);
12565         synchronized (getLockObject()) {
12566             final int userHandle = mInjector.userHandleGetCallingUserId();
12567             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12568 
12569             DevicePolicyData policy = getUserData(userHandle);
12570             if (policy.mPasswordTokenHandle != 0) {
12571                 final String password = passwordOrNull != null ? passwordOrNull : "";
12572                 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token,
12573                         flags, mInjector.binderGetCallingUid(), userHandle);
12574             } else {
12575                 Slog.w(LOG_TAG, "No saved token handle");
12576             }
12577         }
12578         return false;
12579     }
12580 
12581     @Override
isCurrentInputMethodSetByOwner()12582     public boolean isCurrentInputMethodSetByOwner() {
12583         enforceProfileOwnerOrSystemUser();
12584         return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet;
12585     }
12586 
12587     @Override
getOwnerInstalledCaCerts(@onNull UserHandle user)12588     public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) {
12589         final int userId = user.getIdentifier();
12590         enforceProfileOwnerOrFullCrossUsersPermission(userId);
12591         synchronized (getLockObject()) {
12592             return new StringParceledListSlice(
12593                     new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts));
12594         }
12595     }
12596 
12597     @Override
clearApplicationUserData(ComponentName admin, String packageName, IPackageDataObserver callback)12598     public void clearApplicationUserData(ComponentName admin, String packageName,
12599             IPackageDataObserver callback) {
12600         Preconditions.checkNotNull(admin, "ComponentName is null");
12601         Preconditions.checkNotNull(packageName, "packageName is null");
12602         Preconditions.checkNotNull(callback, "callback is null");
12603         synchronized (getLockObject()) {
12604             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12605         }
12606         final int userId = UserHandle.getCallingUserId();
12607 
12608         long ident = mInjector.binderClearCallingIdentity();
12609         try {
12610             ActivityManager.getService().clearApplicationUserData(packageName, false, callback,
12611                     userId);
12612         } catch(RemoteException re) {
12613             // Same process, should not happen.
12614         } catch (SecurityException se) {
12615             // This can happen e.g. for device admin packages, do not throw out the exception,
12616             // because callers have no means to know beforehand for which packages this might
12617             // happen. If so, we send back that removal failed.
12618             Slog.w(LOG_TAG, "Not allowed to clear application user data for package " + packageName,
12619                     se);
12620             try {
12621                 callback.onRemoveCompleted(packageName, false);
12622             } catch (RemoteException re) {
12623                 // Caller is no longer available, ignore
12624             }
12625         } finally {
12626             mInjector.binderRestoreCallingIdentity(ident);
12627         }
12628     }
12629 
12630     @Override
setLogoutEnabled(ComponentName admin, boolean enabled)12631     public void setLogoutEnabled(ComponentName admin, boolean enabled) {
12632         if (!mHasFeature) {
12633             return;
12634         }
12635         Preconditions.checkNotNull(admin);
12636 
12637         synchronized (getLockObject()) {
12638             ActiveAdmin deviceOwner =
12639                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12640 
12641             if (deviceOwner.isLogoutEnabled == enabled) {
12642                 // already in the requested state
12643                 return;
12644             }
12645             deviceOwner.isLogoutEnabled = enabled;
12646             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12647         }
12648     }
12649 
12650     @Override
isLogoutEnabled()12651     public boolean isLogoutEnabled() {
12652         if (!mHasFeature) {
12653             return false;
12654         }
12655         synchronized (getLockObject()) {
12656             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
12657             return (deviceOwner != null) && deviceOwner.isLogoutEnabled;
12658         }
12659     }
12660 
12661     @Override
getDisallowedSystemApps(ComponentName admin, int userId, String provisioningAction)12662     public List<String> getDisallowedSystemApps(ComponentName admin, int userId,
12663             String provisioningAction) throws RemoteException {
12664         enforceCanManageProfileAndDeviceOwners();
12665         return new ArrayList<>(
12666                 mOverlayPackagesProvider.getNonRequiredApps(admin, userId, provisioningAction));
12667     }
12668 
12669     @Override
transferOwnership(@onNull ComponentName admin, @NonNull ComponentName target, @Nullable PersistableBundle bundle)12670     public void transferOwnership(@NonNull ComponentName admin, @NonNull ComponentName target,
12671             @Nullable PersistableBundle bundle) {
12672         if (!mHasFeature) {
12673             return;
12674         }
12675 
12676         Preconditions.checkNotNull(admin, "Admin cannot be null.");
12677         Preconditions.checkNotNull(target, "Target cannot be null.");
12678 
12679         enforceProfileOrDeviceOwner(admin);
12680 
12681         if (admin.equals(target)) {
12682             throw new IllegalArgumentException("Provided administrator and target are "
12683                     + "the same object.");
12684         }
12685 
12686         if (admin.getPackageName().equals(target.getPackageName())) {
12687             throw new IllegalArgumentException("Provided administrator and target have "
12688                     + "the same package name.");
12689         }
12690 
12691         final int callingUserId = mInjector.userHandleGetCallingUserId();
12692         final DevicePolicyData policy = getUserData(callingUserId);
12693         final DeviceAdminInfo incomingDeviceInfo = findAdmin(target, callingUserId,
12694                 /* throwForMissingPermission= */ true);
12695         checkActiveAdminPrecondition(target, incomingDeviceInfo, policy);
12696         if (!incomingDeviceInfo.supportsTransferOwnership()) {
12697             throw new IllegalArgumentException("Provided target does not support "
12698                     + "ownership transfer.");
12699         }
12700 
12701         final long id = mInjector.binderClearCallingIdentity();
12702         try {
12703             synchronized (getLockObject()) {
12704                 /*
12705                 * We must ensure the whole process is atomic to prevent the device from ending up
12706                 * in an invalid state (e.g. no active admin). This could happen if the device
12707                 * is rebooted or work mode is turned off mid-transfer.
12708                 * In order to guarantee atomicity, we:
12709                 *
12710                 * 1. Save an atomic journal file describing the transfer process
12711                 * 2. Perform the transfer itself
12712                 * 3. Delete the journal file
12713                 *
12714                 * That way if the journal file exists on device boot, we know that the transfer
12715                 * must be reverted back to the original administrator. This logic is implemented in
12716                 * revertTransferOwnershipIfNecessaryLocked.
12717                 * */
12718                 if (bundle == null) {
12719                     bundle = new PersistableBundle();
12720                 }
12721                 if (isProfileOwner(admin, callingUserId)) {
12722                     prepareTransfer(admin, target, bundle, callingUserId,
12723                             ADMIN_TYPE_PROFILE_OWNER);
12724                     transferProfileOwnershipLocked(admin, target, callingUserId);
12725                     sendProfileOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12726                             getTransferOwnershipAdminExtras(bundle), callingUserId);
12727                     postTransfer(DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED, callingUserId);
12728                     if (isUserAffiliatedWithDeviceLocked(callingUserId)) {
12729                         notifyAffiliatedProfileTransferOwnershipComplete(callingUserId);
12730                     }
12731                 } else if (isDeviceOwner(admin, callingUserId)) {
12732                     prepareTransfer(admin, target, bundle, callingUserId,
12733                             ADMIN_TYPE_DEVICE_OWNER);
12734                     transferDeviceOwnershipLocked(admin, target, callingUserId);
12735                     sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_TRANSFER_OWNERSHIP_COMPLETE,
12736                             getTransferOwnershipAdminExtras(bundle));
12737                     postTransfer(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED, callingUserId);
12738                 }
12739             }
12740         } finally {
12741             mInjector.binderRestoreCallingIdentity(id);
12742         }
12743     }
12744 
prepareTransfer(ComponentName admin, ComponentName target, PersistableBundle bundle, int callingUserId, String adminType)12745     private void prepareTransfer(ComponentName admin, ComponentName target,
12746             PersistableBundle bundle, int callingUserId, String adminType) {
12747         saveTransferOwnershipBundleLocked(bundle, callingUserId);
12748         mTransferOwnershipMetadataManager.saveMetadataFile(
12749                 new TransferOwnershipMetadataManager.Metadata(admin, target,
12750                         callingUserId, adminType));
12751     }
12752 
postTransfer(String broadcast, int callingUserId)12753     private void postTransfer(String broadcast, int callingUserId) {
12754         deleteTransferOwnershipMetadataFileLocked();
12755         sendOwnerChangedBroadcast(broadcast, callingUserId);
12756     }
12757 
notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId)12758     private void notifyAffiliatedProfileTransferOwnershipComplete(int callingUserId) {
12759         final Bundle extras = new Bundle();
12760         extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(callingUserId));
12761         sendDeviceOwnerCommand(
12762                 DeviceAdminReceiver.ACTION_AFFILIATED_PROFILE_TRANSFER_OWNERSHIP_COMPLETE, extras);
12763     }
12764 
12765     /**
12766      * Transfers the profile owner for user with id profileOwnerUserId from admin to target.
12767      */
transferProfileOwnershipLocked(ComponentName admin, ComponentName target, int profileOwnerUserId)12768     private void transferProfileOwnershipLocked(ComponentName admin, ComponentName target,
12769             int profileOwnerUserId) {
12770         transferActiveAdminUncheckedLocked(target, admin, profileOwnerUserId);
12771         mOwners.transferProfileOwner(target, profileOwnerUserId);
12772         Slog.i(LOG_TAG, "Profile owner set: " + target + " on user " + profileOwnerUserId);
12773         mOwners.writeProfileOwner(profileOwnerUserId);
12774         mDeviceAdminServiceController.startServiceForOwner(
12775                 target.getPackageName(), profileOwnerUserId, "transfer-profile-owner");
12776     }
12777 
12778     /**
12779      * Transfers the device owner for user with id userId from admin to target.
12780      */
transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId)12781     private void transferDeviceOwnershipLocked(ComponentName admin, ComponentName target, int userId) {
12782         transferActiveAdminUncheckedLocked(target, admin, userId);
12783         mOwners.transferDeviceOwnership(target);
12784         Slog.i(LOG_TAG, "Device owner set: " + target + " on user " + userId);
12785         mOwners.writeDeviceOwner();
12786         mDeviceAdminServiceController.startServiceForOwner(
12787                 target.getPackageName(), userId, "transfer-device-owner");
12788     }
12789 
getTransferOwnershipAdminExtras(PersistableBundle bundle)12790     private Bundle getTransferOwnershipAdminExtras(PersistableBundle bundle) {
12791         Bundle extras = new Bundle();
12792         if (bundle != null) {
12793             extras.putParcelable(EXTRA_TRANSFER_OWNERSHIP_ADMIN_EXTRAS_BUNDLE, bundle);
12794         }
12795         return extras;
12796     }
12797 
12798     @Override
setStartUserSessionMessage( ComponentName admin, CharSequence startUserSessionMessage)12799     public void setStartUserSessionMessage(
12800             ComponentName admin, CharSequence startUserSessionMessage) {
12801         if (!mHasFeature) {
12802             return;
12803         }
12804         Preconditions.checkNotNull(admin);
12805 
12806         final String startUserSessionMessageString =
12807                 startUserSessionMessage != null ? startUserSessionMessage.toString() : null;
12808 
12809         synchronized (getLockObject()) {
12810             final ActiveAdmin deviceOwner =
12811                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12812 
12813             if (TextUtils.equals(deviceOwner.startUserSessionMessage, startUserSessionMessage)) {
12814                 return;
12815             }
12816             deviceOwner.startUserSessionMessage = startUserSessionMessageString;
12817             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12818         }
12819 
12820         mInjector.getActivityManagerInternal()
12821                 .setSwitchingFromSystemUserMessage(startUserSessionMessageString);
12822     }
12823 
12824     @Override
setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage)12825     public void setEndUserSessionMessage(ComponentName admin, CharSequence endUserSessionMessage) {
12826         if (!mHasFeature) {
12827             return;
12828         }
12829         Preconditions.checkNotNull(admin);
12830 
12831         final String endUserSessionMessageString =
12832                 endUserSessionMessage != null ? endUserSessionMessage.toString() : null;
12833 
12834         synchronized (getLockObject()) {
12835             final ActiveAdmin deviceOwner =
12836                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12837 
12838             if (TextUtils.equals(deviceOwner.endUserSessionMessage, endUserSessionMessage)) {
12839                 return;
12840             }
12841             deviceOwner.endUserSessionMessage = endUserSessionMessageString;
12842             saveSettingsLocked(mInjector.userHandleGetCallingUserId());
12843         }
12844 
12845         mInjector.getActivityManagerInternal()
12846                 .setSwitchingToSystemUserMessage(endUserSessionMessageString);
12847     }
12848 
12849     @Override
getStartUserSessionMessage(ComponentName admin)12850     public String getStartUserSessionMessage(ComponentName admin) {
12851         if (!mHasFeature) {
12852             return null;
12853         }
12854         Preconditions.checkNotNull(admin);
12855 
12856         synchronized (getLockObject()) {
12857             final ActiveAdmin deviceOwner =
12858                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12859             return deviceOwner.startUserSessionMessage;
12860         }
12861     }
12862 
12863     @Override
getEndUserSessionMessage(ComponentName admin)12864     public String getEndUserSessionMessage(ComponentName admin) {
12865         if (!mHasFeature) {
12866             return null;
12867         }
12868         Preconditions.checkNotNull(admin);
12869 
12870         synchronized (getLockObject()) {
12871             final ActiveAdmin deviceOwner =
12872                     getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12873             return deviceOwner.endUserSessionMessage;
12874         }
12875     }
12876 
deleteTransferOwnershipMetadataFileLocked()12877     private void deleteTransferOwnershipMetadataFileLocked() {
12878         mTransferOwnershipMetadataManager.deleteMetadataFile();
12879     }
12880 
12881     @Override
12882     @Nullable
getTransferOwnershipBundle()12883     public PersistableBundle getTransferOwnershipBundle() {
12884         synchronized (getLockObject()) {
12885             final int callingUserId = mInjector.userHandleGetCallingUserId();
12886             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
12887             final File bundleFile = new File(
12888                     mInjector.environmentGetUserSystemDirectory(callingUserId),
12889                     TRANSFER_OWNERSHIP_PARAMETERS_XML);
12890             if (!bundleFile.exists()) {
12891                 return null;
12892             }
12893             try (FileInputStream stream = new FileInputStream(bundleFile)) {
12894                 XmlPullParser parser = Xml.newPullParser();
12895                 parser.setInput(stream, null);
12896                 parser.next();
12897                 return PersistableBundle.restoreFromXml(parser);
12898             } catch (IOException | XmlPullParserException | IllegalArgumentException e) {
12899                 Slog.e(LOG_TAG, "Caught exception while trying to load the "
12900                         + "owner transfer parameters from file " + bundleFile, e);
12901                 return null;
12902             }
12903         }
12904     }
12905 
12906     @Override
addOverrideApn(@onNull ComponentName who, @NonNull ApnSetting apnSetting)12907     public int addOverrideApn(@NonNull ComponentName who, @NonNull ApnSetting apnSetting) {
12908         if (!mHasFeature) {
12909             return -1;
12910         }
12911         Preconditions.checkNotNull(who, "ComponentName is null in addOverrideApn");
12912         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in addOverrideApn");
12913         synchronized (getLockObject()) {
12914             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12915         }
12916 
12917         int operatedId = -1;
12918         Uri resultUri;
12919         final long id = mInjector.binderClearCallingIdentity();
12920         try {
12921             resultUri = mContext.getContentResolver().insert(DPC_URI, apnSetting.toContentValues());
12922         } finally {
12923             mInjector.binderRestoreCallingIdentity(id);
12924         }
12925         if (resultUri != null) {
12926             try {
12927                 operatedId = Integer.parseInt(resultUri.getLastPathSegment());
12928             } catch (NumberFormatException e) {
12929                 Slog.e(LOG_TAG, "Failed to parse inserted override APN id.", e);
12930             }
12931         }
12932 
12933         return operatedId;
12934     }
12935 
12936     @Override
updateOverrideApn(@onNull ComponentName who, int apnId, @NonNull ApnSetting apnSetting)12937     public boolean updateOverrideApn(@NonNull ComponentName who, int apnId,
12938             @NonNull ApnSetting apnSetting) {
12939         if (!mHasFeature) {
12940             return false;
12941         }
12942         Preconditions.checkNotNull(who, "ComponentName is null in updateOverrideApn");
12943         Preconditions.checkNotNull(apnSetting, "ApnSetting is null in updateOverrideApn");
12944         synchronized (getLockObject()) {
12945             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12946         }
12947 
12948         if (apnId < 0) {
12949             return false;
12950         }
12951         final long id = mInjector.binderClearCallingIdentity();
12952         try {
12953             return mContext.getContentResolver().update(
12954                     Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)),
12955                     apnSetting.toContentValues(), null, null) > 0;
12956         } finally {
12957             mInjector.binderRestoreCallingIdentity(id);
12958         }
12959     }
12960 
12961     @Override
removeOverrideApn(@onNull ComponentName who, int apnId)12962     public boolean removeOverrideApn(@NonNull ComponentName who, int apnId) {
12963         if (!mHasFeature) {
12964             return false;
12965         }
12966         Preconditions.checkNotNull(who, "ComponentName is null in removeOverrideApn");
12967         synchronized (getLockObject()) {
12968             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12969         }
12970 
12971         return removeOverrideApnUnchecked(apnId);
12972     }
12973 
removeOverrideApnUnchecked(int apnId)12974     private boolean removeOverrideApnUnchecked(int apnId) {
12975         if(apnId < 0) {
12976             return false;
12977         }
12978         int numDeleted = 0;
12979         final long id = mInjector.binderClearCallingIdentity();
12980         try {
12981             numDeleted = mContext.getContentResolver().delete(
12982                     Uri.withAppendedPath(DPC_URI, Integer.toString(apnId)), null, null);
12983         } finally {
12984             mInjector.binderRestoreCallingIdentity(id);
12985         }
12986         return numDeleted > 0;
12987     }
12988 
12989     @Override
getOverrideApns(@onNull ComponentName who)12990     public List<ApnSetting> getOverrideApns(@NonNull ComponentName who) {
12991         if (!mHasFeature) {
12992             return Collections.emptyList();
12993         }
12994         Preconditions.checkNotNull(who, "ComponentName is null in getOverrideApns");
12995         synchronized (getLockObject()) {
12996             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
12997         }
12998 
12999         return getOverrideApnsUnchecked();
13000     }
13001 
getOverrideApnsUnchecked()13002     private List<ApnSetting> getOverrideApnsUnchecked() {
13003         final Cursor cursor;
13004         final long id = mInjector.binderClearCallingIdentity();
13005         try {
13006             cursor = mContext.getContentResolver().query(DPC_URI, null, null, null, null);
13007         } finally {
13008             mInjector.binderRestoreCallingIdentity(id);
13009         }
13010 
13011         if (cursor == null) {
13012             return Collections.emptyList();
13013         }
13014         try {
13015             List<ApnSetting> apnList = new ArrayList<ApnSetting>();
13016             cursor.moveToPosition(-1);
13017             while (cursor.moveToNext()) {
13018                 ApnSetting apn = ApnSetting.makeApnSetting(cursor);
13019                 apnList.add(apn);
13020             }
13021             return apnList;
13022         } finally {
13023             cursor.close();
13024         }
13025     }
13026 
13027     @Override
setOverrideApnsEnabled(@onNull ComponentName who, boolean enabled)13028     public void setOverrideApnsEnabled(@NonNull ComponentName who, boolean enabled) {
13029         if (!mHasFeature) {
13030             return;
13031         }
13032         Preconditions.checkNotNull(who, "ComponentName is null in setOverrideApnEnabled");
13033         synchronized (getLockObject()) {
13034             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13035         }
13036 
13037         setOverrideApnsEnabledUnchecked(enabled);
13038     }
13039 
setOverrideApnsEnabledUnchecked(boolean enabled)13040     private void setOverrideApnsEnabledUnchecked(boolean enabled) {
13041         ContentValues value = new ContentValues();
13042         value.put(ENFORCE_KEY, enabled);
13043         final long id = mInjector.binderClearCallingIdentity();
13044         try {
13045             mContext.getContentResolver().update(
13046                     ENFORCE_MANAGED_URI, value, null, null);
13047         } finally {
13048             mInjector.binderRestoreCallingIdentity(id);
13049         }
13050     }
13051 
13052     @Override
isOverrideApnEnabled(@onNull ComponentName who)13053     public boolean isOverrideApnEnabled(@NonNull ComponentName who) {
13054         if (!mHasFeature) {
13055             return false;
13056         }
13057         Preconditions.checkNotNull(who, "ComponentName is null in isOverrideApnEnabled");
13058         synchronized (getLockObject()) {
13059             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
13060         }
13061 
13062         Cursor enforceCursor;
13063         final long id = mInjector.binderClearCallingIdentity();
13064         try {
13065             enforceCursor = mContext.getContentResolver().query(
13066                     ENFORCE_MANAGED_URI, null, null, null, null);
13067         } finally {
13068             mInjector.binderRestoreCallingIdentity(id);
13069         }
13070 
13071         if (enforceCursor == null) {
13072             return false;
13073         }
13074         try {
13075             if (enforceCursor.moveToFirst()) {
13076                 return enforceCursor.getInt(enforceCursor.getColumnIndex(ENFORCE_KEY)) == 1;
13077             }
13078         } catch (IllegalArgumentException e) {
13079             Slog.e(LOG_TAG, "Cursor returned from ENFORCE_MANAGED_URI doesn't contain "
13080                     + "correct info.", e);
13081         } finally {
13082             enforceCursor.close();
13083         }
13084         return false;
13085     }
13086 
13087     @VisibleForTesting
saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId)13088     void saveTransferOwnershipBundleLocked(PersistableBundle bundle, int userId) {
13089         final File parametersFile = new File(
13090                 mInjector.environmentGetUserSystemDirectory(userId),
13091                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
13092         final AtomicFile atomicFile = new AtomicFile(parametersFile);
13093         FileOutputStream stream = null;
13094         try {
13095             stream = atomicFile.startWrite();
13096             final XmlSerializer serializer = new FastXmlSerializer();
13097             serializer.setOutput(stream, StandardCharsets.UTF_8.name());
13098             serializer.startDocument(null, true);
13099             serializer.startTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
13100             bundle.saveToXml(serializer);
13101             serializer.endTag(null, TAG_TRANSFER_OWNERSHIP_BUNDLE);
13102             serializer.endDocument();
13103             atomicFile.finishWrite(stream);
13104         } catch (IOException | XmlPullParserException e) {
13105             Slog.e(LOG_TAG, "Caught exception while trying to save the "
13106                     + "owner transfer parameters to file " + parametersFile, e);
13107             parametersFile.delete();
13108             atomicFile.failWrite(stream);
13109         }
13110     }
13111 
deleteTransferOwnershipBundleLocked(int userId)13112     void deleteTransferOwnershipBundleLocked(int userId) {
13113         final File parametersFile = new File(mInjector.environmentGetUserSystemDirectory(userId),
13114                 TRANSFER_OWNERSHIP_PARAMETERS_XML);
13115         parametersFile.delete();
13116     }
13117 
maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent, PasswordMetrics metrics)13118     private void maybeLogPasswordComplexitySet(ComponentName who, int userId, boolean parent,
13119             PasswordMetrics metrics) {
13120         if (SecurityLog.isLoggingEnabled()) {
13121             final int affectedUserId = parent ? getProfileParentId(userId) : userId;
13122             SecurityLog.writeEvent(SecurityLog.TAG_PASSWORD_COMPLEXITY_SET, who.getPackageName(),
13123                     userId, affectedUserId, metrics.length, metrics.quality, metrics.letters,
13124                     metrics.nonLetter, metrics.numeric, metrics.upperCase, metrics.lowerCase,
13125                     metrics.symbols);
13126         }
13127     }
13128 
getManagedProvisioningPackage(Context context)13129     private static String getManagedProvisioningPackage(Context context) {
13130         return context.getResources().getString(R.string.config_managed_provisioning_package);
13131     }
13132 }
13133