OSDN Git Service

DO NOT MERGE Do not call RecoverySystem with DPMS lock held am: 2317451acc am: 01f971dcdc
[android-x86/frameworks-base.git] / services / devicepolicy / java / com / android / server / devicepolicy / DevicePolicyManagerService.java
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.MANAGE_CA_CERTIFICATES;
20 import static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
21 import static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE;
22 import static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA;
23 import static android.content.pm.PackageManager.GET_UNINSTALLED_PACKAGES;
24
25 import static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW;
26 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
27 import static org.xmlpull.v1.XmlPullParser.END_TAG;
28 import static org.xmlpull.v1.XmlPullParser.TEXT;
29
30 import android.Manifest.permission;
31 import android.accessibilityservice.AccessibilityServiceInfo;
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.annotation.IntDef;
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.annotation.UserIdInt;
38 import android.app.Activity;
39 import android.app.ActivityManager;
40 import android.app.ActivityManagerNative;
41 import android.app.AlarmManager;
42 import android.app.AppGlobals;
43 import android.app.IActivityManager;
44 import android.app.Notification;
45 import android.app.NotificationManager;
46 import android.app.PendingIntent;
47 import android.app.StatusBarManager;
48 import android.app.admin.DeviceAdminInfo;
49 import android.app.admin.DeviceAdminReceiver;
50 import android.app.admin.DevicePolicyManager;
51 import android.app.admin.DevicePolicyManagerInternal;
52 import android.app.admin.IDevicePolicyManager;
53 import android.app.admin.SecurityLog;
54 import android.app.admin.SecurityLog.SecurityEvent;
55 import android.app.admin.SystemUpdatePolicy;
56 import android.app.backup.IBackupManager;
57 import android.app.trust.TrustManager;
58 import android.content.BroadcastReceiver;
59 import android.content.ComponentName;
60 import android.content.Context;
61 import android.content.Intent;
62 import android.content.IntentFilter;
63 import android.content.pm.ActivityInfo;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.IPackageManager;
66 import android.content.pm.PackageInfo;
67 import android.content.pm.PackageManager;
68 import android.content.pm.PackageManager.NameNotFoundException;
69 import android.content.pm.PackageManagerInternal;
70 import android.content.pm.ParceledListSlice;
71 import android.content.pm.ResolveInfo;
72 import android.content.pm.ServiceInfo;
73 import android.content.pm.UserInfo;
74 import android.database.ContentObserver;
75 import android.graphics.Bitmap;
76 import android.graphics.Color;
77 import android.media.AudioManager;
78 import android.media.IAudioService;
79 import android.net.ConnectivityManager;
80 import android.net.ProxyInfo;
81 import android.net.Uri;
82 import android.net.wifi.WifiInfo;
83 import android.net.wifi.WifiManager;
84 import android.os.AsyncTask;
85 import android.os.Binder;
86 import android.os.Build;
87 import android.os.Bundle;
88 import android.os.Environment;
89 import android.os.FileUtils;
90 import android.os.Handler;
91 import android.os.IBinder;
92 import android.os.Looper;
93 import android.os.ParcelFileDescriptor;
94 import android.os.PersistableBundle;
95 import android.os.PowerManager;
96 import android.os.PowerManagerInternal;
97 import android.os.Process;
98 import android.os.RecoverySystem;
99 import android.os.RemoteCallback;
100 import android.os.RemoteException;
101 import android.os.ServiceManager;
102 import android.os.SystemClock;
103 import android.os.SystemProperties;
104 import android.os.UserHandle;
105 import android.os.UserManager;
106 import android.os.UserManagerInternal;
107 import android.os.storage.StorageManager;
108 import android.provider.ContactsContract.QuickContact;
109 import android.provider.ContactsInternal;
110 import android.provider.Settings;
111 import android.security.Credentials;
112 import android.security.IKeyChainAliasCallback;
113 import android.security.IKeyChainService;
114 import android.security.KeyChain;
115 import android.security.KeyChain.KeyChainConnection;
116 import android.service.persistentdata.PersistentDataBlockManager;
117 import android.telephony.TelephonyManager;
118 import android.text.TextUtils;
119 import android.util.ArrayMap;
120 import android.util.ArraySet;
121 import android.util.Log;
122 import android.util.Pair;
123 import android.util.Slog;
124 import android.util.SparseArray;
125 import android.util.Xml;
126 import android.view.IWindowManager;
127 import android.view.accessibility.AccessibilityManager;
128 import android.view.accessibility.IAccessibilityManager;
129 import android.view.inputmethod.InputMethodInfo;
130 import android.view.inputmethod.InputMethodManager;
131
132 import com.android.internal.R;
133 import com.android.internal.annotations.VisibleForTesting;
134 import com.android.internal.statusbar.IStatusBarService;
135 import com.android.internal.util.FastXmlSerializer;
136 import com.android.internal.util.JournaledFile;
137 import com.android.internal.util.ParcelableString;
138 import com.android.internal.util.Preconditions;
139 import com.android.internal.util.XmlUtils;
140 import com.android.internal.widget.LockPatternUtils;
141 import com.android.server.LocalServices;
142 import com.android.server.SystemService;
143 import com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo;
144 import com.android.server.pm.UserRestrictionsUtils;
145 import com.google.android.collect.Sets;
146
147 import org.xmlpull.v1.XmlPullParser;
148 import org.xmlpull.v1.XmlPullParserException;
149 import org.xmlpull.v1.XmlSerializer;
150
151 import java.io.ByteArrayInputStream;
152 import java.io.File;
153 import java.io.FileDescriptor;
154 import java.io.FileInputStream;
155 import java.io.FileNotFoundException;
156 import java.io.FileOutputStream;
157 import java.io.IOException;
158 import java.io.PrintWriter;
159 import java.lang.annotation.Retention;
160 import java.lang.annotation.RetentionPolicy;
161 import java.nio.charset.StandardCharsets;
162 import java.security.cert.CertificateException;
163 import java.security.cert.CertificateFactory;
164 import java.security.cert.X509Certificate;
165 import java.text.DateFormat;
166 import java.util.ArrayList;
167 import java.util.Arrays;
168 import java.util.Collections;
169 import java.util.Date;
170 import java.util.List;
171 import java.util.Map.Entry;
172 import java.util.Set;
173 import java.util.concurrent.atomic.AtomicBoolean;
174
175 /**
176  * Implementation of the device policy APIs.
177  */
178 public class DevicePolicyManagerService extends IDevicePolicyManager.Stub {
179
180     private static final String LOG_TAG = "DevicePolicyManagerService";
181
182     private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE
183
184     private static final String DEVICE_POLICIES_XML = "device_policies.xml";
185
186     private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate";
187
188     private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component";
189
190     private static final String TAG_STATUS_BAR = "statusbar";
191
192     private static final String ATTR_DISABLED = "disabled";
193
194     private static final String ATTR_NAME = "name";
195
196     private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML =
197             "do-not-ask-credentials-on-boot";
198
199     private static final String TAG_AFFILIATION_ID = "affiliation-id";
200
201     private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending";
202
203     private static final String ATTR_VALUE = "value";
204
205     private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle";
206
207     private static final int REQUEST_EXPIRE_PASSWORD = 5571;
208
209     private static final long MS_PER_DAY = 86400 * 1000;
210
211     private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms
212
213     private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION
214             = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION";
215
216     private static final int MONITORING_CERT_NOTIFICATION_ID = R.plurals.ssl_ca_cert_warning;
217     private static final int PROFILE_WIPED_NOTIFICATION_ID = 1001;
218
219     private static final String ATTR_PERMISSION_PROVIDER = "permission-provider";
220     private static final String ATTR_SETUP_COMPLETE = "setup-complete";
221     private static final String ATTR_PROVISIONING_STATE = "provisioning-state";
222     private static final String ATTR_PERMISSION_POLICY = "permission-policy";
223     private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED =
224             "device-provisioning-config-applied";
225     private static final String ATTR_DEVICE_PAIRED = "device-paired";
226
227     private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer";
228     private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER
229             = "application-restrictions-manager";
230
231     /**
232      *  System property whose value is either "true" or "false", indicating whether
233      */
234     private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner";
235
236     private static final int STATUS_BAR_DISABLE_MASK =
237             StatusBarManager.DISABLE_EXPAND |
238             StatusBarManager.DISABLE_NOTIFICATION_ICONS |
239             StatusBarManager.DISABLE_NOTIFICATION_ALERTS |
240             StatusBarManager.DISABLE_SEARCH;
241
242     private static final int STATUS_BAR_DISABLE2_MASK =
243             StatusBarManager.DISABLE2_QUICK_SETTINGS;
244
245     private static final Set<String> SECURE_SETTINGS_WHITELIST;
246     private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST;
247     private static final Set<String> GLOBAL_SETTINGS_WHITELIST;
248     private static final Set<String> GLOBAL_SETTINGS_DEPRECATED;
249     static {
250         SECURE_SETTINGS_WHITELIST = new ArraySet<>();
251         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD);
252         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS);
253         SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS);
254
255         SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>();
256         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST);
257         SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE);
258
259         GLOBAL_SETTINGS_WHITELIST = new ArraySet<>();
260         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED);
261         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME);
262         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE);
263         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING);
264         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED);
265         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY);
266         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN);
267         GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN);
268
269         GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>();
270         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON);
271         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED);
272         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER);
273         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE);
274         GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON);
275     }
276
277     /**
278      * Keyguard features that when set on a managed profile that doesn't have its own challenge will
279      * affect the profile's parent user. These can also be set on the managed profile's parent DPM
280      * instance.
281      */
282     private static final int PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER =
283             DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS
284             | DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT;
285
286     /**
287      * Keyguard features that when set on a profile affect the profile content or challenge only.
288      * These cannot be set on the managed profile's parent DPM instance
289      */
290     private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY =
291             DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS;
292
293     /** Keyguard features that are allowed to be set on a managed profile */
294     private static final int PROFILE_KEYGUARD_FEATURES =
295             PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY;
296
297     private static final int CODE_OK = 0;
298     private static final int CODE_HAS_DEVICE_OWNER = 1;
299     private static final int CODE_USER_HAS_PROFILE_OWNER = 2;
300     private static final int CODE_USER_NOT_RUNNING = 3;
301     private static final int CODE_USER_SETUP_COMPLETED = 4;
302     private static final int CODE_NONSYSTEM_USER_EXISTS = 5;
303     private static final int CODE_ACCOUNTS_NOT_EMPTY = 6;
304     private static final int CODE_NOT_SYSTEM_USER = 7;
305     private static final int CODE_HAS_PAIRED = 8;
306
307     @Retention(RetentionPolicy.SOURCE)
308     @IntDef({ CODE_OK, CODE_HAS_DEVICE_OWNER, CODE_USER_HAS_PROFILE_OWNER, CODE_USER_NOT_RUNNING,
309             CODE_USER_SETUP_COMPLETED, CODE_NOT_SYSTEM_USER })
310     private @interface DeviceOwnerPreConditionCode {}
311
312     private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000;
313
314     /**
315      * Minimum timeout in milliseconds after which unlocking with weak auth times out,
316      * i.e. the user has to use a strong authentication method like password, PIN or pattern.
317      */
318     private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = 1 * 60 * 60 * 1000; // 1h
319
320     final Context mContext;
321     final Injector mInjector;
322     final IPackageManager mIPackageManager;
323     final UserManager mUserManager;
324     final UserManagerInternal mUserManagerInternal;
325     final TelephonyManager mTelephonyManager;
326     private final LockPatternUtils mLockPatternUtils;
327
328     /**
329      * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p
330      * is requested for user u.
331      */
332     private final Set<Pair<String, Integer>> mPackagesToRemove =
333             new ArraySet<Pair<String, Integer>>();
334
335     final LocalService mLocalService;
336
337     // Stores and loads state on device and profile owners.
338     @VisibleForTesting
339     final Owners mOwners;
340
341     private final Binder mToken = new Binder();
342
343     /**
344      * Whether or not device admin feature is supported. If it isn't return defaults for all
345      * public methods.
346      */
347     boolean mHasFeature;
348
349     /**
350      * Whether or not this device is a watch.
351      */
352     boolean mIsWatch;
353
354     private final SecurityLogMonitor mSecurityLogMonitor;
355
356     private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean();
357     private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean();
358
359     private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() {
360         @Override
361         public void run() {
362             if(mRemoteBugreportServiceIsActive.get()) {
363                 onBugreportFailed();
364             }
365         }
366     };
367
368     private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() {
369
370         @Override
371         public void onReceive(Context context, Intent intent) {
372             if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction())
373                     && mRemoteBugreportServiceIsActive.get()) {
374                 onBugreportFinished(intent);
375             }
376         }
377     };
378
379     private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() {
380
381         @Override
382         public void onReceive(Context context, Intent intent) {
383             String action = intent.getAction();
384             mInjector.getNotificationManager().cancel(LOG_TAG,
385                     RemoteBugreportUtils.NOTIFICATION_ID);
386             if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) {
387                 onBugreportSharingAccepted();
388             } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) {
389                 onBugreportSharingDeclined();
390             }
391             mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
392         }
393     };
394
395     public static final class Lifecycle extends SystemService {
396         private DevicePolicyManagerService mService;
397
398         public Lifecycle(Context context) {
399             super(context);
400             mService = new DevicePolicyManagerService(context);
401         }
402
403         @Override
404         public void onStart() {
405             publishBinderService(Context.DEVICE_POLICY_SERVICE, mService);
406         }
407
408         @Override
409         public void onBootPhase(int phase) {
410             mService.systemReady(phase);
411         }
412
413         @Override
414         public void onStartUser(int userHandle) {
415             mService.onStartUser(userHandle);
416         }
417     }
418
419     public static class DevicePolicyData {
420         int mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
421         int mActivePasswordLength = 0;
422         int mActivePasswordUpperCase = 0;
423         int mActivePasswordLowerCase = 0;
424         int mActivePasswordLetters = 0;
425         int mActivePasswordNumeric = 0;
426         int mActivePasswordSymbols = 0;
427         int mActivePasswordNonLetter = 0;
428         int mFailedPasswordAttempts = 0;
429
430         int mUserHandle;
431         int mPasswordOwner = -1;
432         long mLastMaximumTimeToLock = -1;
433         boolean mUserSetupComplete = false;
434         boolean mPaired = false;
435         int mUserProvisioningState;
436         int mPermissionPolicy;
437
438         boolean mDeviceProvisioningConfigApplied = false;
439
440         final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>();
441         final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>();
442         final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>();
443
444         final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>();
445
446         // This is the list of component allowed to start lock task mode.
447         List<String> mLockTaskPackages = new ArrayList<>();
448
449         boolean mStatusBarDisabled = false;
450
451         ComponentName mRestrictionsProvider;
452
453         String mDelegatedCertInstallerPackage;
454
455         boolean doNotAskCredentialsOnBoot = false;
456
457         String mApplicationRestrictionsManagingPackage;
458
459         Set<String> mAffiliationIds = new ArraySet<>();
460
461         // Used for initialization of users created by createAndManageUsers.
462         boolean mAdminBroadcastPending = false;
463         PersistableBundle mInitBundle = null;
464
465         public DevicePolicyData(int userHandle) {
466             mUserHandle = userHandle;
467         }
468     }
469
470     final SparseArray<DevicePolicyData> mUserData = new SparseArray<>();
471
472     final Handler mHandler;
473
474     BroadcastReceiver mReceiver = new BroadcastReceiver() {
475         @Override
476         public void onReceive(Context context, Intent intent) {
477             final String action = intent.getAction();
478             final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
479                     getSendingUserId());
480
481             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
482                     && userHandle == mOwners.getDeviceOwnerUserId()
483                     && getDeviceOwnerRemoteBugreportUri() != null) {
484                 IntentFilter filterConsent = new IntentFilter();
485                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
486                 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
487                 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
488                 mInjector.getNotificationManager().notifyAsUser(LOG_TAG,
489                         RemoteBugreportUtils.NOTIFICATION_ID,
490                         RemoteBugreportUtils.buildNotification(mContext,
491                                 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
492                                 UserHandle.ALL);
493             }
494             if (Intent.ACTION_BOOT_COMPLETED.equals(action)
495                     || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
496                 if (VERBOSE_LOG) {
497                     Slog.v(LOG_TAG, "Sending password expiration notifications for action "
498                             + action + " for user " + userHandle);
499                 }
500                 mHandler.post(new Runnable() {
501                     @Override
502                     public void run() {
503                         handlePasswordExpirationNotification(userHandle);
504                     }
505                 });
506             }
507             if (Intent.ACTION_USER_UNLOCKED.equals(action)
508                     || Intent.ACTION_USER_STARTED.equals(action)
509                     || KeyChain.ACTION_STORAGE_CHANGED.equals(action)) {
510                 int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_ALL);
511                 new MonitoringCertNotificationTask().execute(userId);
512             }
513             if (Intent.ACTION_USER_ADDED.equals(action)) {
514                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
515             } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
516                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
517                 removeUserData(userHandle);
518             } else if (Intent.ACTION_USER_STARTED.equals(action)) {
519                 synchronized (DevicePolicyManagerService.this) {
520                     // Reset the policy data
521                     mUserData.remove(userHandle);
522                     sendAdminEnabledBroadcastLocked(userHandle);
523                 }
524                 handlePackagesChanged(null /* check all admins */, userHandle);
525             } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
526                 handlePackagesChanged(null /* check all admins */, userHandle);
527             } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action)
528                     || (Intent.ACTION_PACKAGE_ADDED.equals(action)
529                             && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) {
530                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
531             } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
532                     && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
533                 handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle);
534             } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) {
535                 clearWipeProfileNotification();
536             }
537         }
538     };
539
540     static class ActiveAdmin {
541         private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features";
542         private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin";
543         private static final String TAG_DISABLE_CAMERA = "disable-camera";
544         private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id";
545         private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search";
546         private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING
547                 = "disable-bt-contacts-sharing";
548         private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture";
549         private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management";
550         private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time";
551         private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users";
552         private static final String TAG_ACCOUNT_TYPE = "account-type";
553         private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES
554                 = "permitted-accessiblity-services";
555         private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested";
556         private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features";
557         private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options";
558         private static final String TAG_TRUST_AGENT_COMPONENT = "component";
559         private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date";
560         private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout";
561         private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list";
562         private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec";
563         private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy";
564         private static final String TAG_PERMITTED_IMES = "permitted-imes";
565         private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe";
566         private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock";
567         private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout";
568         private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter";
569         private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols";
570         private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric";
571         private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters";
572         private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase";
573         private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase";
574         private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length";
575         private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length";
576         private static final String ATTR_VALUE = "value";
577         private static final String TAG_PASSWORD_QUALITY = "password-quality";
578         private static final String TAG_POLICIES = "policies";
579         private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS =
580                 "cross-profile-widget-providers";
581         private static final String TAG_PROVIDER = "provider";
582         private static final String TAG_PACKAGE_LIST_ITEM  = "item";
583         private static final String TAG_KEEP_UNINSTALLED_PACKAGES  = "keep-uninstalled-packages";
584         private static final String TAG_USER_RESTRICTIONS = "user-restrictions";
585         private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message";
586         private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message";
587         private static final String TAG_PARENT_ADMIN = "parent-admin";
588         private static final String TAG_ORGANIZATION_COLOR = "organization-color";
589         private static final String TAG_ORGANIZATION_NAME = "organization-name";
590
591         final DeviceAdminInfo info;
592
593         int passwordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
594
595         static final int DEF_MINIMUM_PASSWORD_LENGTH = 0;
596         int minimumPasswordLength = DEF_MINIMUM_PASSWORD_LENGTH;
597
598         static final int DEF_PASSWORD_HISTORY_LENGTH = 0;
599         int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH;
600
601         static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0;
602         int minimumPasswordUpperCase = DEF_MINIMUM_PASSWORD_UPPER_CASE;
603
604         static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0;
605         int minimumPasswordLowerCase = DEF_MINIMUM_PASSWORD_LOWER_CASE;
606
607         static final int DEF_MINIMUM_PASSWORD_LETTERS = 1;
608         int minimumPasswordLetters = DEF_MINIMUM_PASSWORD_LETTERS;
609
610         static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1;
611         int minimumPasswordNumeric = DEF_MINIMUM_PASSWORD_NUMERIC;
612
613         static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1;
614         int minimumPasswordSymbols = DEF_MINIMUM_PASSWORD_SYMBOLS;
615
616         static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0;
617         int minimumPasswordNonLetter = DEF_MINIMUM_PASSWORD_NON_LETTER;
618
619         static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0;
620         long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK;
621
622         long strongAuthUnlockTimeout = 0; // admin doesn't participate by default
623
624         static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0;
625         int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE;
626
627         static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0;
628         long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT;
629
630         static final long DEF_PASSWORD_EXPIRATION_DATE = 0;
631         long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE;
632
633         static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none
634
635         int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED;
636
637         boolean encryptionRequested = false;
638         boolean testOnlyAdmin = false;
639         boolean disableCamera = false;
640         boolean disableCallerId = false;
641         boolean disableContactsSearch = false;
642         boolean disableBluetoothContactSharing = true;
643         boolean disableScreenCapture = false; // Can only be set by a device/profile owner.
644         boolean requireAutoTime = false; // Can only be set by a device owner.
645         boolean forceEphemeralUsers = false; // Can only be set by a device owner.
646
647         ActiveAdmin parentAdmin;
648         final boolean isParent;
649
650         static class TrustAgentInfo {
651             public PersistableBundle options;
652             TrustAgentInfo(PersistableBundle bundle) {
653                 options = bundle;
654             }
655         }
656
657         Set<String> accountTypesWithManagementDisabled = new ArraySet<>();
658
659         // The list of permitted accessibility services package namesas set by a profile
660         // or device owner. Null means all accessibility services are allowed, empty means
661         // none except system services are allowed.
662         List<String> permittedAccessiblityServices;
663
664         // The list of permitted input methods package names as set by a profile or device owner.
665         // Null means all input methods are allowed, empty means none except system imes are
666         // allowed.
667         List<String> permittedInputMethods;
668
669         // List of package names to keep cached.
670         List<String> keepUninstalledPackages;
671
672         // TODO: review implementation decisions with frameworks team
673         boolean specifiesGlobalProxy = false;
674         String globalProxySpec = null;
675         String globalProxyExclusionList = null;
676
677         ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>();
678
679         List<String> crossProfileWidgetProviders;
680
681         Bundle userRestrictions;
682
683         // Support text provided by the admin to display to the user.
684         CharSequence shortSupportMessage = null;
685         CharSequence longSupportMessage = null;
686
687         // Background color of confirm credentials screen. Default: teal.
688         static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B");
689         int organizationColor = DEF_ORGANIZATION_COLOR;
690
691         // Default title of confirm credentials screen
692         String organizationName = null;
693
694         ActiveAdmin(DeviceAdminInfo _info, boolean parent) {
695             info = _info;
696             isParent = parent;
697         }
698
699         ActiveAdmin getParentActiveAdmin() {
700             Preconditions.checkState(!isParent);
701
702             if (parentAdmin == null) {
703                 parentAdmin = new ActiveAdmin(info, /* parent */ true);
704             }
705             return parentAdmin;
706         }
707
708         boolean hasParentActiveAdmin() {
709             return parentAdmin != null;
710         }
711
712         int getUid() { return info.getActivityInfo().applicationInfo.uid; }
713
714         public UserHandle getUserHandle() {
715             return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid));
716         }
717
718         void writeToXml(XmlSerializer out)
719                 throws IllegalArgumentException, IllegalStateException, IOException {
720             out.startTag(null, TAG_POLICIES);
721             info.writePoliciesToXml(out);
722             out.endTag(null, TAG_POLICIES);
723             if (passwordQuality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
724                 out.startTag(null, TAG_PASSWORD_QUALITY);
725                 out.attribute(null, ATTR_VALUE, Integer.toString(passwordQuality));
726                 out.endTag(null, TAG_PASSWORD_QUALITY);
727                 if (minimumPasswordLength != DEF_MINIMUM_PASSWORD_LENGTH) {
728                     out.startTag(null, TAG_MIN_PASSWORD_LENGTH);
729                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLength));
730                     out.endTag(null, TAG_MIN_PASSWORD_LENGTH);
731                 }
732                 if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) {
733                     out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH);
734                     out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength));
735                     out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH);
736                 }
737                 if (minimumPasswordUpperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) {
738                     out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE);
739                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordUpperCase));
740                     out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE);
741                 }
742                 if (minimumPasswordLowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) {
743                     out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE);
744                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLowerCase));
745                     out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE);
746                 }
747                 if (minimumPasswordLetters != DEF_MINIMUM_PASSWORD_LETTERS) {
748                     out.startTag(null, TAG_MIN_PASSWORD_LETTERS);
749                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordLetters));
750                     out.endTag(null, TAG_MIN_PASSWORD_LETTERS);
751                 }
752                 if (minimumPasswordNumeric != DEF_MINIMUM_PASSWORD_NUMERIC) {
753                     out.startTag(null, TAG_MIN_PASSWORD_NUMERIC);
754                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNumeric));
755                     out.endTag(null, TAG_MIN_PASSWORD_NUMERIC);
756                 }
757                 if (minimumPasswordSymbols != DEF_MINIMUM_PASSWORD_SYMBOLS) {
758                     out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS);
759                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordSymbols));
760                     out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS);
761                 }
762                 if (minimumPasswordNonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) {
763                     out.startTag(null, TAG_MIN_PASSWORD_NONLETTER);
764                     out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordNonLetter));
765                     out.endTag(null, TAG_MIN_PASSWORD_NONLETTER);
766                 }
767             }
768             if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) {
769                 out.startTag(null, TAG_MAX_TIME_TO_UNLOCK);
770                 out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock));
771                 out.endTag(null, TAG_MAX_TIME_TO_UNLOCK);
772             }
773             if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
774                 out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
775                 out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout));
776                 out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT);
777             }
778             if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
779                 out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
780                 out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe));
781                 out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE);
782             }
783             if (specifiesGlobalProxy) {
784                 out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
785                 out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy));
786                 out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY);
787                 if (globalProxySpec != null) {
788                     out.startTag(null, TAG_GLOBAL_PROXY_SPEC);
789                     out.attribute(null, ATTR_VALUE, globalProxySpec);
790                     out.endTag(null, TAG_GLOBAL_PROXY_SPEC);
791                 }
792                 if (globalProxyExclusionList != null) {
793                     out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
794                     out.attribute(null, ATTR_VALUE, globalProxyExclusionList);
795                     out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST);
796                 }
797             }
798             if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) {
799                 out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
800                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout));
801                 out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT);
802             }
803             if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) {
804                 out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE);
805                 out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate));
806                 out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE);
807             }
808             if (encryptionRequested) {
809                 out.startTag(null, TAG_ENCRYPTION_REQUESTED);
810                 out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested));
811                 out.endTag(null, TAG_ENCRYPTION_REQUESTED);
812             }
813             if (testOnlyAdmin) {
814                 out.startTag(null, TAG_TEST_ONLY_ADMIN);
815                 out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin));
816                 out.endTag(null, TAG_TEST_ONLY_ADMIN);
817             }
818             if (disableCamera) {
819                 out.startTag(null, TAG_DISABLE_CAMERA);
820                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera));
821                 out.endTag(null, TAG_DISABLE_CAMERA);
822             }
823             if (disableCallerId) {
824                 out.startTag(null, TAG_DISABLE_CALLER_ID);
825                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId));
826                 out.endTag(null, TAG_DISABLE_CALLER_ID);
827             }
828             if (disableContactsSearch) {
829                 out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH);
830                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch));
831                 out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH);
832             }
833             if (!disableBluetoothContactSharing) {
834                 out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
835                 out.attribute(null, ATTR_VALUE,
836                         Boolean.toString(disableBluetoothContactSharing));
837                 out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING);
838             }
839             if (disableScreenCapture) {
840                 out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE);
841                 out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture));
842                 out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE);
843             }
844             if (requireAutoTime) {
845                 out.startTag(null, TAG_REQUIRE_AUTO_TIME);
846                 out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime));
847                 out.endTag(null, TAG_REQUIRE_AUTO_TIME);
848             }
849             if (forceEphemeralUsers) {
850                 out.startTag(null, TAG_FORCE_EPHEMERAL_USERS);
851                 out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers));
852                 out.endTag(null, TAG_FORCE_EPHEMERAL_USERS);
853             }
854             if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) {
855                 out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
856                 out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures));
857                 out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES);
858             }
859             if (!accountTypesWithManagementDisabled.isEmpty()) {
860                 out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT);
861                 for (String ac : accountTypesWithManagementDisabled) {
862                     out.startTag(null, TAG_ACCOUNT_TYPE);
863                     out.attribute(null, ATTR_VALUE, ac);
864                     out.endTag(null, TAG_ACCOUNT_TYPE);
865                 }
866                 out.endTag(null,  TAG_DISABLE_ACCOUNT_MANAGEMENT);
867             }
868             if (!trustAgentInfos.isEmpty()) {
869                 Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet();
870                 out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
871                 for (Entry<String, TrustAgentInfo> entry : set) {
872                     TrustAgentInfo trustAgentInfo = entry.getValue();
873                     out.startTag(null, TAG_TRUST_AGENT_COMPONENT);
874                     out.attribute(null, ATTR_VALUE, entry.getKey());
875                     if (trustAgentInfo.options != null) {
876                         out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
877                         try {
878                             trustAgentInfo.options.saveToXml(out);
879                         } catch (XmlPullParserException e) {
880                             Log.e(LOG_TAG, "Failed to save TrustAgent options", e);
881                         }
882                         out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS);
883                     }
884                     out.endTag(null, TAG_TRUST_AGENT_COMPONENT);
885                 }
886                 out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES);
887             }
888             if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) {
889                 out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
890                 final int providerCount = crossProfileWidgetProviders.size();
891                 for (int i = 0; i < providerCount; i++) {
892                     String provider = crossProfileWidgetProviders.get(i);
893                     out.startTag(null, TAG_PROVIDER);
894                     out.attribute(null, ATTR_VALUE, provider);
895                     out.endTag(null, TAG_PROVIDER);
896                 }
897                 out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS);
898             }
899             writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES,
900                     permittedAccessiblityServices);
901             writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods);
902             writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages);
903             if (hasUserRestrictions()) {
904                 UserRestrictionsUtils.writeRestrictions(
905                         out, userRestrictions, TAG_USER_RESTRICTIONS);
906             }
907             if (!TextUtils.isEmpty(shortSupportMessage)) {
908                 out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE);
909                 out.text(shortSupportMessage.toString());
910                 out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE);
911             }
912             if (!TextUtils.isEmpty(longSupportMessage)) {
913                 out.startTag(null, TAG_LONG_SUPPORT_MESSAGE);
914                 out.text(longSupportMessage.toString());
915                 out.endTag(null, TAG_LONG_SUPPORT_MESSAGE);
916             }
917             if (parentAdmin != null) {
918                 out.startTag(null, TAG_PARENT_ADMIN);
919                 parentAdmin.writeToXml(out);
920                 out.endTag(null, TAG_PARENT_ADMIN);
921             }
922             if (organizationColor != DEF_ORGANIZATION_COLOR) {
923                 out.startTag(null, TAG_ORGANIZATION_COLOR);
924                 out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor));
925                 out.endTag(null, TAG_ORGANIZATION_COLOR);
926             }
927             if (organizationName != null) {
928                 out.startTag(null, TAG_ORGANIZATION_NAME);
929                 out.text(organizationName);
930                 out.endTag(null, TAG_ORGANIZATION_NAME);
931             }
932         }
933
934         void writePackageListToXml(XmlSerializer out, String outerTag,
935                 List<String> packageList)
936                 throws IllegalArgumentException, IllegalStateException, IOException {
937             if (packageList == null) {
938                 return;
939             }
940
941             out.startTag(null, outerTag);
942             for (String packageName : packageList) {
943                 out.startTag(null, TAG_PACKAGE_LIST_ITEM);
944                 out.attribute(null, ATTR_VALUE, packageName);
945                 out.endTag(null, TAG_PACKAGE_LIST_ITEM);
946             }
947             out.endTag(null, outerTag);
948         }
949
950         void readFromXml(XmlPullParser parser)
951                 throws XmlPullParserException, IOException {
952             int outerDepth = parser.getDepth();
953             int type;
954             while ((type=parser.next()) != END_DOCUMENT
955                    && (type != END_TAG || parser.getDepth() > outerDepth)) {
956                 if (type == END_TAG || type == TEXT) {
957                     continue;
958                 }
959                 String tag = parser.getName();
960                 if (TAG_POLICIES.equals(tag)) {
961                     info.readPoliciesFromXml(parser);
962                 } else if (TAG_PASSWORD_QUALITY.equals(tag)) {
963                     passwordQuality = Integer.parseInt(
964                             parser.getAttributeValue(null, ATTR_VALUE));
965                 } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) {
966                     minimumPasswordLength = Integer.parseInt(
967                             parser.getAttributeValue(null, ATTR_VALUE));
968                 } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) {
969                     passwordHistoryLength = Integer.parseInt(
970                             parser.getAttributeValue(null, ATTR_VALUE));
971                 } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) {
972                     minimumPasswordUpperCase = Integer.parseInt(
973                             parser.getAttributeValue(null, ATTR_VALUE));
974                 } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) {
975                     minimumPasswordLowerCase = Integer.parseInt(
976                             parser.getAttributeValue(null, ATTR_VALUE));
977                 } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) {
978                     minimumPasswordLetters = Integer.parseInt(
979                             parser.getAttributeValue(null, ATTR_VALUE));
980                 } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) {
981                     minimumPasswordNumeric = Integer.parseInt(
982                             parser.getAttributeValue(null, ATTR_VALUE));
983                 } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) {
984                     minimumPasswordSymbols = Integer.parseInt(
985                             parser.getAttributeValue(null, ATTR_VALUE));
986                 } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) {
987                     minimumPasswordNonLetter = Integer.parseInt(
988                             parser.getAttributeValue(null, ATTR_VALUE));
989                 } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) {
990                     maximumTimeToUnlock = Long.parseLong(
991                             parser.getAttributeValue(null, ATTR_VALUE));
992                 } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) {
993                     strongAuthUnlockTimeout = Long.parseLong(
994                             parser.getAttributeValue(null, ATTR_VALUE));
995                 } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) {
996                     maximumFailedPasswordsForWipe = Integer.parseInt(
997                             parser.getAttributeValue(null, ATTR_VALUE));
998                 } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) {
999                     specifiesGlobalProxy = Boolean.parseBoolean(
1000                             parser.getAttributeValue(null, ATTR_VALUE));
1001                 } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) {
1002                     globalProxySpec =
1003                         parser.getAttributeValue(null, ATTR_VALUE);
1004                 } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) {
1005                     globalProxyExclusionList =
1006                         parser.getAttributeValue(null, ATTR_VALUE);
1007                 } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) {
1008                     passwordExpirationTimeout = Long.parseLong(
1009                             parser.getAttributeValue(null, ATTR_VALUE));
1010                 } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) {
1011                     passwordExpirationDate = Long.parseLong(
1012                             parser.getAttributeValue(null, ATTR_VALUE));
1013                 } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) {
1014                     encryptionRequested = Boolean.parseBoolean(
1015                             parser.getAttributeValue(null, ATTR_VALUE));
1016                 } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) {
1017                     testOnlyAdmin = Boolean.parseBoolean(
1018                             parser.getAttributeValue(null, ATTR_VALUE));
1019                 } else if (TAG_DISABLE_CAMERA.equals(tag)) {
1020                     disableCamera = Boolean.parseBoolean(
1021                             parser.getAttributeValue(null, ATTR_VALUE));
1022                 } else if (TAG_DISABLE_CALLER_ID.equals(tag)) {
1023                     disableCallerId = Boolean.parseBoolean(
1024                             parser.getAttributeValue(null, ATTR_VALUE));
1025                 } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) {
1026                     disableContactsSearch = Boolean.parseBoolean(
1027                             parser.getAttributeValue(null, ATTR_VALUE));
1028                 } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) {
1029                     disableBluetoothContactSharing = Boolean.parseBoolean(parser
1030                             .getAttributeValue(null, ATTR_VALUE));
1031                 } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) {
1032                     disableScreenCapture = Boolean.parseBoolean(
1033                             parser.getAttributeValue(null, ATTR_VALUE));
1034                 } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) {
1035                     requireAutoTime = Boolean.parseBoolean(
1036                             parser.getAttributeValue(null, ATTR_VALUE));
1037                 } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) {
1038                     forceEphemeralUsers = Boolean.parseBoolean(
1039                             parser.getAttributeValue(null, ATTR_VALUE));
1040                 } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) {
1041                     disabledKeyguardFeatures = Integer.parseInt(
1042                             parser.getAttributeValue(null, ATTR_VALUE));
1043                 } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) {
1044                     accountTypesWithManagementDisabled = readDisableAccountInfo(parser, tag);
1045                 } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) {
1046                     trustAgentInfos = getAllTrustAgentInfos(parser, tag);
1047                 } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) {
1048                     crossProfileWidgetProviders = getCrossProfileWidgetProviders(parser, tag);
1049                 } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) {
1050                     permittedAccessiblityServices = readPackageList(parser, tag);
1051                 } else if (TAG_PERMITTED_IMES.equals(tag)) {
1052                     permittedInputMethods = readPackageList(parser, tag);
1053                 } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) {
1054                     keepUninstalledPackages = readPackageList(parser, tag);
1055                 } else if (TAG_USER_RESTRICTIONS.equals(tag)) {
1056                     UserRestrictionsUtils.readRestrictions(parser, ensureUserRestrictions());
1057                 } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) {
1058                     type = parser.next();
1059                     if (type == XmlPullParser.TEXT) {
1060                         shortSupportMessage = parser.getText();
1061                     } else {
1062                         Log.w(LOG_TAG, "Missing text when loading short support message");
1063                     }
1064                 } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) {
1065                     type = parser.next();
1066                     if (type == XmlPullParser.TEXT) {
1067                         longSupportMessage = parser.getText();
1068                     } else {
1069                         Log.w(LOG_TAG, "Missing text when loading long support message");
1070                     }
1071                 } else if (TAG_PARENT_ADMIN.equals(tag)) {
1072                     Preconditions.checkState(!isParent);
1073
1074                     parentAdmin = new ActiveAdmin(info, /* parent */ true);
1075                     parentAdmin.readFromXml(parser);
1076                 } else if (TAG_ORGANIZATION_COLOR.equals(tag)) {
1077                     organizationColor = Integer.parseInt(
1078                             parser.getAttributeValue(null, ATTR_VALUE));
1079                 } else if (TAG_ORGANIZATION_NAME.equals(tag)) {
1080                     type = parser.next();
1081                     if (type == XmlPullParser.TEXT) {
1082                         organizationName = parser.getText();
1083                     } else {
1084                         Log.w(LOG_TAG, "Missing text when loading organization name");
1085                     }
1086                 } else {
1087                     Slog.w(LOG_TAG, "Unknown admin tag: " + tag);
1088                     XmlUtils.skipCurrentTag(parser);
1089                 }
1090             }
1091         }
1092
1093         private List<String> readPackageList(XmlPullParser parser,
1094                 String tag) throws XmlPullParserException, IOException {
1095             List<String> result = new ArrayList<String>();
1096             int outerDepth = parser.getDepth();
1097             int outerType;
1098             while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT
1099                     && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
1100                 if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) {
1101                     continue;
1102                 }
1103                 String outerTag = parser.getName();
1104                 if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) {
1105                     String packageName = parser.getAttributeValue(null, ATTR_VALUE);
1106                     if (packageName != null) {
1107                         result.add(packageName);
1108                     } else {
1109                         Slog.w(LOG_TAG, "Package name missing under " + outerTag);
1110                     }
1111                 } else {
1112                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + outerTag);
1113                 }
1114             }
1115             return result;
1116         }
1117
1118         private Set<String> readDisableAccountInfo(XmlPullParser parser, String tag)
1119                 throws XmlPullParserException, IOException {
1120             int outerDepthDAM = parser.getDepth();
1121             int typeDAM;
1122             Set<String> result = new ArraySet<>();
1123             while ((typeDAM=parser.next()) != END_DOCUMENT
1124                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1125                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1126                     continue;
1127                 }
1128                 String tagDAM = parser.getName();
1129                 if (TAG_ACCOUNT_TYPE.equals(tagDAM)) {
1130                     result.add(parser.getAttributeValue(null, ATTR_VALUE));
1131                 } else {
1132                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1133                 }
1134             }
1135             return result;
1136         }
1137
1138         private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos(
1139                 XmlPullParser parser, String tag) throws XmlPullParserException, IOException {
1140             int outerDepthDAM = parser.getDepth();
1141             int typeDAM;
1142             final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>();
1143             while ((typeDAM=parser.next()) != END_DOCUMENT
1144                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1145                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1146                     continue;
1147                 }
1148                 String tagDAM = parser.getName();
1149                 if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) {
1150                     final String component = parser.getAttributeValue(null, ATTR_VALUE);
1151                     final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag);
1152                     result.put(component, trustAgentInfo);
1153                 } else {
1154                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1155                 }
1156             }
1157             return result;
1158         }
1159
1160         private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag)
1161                 throws XmlPullParserException, IOException  {
1162             int outerDepthDAM = parser.getDepth();
1163             int typeDAM;
1164             TrustAgentInfo result = new TrustAgentInfo(null);
1165             while ((typeDAM=parser.next()) != END_DOCUMENT
1166                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1167                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1168                     continue;
1169                 }
1170                 String tagDAM = parser.getName();
1171                 if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) {
1172                     result.options = PersistableBundle.restoreFromXml(parser);
1173                 } else {
1174                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1175                 }
1176             }
1177             return result;
1178         }
1179
1180         private List<String> getCrossProfileWidgetProviders(XmlPullParser parser, String tag)
1181                 throws XmlPullParserException, IOException  {
1182             int outerDepthDAM = parser.getDepth();
1183             int typeDAM;
1184             ArrayList<String> result = null;
1185             while ((typeDAM=parser.next()) != END_DOCUMENT
1186                     && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) {
1187                 if (typeDAM == END_TAG || typeDAM == TEXT) {
1188                     continue;
1189                 }
1190                 String tagDAM = parser.getName();
1191                 if (TAG_PROVIDER.equals(tagDAM)) {
1192                     final String provider = parser.getAttributeValue(null, ATTR_VALUE);
1193                     if (result == null) {
1194                         result = new ArrayList<>();
1195                     }
1196                     result.add(provider);
1197                 } else {
1198                     Slog.w(LOG_TAG, "Unknown tag under " + tag +  ": " + tagDAM);
1199                 }
1200             }
1201             return result;
1202         }
1203
1204         boolean hasUserRestrictions() {
1205             return userRestrictions != null && userRestrictions.size() > 0;
1206         }
1207
1208         Bundle ensureUserRestrictions() {
1209             if (userRestrictions == null) {
1210                 userRestrictions = new Bundle();
1211             }
1212             return userRestrictions;
1213         }
1214
1215         void dump(String prefix, PrintWriter pw) {
1216             pw.print(prefix); pw.print("uid="); pw.println(getUid());
1217             pw.print(prefix); pw.print("testOnlyAdmin=");
1218             pw.println(testOnlyAdmin);
1219             pw.print(prefix); pw.println("policies:");
1220             ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies();
1221             if (pols != null) {
1222                 for (int i=0; i<pols.size(); i++) {
1223                     pw.print(prefix); pw.print("  "); pw.println(pols.get(i).tag);
1224                 }
1225             }
1226             pw.print(prefix); pw.print("passwordQuality=0x");
1227                     pw.println(Integer.toHexString(passwordQuality));
1228             pw.print(prefix); pw.print("minimumPasswordLength=");
1229                     pw.println(minimumPasswordLength);
1230             pw.print(prefix); pw.print("passwordHistoryLength=");
1231                     pw.println(passwordHistoryLength);
1232             pw.print(prefix); pw.print("minimumPasswordUpperCase=");
1233                     pw.println(minimumPasswordUpperCase);
1234             pw.print(prefix); pw.print("minimumPasswordLowerCase=");
1235                     pw.println(minimumPasswordLowerCase);
1236             pw.print(prefix); pw.print("minimumPasswordLetters=");
1237                     pw.println(minimumPasswordLetters);
1238             pw.print(prefix); pw.print("minimumPasswordNumeric=");
1239                     pw.println(minimumPasswordNumeric);
1240             pw.print(prefix); pw.print("minimumPasswordSymbols=");
1241                     pw.println(minimumPasswordSymbols);
1242             pw.print(prefix); pw.print("minimumPasswordNonLetter=");
1243                     pw.println(minimumPasswordNonLetter);
1244             pw.print(prefix); pw.print("maximumTimeToUnlock=");
1245                     pw.println(maximumTimeToUnlock);
1246             pw.print(prefix); pw.print("strongAuthUnlockTimeout=");
1247                     pw.println(strongAuthUnlockTimeout);
1248             pw.print(prefix); pw.print("maximumFailedPasswordsForWipe=");
1249                     pw.println(maximumFailedPasswordsForWipe);
1250             pw.print(prefix); pw.print("specifiesGlobalProxy=");
1251                     pw.println(specifiesGlobalProxy);
1252             pw.print(prefix); pw.print("passwordExpirationTimeout=");
1253                     pw.println(passwordExpirationTimeout);
1254             pw.print(prefix); pw.print("passwordExpirationDate=");
1255                     pw.println(passwordExpirationDate);
1256             if (globalProxySpec != null) {
1257                 pw.print(prefix); pw.print("globalProxySpec=");
1258                         pw.println(globalProxySpec);
1259             }
1260             if (globalProxyExclusionList != null) {
1261                 pw.print(prefix); pw.print("globalProxyEclusionList=");
1262                         pw.println(globalProxyExclusionList);
1263             }
1264             pw.print(prefix); pw.print("encryptionRequested=");
1265                     pw.println(encryptionRequested);
1266             pw.print(prefix); pw.print("disableCamera=");
1267                     pw.println(disableCamera);
1268             pw.print(prefix); pw.print("disableCallerId=");
1269                     pw.println(disableCallerId);
1270             pw.print(prefix); pw.print("disableContactsSearch=");
1271                     pw.println(disableContactsSearch);
1272             pw.print(prefix); pw.print("disableBluetoothContactSharing=");
1273                     pw.println(disableBluetoothContactSharing);
1274             pw.print(prefix); pw.print("disableScreenCapture=");
1275                     pw.println(disableScreenCapture);
1276             pw.print(prefix); pw.print("requireAutoTime=");
1277                     pw.println(requireAutoTime);
1278             pw.print(prefix); pw.print("forceEphemeralUsers=");
1279                     pw.println(forceEphemeralUsers);
1280             pw.print(prefix); pw.print("disabledKeyguardFeatures=");
1281                     pw.println(disabledKeyguardFeatures);
1282             pw.print(prefix); pw.print("crossProfileWidgetProviders=");
1283                     pw.println(crossProfileWidgetProviders);
1284             if (permittedAccessiblityServices != null) {
1285                 pw.print(prefix); pw.print("permittedAccessibilityServices=");
1286                     pw.println(permittedAccessiblityServices);
1287             }
1288             if (permittedInputMethods != null) {
1289                 pw.print(prefix); pw.print("permittedInputMethods=");
1290                     pw.println(permittedInputMethods);
1291             }
1292             if (keepUninstalledPackages != null) {
1293                 pw.print(prefix); pw.print("keepUninstalledPackages=");
1294                     pw.println(keepUninstalledPackages);
1295             }
1296             pw.print(prefix); pw.print("organizationColor=");
1297                     pw.println(organizationColor);
1298             if (organizationName != null) {
1299                 pw.print(prefix); pw.print("organizationName=");
1300                     pw.println(organizationName);
1301             }
1302             pw.print(prefix); pw.println("userRestrictions:");
1303             UserRestrictionsUtils.dumpRestrictions(pw, prefix + "  ", userRestrictions);
1304             pw.print(prefix); pw.print("isParent=");
1305                     pw.println(isParent);
1306             if (parentAdmin != null) {
1307                 pw.print(prefix);  pw.println("parentAdmin:");
1308                 parentAdmin.dump(prefix + "  ", pw);
1309             }
1310         }
1311     }
1312
1313     private void handlePackagesChanged(String packageName, int userHandle) {
1314         boolean removed = false;
1315         if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle);
1316         DevicePolicyData policy = getUserData(userHandle);
1317         synchronized (this) {
1318             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
1319                 ActiveAdmin aa = policy.mAdminList.get(i);
1320                 try {
1321                     // If we're checking all packages or if the specific one we're checking matches,
1322                     // then check if the package and receiver still exist.
1323                     final String adminPackage = aa.info.getPackageName();
1324                     if (packageName == null || packageName.equals(adminPackage)) {
1325                         if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null
1326                                 || mIPackageManager.getReceiverInfo(aa.info.getComponent(),
1327                                         PackageManager.MATCH_DIRECT_BOOT_AWARE
1328                                                 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
1329                                         userHandle) == null) {
1330                             removed = true;
1331                             policy.mAdminList.remove(i);
1332                             policy.mAdminMap.remove(aa.info.getComponent());
1333                         }
1334                     }
1335                 } catch (RemoteException re) {
1336                     // Shouldn't happen
1337                 }
1338             }
1339             if (removed) {
1340                 validatePasswordOwnerLocked(policy);
1341                 saveSettingsLocked(policy.mUserHandle);
1342             }
1343
1344             // Check if delegated cert installer or app restrictions managing packages are removed.
1345             if (isRemovedPackage(packageName, policy.mDelegatedCertInstallerPackage, userHandle)) {
1346                 policy.mDelegatedCertInstallerPackage = null;
1347                 saveSettingsLocked(policy.mUserHandle);
1348             }
1349             if (isRemovedPackage(
1350                     packageName, policy.mApplicationRestrictionsManagingPackage, userHandle)) {
1351                 policy.mApplicationRestrictionsManagingPackage = null;
1352                 saveSettingsLocked(policy.mUserHandle);
1353             }
1354         }
1355         if (removed) {
1356             // The removed admin might have disabled camera, so update user restrictions.
1357             pushUserRestrictions(userHandle);
1358         }
1359     }
1360
1361     private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) {
1362         try {
1363             return targetPackage != null
1364                     && (changedPackage == null || changedPackage.equals(targetPackage))
1365                     && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null;
1366         } catch (RemoteException e) {
1367             // Shouldn't happen
1368         }
1369
1370         return false;
1371     }
1372
1373     /**
1374      * Unit test will subclass it to inject mocks.
1375      */
1376     @VisibleForTesting
1377     static class Injector {
1378
1379         private final Context mContext;
1380
1381         Injector(Context context) {
1382             mContext = context;
1383         }
1384
1385         Owners newOwners() {
1386             return new Owners(getUserManager(), getUserManagerInternal(),
1387                     getPackageManagerInternal());
1388         }
1389
1390         UserManager getUserManager() {
1391             return UserManager.get(mContext);
1392         }
1393
1394         UserManagerInternal getUserManagerInternal() {
1395             return LocalServices.getService(UserManagerInternal.class);
1396         }
1397
1398         PackageManagerInternal getPackageManagerInternal() {
1399             return LocalServices.getService(PackageManagerInternal.class);
1400         }
1401
1402         NotificationManager getNotificationManager() {
1403             return mContext.getSystemService(NotificationManager.class);
1404         }
1405
1406         PowerManagerInternal getPowerManagerInternal() {
1407             return LocalServices.getService(PowerManagerInternal.class);
1408         }
1409
1410         TelephonyManager getTelephonyManager() {
1411             return TelephonyManager.from(mContext);
1412         }
1413
1414         TrustManager getTrustManager() {
1415             return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE);
1416         }
1417
1418         IWindowManager getIWindowManager() {
1419             return IWindowManager.Stub
1420                     .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE));
1421         }
1422
1423         IActivityManager getIActivityManager() {
1424             return ActivityManagerNative.getDefault();
1425         }
1426
1427         IPackageManager getIPackageManager() {
1428             return AppGlobals.getPackageManager();
1429         }
1430
1431         IBackupManager getIBackupManager() {
1432             return IBackupManager.Stub.asInterface(
1433                     ServiceManager.getService(Context.BACKUP_SERVICE));
1434         }
1435
1436         IAudioService getIAudioService() {
1437             return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE));
1438         }
1439
1440         LockPatternUtils newLockPatternUtils() {
1441             return new LockPatternUtils(mContext);
1442         }
1443
1444         boolean storageManagerIsFileBasedEncryptionEnabled() {
1445             return StorageManager.isFileEncryptedNativeOnly();
1446         }
1447
1448         boolean storageManagerIsNonDefaultBlockEncrypted() {
1449             long identity = Binder.clearCallingIdentity();
1450             try {
1451                 return StorageManager.isNonDefaultBlockEncrypted();
1452             } finally {
1453                 Binder.restoreCallingIdentity(identity);
1454             }
1455         }
1456
1457         boolean storageManagerIsEncrypted() {
1458             return StorageManager.isEncrypted();
1459         }
1460
1461         boolean storageManagerIsEncryptable() {
1462             return StorageManager.isEncryptable();
1463         }
1464
1465         Looper getMyLooper() {
1466             return Looper.myLooper();
1467         }
1468
1469         WifiManager getWifiManager() {
1470             return mContext.getSystemService(WifiManager.class);
1471         }
1472
1473         long binderClearCallingIdentity() {
1474             return Binder.clearCallingIdentity();
1475         }
1476
1477         void binderRestoreCallingIdentity(long token) {
1478             Binder.restoreCallingIdentity(token);
1479         }
1480
1481         int binderGetCallingUid() {
1482             return Binder.getCallingUid();
1483         }
1484
1485         int binderGetCallingPid() {
1486             return Binder.getCallingPid();
1487         }
1488
1489         UserHandle binderGetCallingUserHandle() {
1490             return Binder.getCallingUserHandle();
1491         }
1492
1493         boolean binderIsCallingUidMyUid() {
1494             return getCallingUid() == Process.myUid();
1495         }
1496
1497         final int userHandleGetCallingUserId() {
1498             return UserHandle.getUserId(binderGetCallingUid());
1499         }
1500
1501         File environmentGetUserSystemDirectory(int userId) {
1502             return Environment.getUserSystemDirectory(userId);
1503         }
1504
1505         void powerManagerGoToSleep(long time, int reason, int flags) {
1506             mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags);
1507         }
1508
1509         void powerManagerReboot(String reason) {
1510             mContext.getSystemService(PowerManager.class).reboot(reason);
1511         }
1512
1513         boolean systemPropertiesGetBoolean(String key, boolean def) {
1514             return SystemProperties.getBoolean(key, def);
1515         }
1516
1517         long systemPropertiesGetLong(String key, long def) {
1518             return SystemProperties.getLong(key, def);
1519         }
1520
1521         String systemPropertiesGet(String key, String def) {
1522             return SystemProperties.get(key, def);
1523         }
1524
1525         String systemPropertiesGet(String key) {
1526             return SystemProperties.get(key);
1527         }
1528
1529         void systemPropertiesSet(String key, String value) {
1530             SystemProperties.set(key, value);
1531         }
1532
1533         boolean userManagerIsSplitSystemUser() {
1534             return UserManager.isSplitSystemUser();
1535         }
1536
1537         String getDevicePolicyFilePathForSystemUser() {
1538             return "/data/system/";
1539         }
1540
1541         void registerContentObserver(Uri uri, boolean notifyForDescendents,
1542                 ContentObserver observer, int userHandle) {
1543             mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents,
1544                     observer, userHandle);
1545         }
1546
1547         int settingsSecureGetIntForUser(String name, int def, int userHandle) {
1548             return Settings.Secure.getIntForUser(mContext.getContentResolver(),
1549                     name, def, userHandle);
1550         }
1551
1552         void settingsSecurePutIntForUser(String name, int value, int userHandle) {
1553             Settings.Secure.putIntForUser(mContext.getContentResolver(),
1554                     name, value, userHandle);
1555         }
1556
1557         void settingsSecurePutStringForUser(String name, String value, int userHandle) {
1558             Settings.Secure.putStringForUser(mContext.getContentResolver(),
1559                     name, value, userHandle);
1560         }
1561
1562         void settingsGlobalPutStringForUser(String name, String value, int userHandle) {
1563             Settings.Global.putStringForUser(mContext.getContentResolver(),
1564                     name, value, userHandle);
1565         }
1566
1567         void settingsSecurePutInt(String name, int value) {
1568             Settings.Secure.putInt(mContext.getContentResolver(), name, value);
1569         }
1570
1571         int settingsGlobalGetInt(String name, int def) {
1572             return Settings.Global.getInt(mContext.getContentResolver(), name, def);
1573         }
1574
1575         void settingsGlobalPutInt(String name, int value) {
1576             Settings.Global.putInt(mContext.getContentResolver(), name, value);
1577         }
1578
1579         void settingsSecurePutString(String name, String value) {
1580             Settings.Secure.putString(mContext.getContentResolver(), name, value);
1581         }
1582
1583         void settingsGlobalPutString(String name, String value) {
1584             Settings.Global.putString(mContext.getContentResolver(), name, value);
1585         }
1586
1587         void securityLogSetLoggingEnabledProperty(boolean enabled) {
1588             SecurityLog.setLoggingEnabledProperty(enabled);
1589         }
1590
1591         boolean securityLogGetLoggingEnabledProperty() {
1592             return SecurityLog.getLoggingEnabledProperty();
1593         }
1594
1595         boolean securityLogIsLoggingEnabled() {
1596             return SecurityLog.isLoggingEnabled();
1597         }
1598     }
1599
1600     /**
1601      * Instantiates the service.
1602      */
1603     public DevicePolicyManagerService(Context context) {
1604         this(new Injector(context));
1605     }
1606
1607     @VisibleForTesting
1608     DevicePolicyManagerService(Injector injector) {
1609         mInjector = injector;
1610         mContext = Preconditions.checkNotNull(injector.mContext);
1611         mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper()));
1612         mOwners = Preconditions.checkNotNull(injector.newOwners());
1613
1614         mUserManager = Preconditions.checkNotNull(injector.getUserManager());
1615         mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal());
1616         mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager());
1617         mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager());
1618
1619         mLocalService = new LocalService();
1620         mLockPatternUtils = injector.newLockPatternUtils();
1621
1622         mSecurityLogMonitor = new SecurityLogMonitor(this);
1623
1624         mHasFeature = mContext.getPackageManager()
1625                 .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN);
1626         mIsWatch = mContext.getPackageManager()
1627                 .hasSystemFeature(PackageManager.FEATURE_WATCH);
1628         if (!mHasFeature) {
1629             // Skip the rest of the initialization
1630             return;
1631         }
1632         IntentFilter filter = new IntentFilter();
1633         filter.addAction(Intent.ACTION_BOOT_COMPLETED);
1634         filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION);
1635         filter.addAction(Intent.ACTION_USER_ADDED);
1636         filter.addAction(Intent.ACTION_USER_REMOVED);
1637         filter.addAction(Intent.ACTION_USER_STARTED);
1638         filter.addAction(Intent.ACTION_USER_UNLOCKED);
1639         filter.addAction(KeyChain.ACTION_STORAGE_CHANGED);
1640         filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1641         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1642         filter = new IntentFilter();
1643         filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1644         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1645         filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1646         filter.addAction(Intent.ACTION_PACKAGE_ADDED);
1647         filter.addDataScheme("package");
1648         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1649         filter = new IntentFilter();
1650         filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
1651         mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
1652
1653         LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService);
1654     }
1655
1656     /**
1657      * Creates and loads the policy data from xml.
1658      * @param userHandle the user for whom to load the policy data
1659      * @return
1660      */
1661     @NonNull
1662     DevicePolicyData getUserData(int userHandle) {
1663         synchronized (this) {
1664             DevicePolicyData policy = mUserData.get(userHandle);
1665             if (policy == null) {
1666                 policy = new DevicePolicyData(userHandle);
1667                 mUserData.append(userHandle, policy);
1668                 loadSettingsLocked(policy, userHandle);
1669             }
1670             return policy;
1671         }
1672     }
1673
1674     /**
1675      * Creates and loads the policy data from xml for data that is shared between
1676      * various profiles of a user. In contrast to {@link #getUserData(int)}
1677      * it allows access to data of users other than the calling user.
1678      *
1679      * This function should only be used for shared data, e.g. everything regarding
1680      * passwords and should be removed once multiple screen locks are present.
1681      * @param userHandle the user for whom to load the policy data
1682      * @return
1683      */
1684     DevicePolicyData getUserDataUnchecked(int userHandle) {
1685         long ident = mInjector.binderClearCallingIdentity();
1686         try {
1687             return getUserData(userHandle);
1688         } finally {
1689             mInjector.binderRestoreCallingIdentity(ident);
1690         }
1691     }
1692
1693     void removeUserData(int userHandle) {
1694         synchronized (this) {
1695             if (userHandle == UserHandle.USER_SYSTEM) {
1696                 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring.");
1697                 return;
1698             }
1699             mOwners.removeProfileOwner(userHandle);
1700             mOwners.writeProfileOwner(userHandle);
1701
1702             DevicePolicyData policy = mUserData.get(userHandle);
1703             if (policy != null) {
1704                 mUserData.remove(userHandle);
1705             }
1706             File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle),
1707                     DEVICE_POLICIES_XML);
1708             policyFile.delete();
1709             Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath());
1710         }
1711         updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */);
1712     }
1713
1714     void loadOwners() {
1715         synchronized (this) {
1716             mOwners.load();
1717             setDeviceOwnerSystemPropertyLocked();
1718             findOwnerComponentIfNecessaryLocked();
1719             migrateUserRestrictionsIfNecessaryLocked();
1720
1721             // TODO PO may not have a class name either due to b/17652534.  Address that too.
1722
1723             updateDeviceOwnerLocked();
1724         }
1725     }
1726
1727     private void setDeviceOwnerSystemPropertyLocked() {
1728         // Device owner may still be provisioned, do not set the read-only system property yet.
1729         if (mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) == 0) {
1730             return;
1731         }
1732         // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is
1733         // always false at this point.
1734         if (StorageManager.inCryptKeeperBounce()) {
1735             return;
1736         }
1737
1738         if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) {
1739             Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?");
1740         } else {
1741             if (mOwners.hasDeviceOwner()) {
1742                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true");
1743                 Slog.i(LOG_TAG, "Set ro.device_owner property to true");
1744                 disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
1745                 if (mInjector.securityLogGetLoggingEnabledProperty()) {
1746                     mSecurityLogMonitor.start();
1747                 }
1748             } else {
1749                 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false");
1750                 Slog.i(LOG_TAG, "Set ro.device_owner property to false");
1751             }
1752         }
1753     }
1754
1755     private void findOwnerComponentIfNecessaryLocked() {
1756         if (!mOwners.hasDeviceOwner()) {
1757             return;
1758         }
1759         final ComponentName doComponentName = mOwners.getDeviceOwnerComponent();
1760
1761         if (!TextUtils.isEmpty(doComponentName.getClassName())) {
1762             return; // Already a full component name.
1763         }
1764
1765         final ComponentName doComponent = findAdminComponentWithPackageLocked(
1766                 doComponentName.getPackageName(),
1767                 mOwners.getDeviceOwnerUserId());
1768         if (doComponent == null) {
1769             Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin");
1770         } else {
1771             mOwners.setDeviceOwnerWithRestrictionsMigrated(
1772                     doComponent,
1773                     mOwners.getDeviceOwnerName(),
1774                     mOwners.getDeviceOwnerUserId(),
1775                     !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration());
1776             mOwners.writeDeviceOwner();
1777             if (VERBOSE_LOG) {
1778                 Log.v(LOG_TAG, "Device owner component filled in");
1779             }
1780         }
1781     }
1782
1783     /**
1784      * We didn't use to persist user restrictions for each owners but only persisted in user
1785      * manager.
1786      */
1787     private void migrateUserRestrictionsIfNecessaryLocked() {
1788         boolean migrated = false;
1789         // Migrate for the DO.  Basically all restrictions should be considered to be set by DO,
1790         // except for the "system controlled" ones.
1791         if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) {
1792             if (VERBOSE_LOG) {
1793                 Log.v(LOG_TAG, "Migrating DO user restrictions");
1794             }
1795             migrated = true;
1796
1797             // Migrate user 0 restrictions to DO.
1798             final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
1799
1800             migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin,
1801                     /* exceptionList =*/ null, /* isDeviceOwner =*/ true);
1802
1803             // Push DO user restrictions to user manager.
1804             pushUserRestrictions(UserHandle.USER_SYSTEM);
1805
1806             mOwners.setDeviceOwnerUserRestrictionsMigrated();
1807         }
1808
1809         // Migrate for POs.
1810
1811         // The following restrictions can be set on secondary users by the device owner, so we
1812         // assume they're not from the PO.
1813         final Set<String> secondaryUserExceptionList = Sets.newArraySet(
1814                 UserManager.DISALLOW_OUTGOING_CALLS,
1815                 UserManager.DISALLOW_SMS);
1816
1817         for (UserInfo ui : mUserManager.getUsers()) {
1818             final int userId = ui.id;
1819             if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) {
1820                 if (VERBOSE_LOG) {
1821                     Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId);
1822                 }
1823                 migrated = true;
1824
1825                 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId);
1826
1827                 final Set<String> exceptionList =
1828                         (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList;
1829
1830                 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin,
1831                         exceptionList, /* isDeviceOwner =*/ false);
1832
1833                 // Note if a secondary user has no PO but has a DA that disables camera, we
1834                 // don't get here and won't push the camera user restriction to UserManager
1835                 // here.  That's okay because we'll push user restrictions anyway when a user
1836                 // starts.  But we still do it because we want to let user manager persist
1837                 // upon migration.
1838                 pushUserRestrictions(userId);
1839
1840                 mOwners.setProfileOwnerUserRestrictionsMigrated(userId);
1841             }
1842         }
1843         if (VERBOSE_LOG && migrated) {
1844             Log.v(LOG_TAG, "User restrictions migrated.");
1845         }
1846     }
1847
1848     private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin,
1849             Set<String> exceptionList, boolean isDeviceOwner) {
1850         final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions(
1851                 user.getIdentifier());
1852
1853         final Bundle newBaseRestrictions = new Bundle();
1854         final Bundle newOwnerRestrictions = new Bundle();
1855
1856         for (String key : origRestrictions.keySet()) {
1857             if (!origRestrictions.getBoolean(key)) {
1858                 continue;
1859             }
1860             final boolean canOwnerChange = isDeviceOwner
1861                     ? UserRestrictionsUtils.canDeviceOwnerChange(key)
1862                     : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier());
1863
1864             if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) {
1865                 newBaseRestrictions.putBoolean(key, true);
1866             } else {
1867                 newOwnerRestrictions.putBoolean(key, true);
1868             }
1869         }
1870
1871         if (VERBOSE_LOG) {
1872             Log.v(LOG_TAG, "origRestrictions=" + origRestrictions);
1873             Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions);
1874             Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions);
1875         }
1876         mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(),
1877                 newBaseRestrictions);
1878
1879         if (admin != null) {
1880             admin.ensureUserRestrictions().clear();
1881             admin.ensureUserRestrictions().putAll(newOwnerRestrictions);
1882         } else {
1883             Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier());
1884         }
1885         saveSettingsLocked(user.getIdentifier());
1886     }
1887
1888     private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) {
1889         final DevicePolicyData policy = getUserData(userId);
1890         final int n = policy.mAdminList.size();
1891         ComponentName found = null;
1892         int nFound = 0;
1893         for (int i = 0; i < n; i++) {
1894             final ActiveAdmin admin = policy.mAdminList.get(i);
1895             if (packageName.equals(admin.info.getPackageName())) {
1896                 // Found!
1897                 if (nFound == 0) {
1898                     found = admin.info.getComponent();
1899                 }
1900                 nFound++;
1901             }
1902         }
1903         if (nFound > 1) {
1904             Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO.");
1905         }
1906         return found;
1907     }
1908
1909     /**
1910      * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration
1911      * reminders.  Clears alarm if no expirations are configured.
1912      */
1913     private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) {
1914         final long expiration = getPasswordExpirationLocked(null, userHandle, parent);
1915         final long now = System.currentTimeMillis();
1916         final long timeToExpire = expiration - now;
1917         final long alarmTime;
1918         if (expiration == 0) {
1919             // No expirations are currently configured:  Cancel alarm.
1920             alarmTime = 0;
1921         } else if (timeToExpire <= 0) {
1922             // The password has already expired:  Repeat every 24 hours.
1923             alarmTime = now + MS_PER_DAY;
1924         } else {
1925             // Selecting the next alarm time:  Roll forward to the next 24 hour multiple before
1926             // the expiration time.
1927             long alarmInterval = timeToExpire % MS_PER_DAY;
1928             if (alarmInterval == 0) {
1929                 alarmInterval = MS_PER_DAY;
1930             }
1931             alarmTime = now + alarmInterval;
1932         }
1933
1934         long token = mInjector.binderClearCallingIdentity();
1935         try {
1936             int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle;
1937             AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
1938             PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD,
1939                     new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION),
1940                     PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT,
1941                     UserHandle.of(affectedUserHandle));
1942             am.cancel(pi);
1943             if (alarmTime != 0) {
1944                 am.set(AlarmManager.RTC, alarmTime, pi);
1945             }
1946         } finally {
1947             mInjector.binderRestoreCallingIdentity(token);
1948         }
1949     }
1950
1951     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) {
1952         ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who);
1953         if (admin != null
1954                 && who.getPackageName().equals(admin.info.getActivityInfo().packageName)
1955                 && who.getClassName().equals(admin.info.getActivityInfo().name)) {
1956             return admin;
1957         }
1958         return null;
1959     }
1960
1961     ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) {
1962         if (parent) {
1963             enforceManagedProfile(userHandle, "call APIs on the parent profile");
1964         }
1965         ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
1966         if (admin != null && parent) {
1967             admin = admin.getParentActiveAdmin();
1968         }
1969         return admin;
1970     }
1971
1972     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy)
1973             throws SecurityException {
1974         final int callingUid = mInjector.binderGetCallingUid();
1975
1976         ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid);
1977         if (result != null) {
1978             return result;
1979         }
1980
1981         if (who != null) {
1982             final int userId = UserHandle.getUserId(callingUid);
1983             final DevicePolicyData policy = getUserData(userId);
1984             ActiveAdmin admin = policy.mAdminMap.get(who);
1985             if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
1986                 throw new SecurityException("Admin " + admin.info.getComponent()
1987                          + " does not own the device");
1988             }
1989             if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
1990                 throw new SecurityException("Admin " + admin.info.getComponent()
1991                         + " does not own the profile");
1992             }
1993             throw new SecurityException("Admin " + admin.info.getComponent()
1994                     + " did not specify uses-policy for: "
1995                     + admin.info.getTagForPolicy(reqPolicy));
1996         } else {
1997             throw new SecurityException("No active admin owned by uid "
1998                     + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy);
1999         }
2000     }
2001
2002     ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent)
2003             throws SecurityException {
2004         if (parent) {
2005             enforceManagedProfile(mInjector.userHandleGetCallingUserId(),
2006                     "call APIs on the parent profile");
2007         }
2008         ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy);
2009         return parent ? admin.getParentActiveAdmin() : admin;
2010     }
2011     /**
2012      * Find the admin for the component and userId bit of the uid, then check
2013      * the admin's uid matches the uid.
2014      */
2015     private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) {
2016         final int userId = UserHandle.getUserId(uid);
2017         final DevicePolicyData policy = getUserData(userId);
2018         ActiveAdmin admin = policy.mAdminMap.get(who);
2019         if (admin == null) {
2020             throw new SecurityException("No active admin " + who);
2021         }
2022         if (admin.getUid() != uid) {
2023             throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2024         }
2025         return admin;
2026     }
2027
2028     private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy,
2029             int uid) {
2030         // Try to find an admin which can use reqPolicy
2031         final int userId = UserHandle.getUserId(uid);
2032         final DevicePolicyData policy = getUserData(userId);
2033         if (who != null) {
2034             ActiveAdmin admin = policy.mAdminMap.get(who);
2035             if (admin == null) {
2036                 throw new SecurityException("No active admin " + who);
2037             }
2038             if (admin.getUid() != uid) {
2039                 throw new SecurityException("Admin " + who + " is not owned by uid " + uid);
2040             }
2041             if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) {
2042                 return admin;
2043             }
2044         } else {
2045             for (ActiveAdmin admin : policy.mAdminList) {
2046                 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy,
2047                         userId)) {
2048                     return admin;
2049                 }
2050             }
2051         }
2052
2053         return null;
2054     }
2055
2056     @VisibleForTesting
2057     boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy,
2058             int userId) {
2059         final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId);
2060         final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId);
2061
2062         if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) {
2063             return ownsDevice;
2064         } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) {
2065             // DO always has the PO power.
2066             return ownsDevice || ownsProfile;
2067         } else {
2068             return admin.info.usesPolicy(reqPolicy);
2069         }
2070     }
2071
2072     void sendAdminCommandLocked(ActiveAdmin admin, String action) {
2073         sendAdminCommandLocked(admin, action, null);
2074     }
2075
2076     void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) {
2077         sendAdminCommandLocked(admin, action, null, result);
2078     }
2079
2080     /**
2081      * Send an update to one specific admin, get notified when that admin returns a result.
2082      */
2083     void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras,
2084             BroadcastReceiver result) {
2085         Intent intent = new Intent(action);
2086         intent.setComponent(admin.info.getComponent());
2087         if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) {
2088             intent.putExtra("expiration", admin.passwordExpirationDate);
2089         }
2090         if (adminExtras != null) {
2091             intent.putExtras(adminExtras);
2092         }
2093         if (result != null) {
2094             mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(),
2095                     null, result, mHandler, Activity.RESULT_OK, null, null);
2096         } else {
2097             mContext.sendBroadcastAsUser(intent, admin.getUserHandle());
2098         }
2099     }
2100
2101     /**
2102      * Send an update to all admins of a user that enforce a specified policy.
2103      */
2104     void sendAdminCommandLocked(String action, int reqPolicy, int userHandle) {
2105         final DevicePolicyData policy = getUserData(userHandle);
2106         final int count = policy.mAdminList.size();
2107         if (count > 0) {
2108             for (int i = 0; i < count; i++) {
2109                 final ActiveAdmin admin = policy.mAdminList.get(i);
2110                 if (admin.info.usesPolicy(reqPolicy)) {
2111                     sendAdminCommandLocked(admin, action);
2112                 }
2113             }
2114         }
2115     }
2116
2117     /**
2118      * Send an update intent to all admins of a user and its profiles. Only send to admins that
2119      * enforce a specified policy.
2120      */
2121     private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy,
2122             int userHandle) {
2123         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
2124         for (int profileId : profileIds) {
2125             sendAdminCommandLocked(action, reqPolicy, profileId);
2126         }
2127     }
2128
2129     /**
2130      * Sends a broadcast to each profile that share the password unlock with the given user id.
2131      */
2132     private void sendAdminCommandForLockscreenPoliciesLocked(
2133             String action, int reqPolicy, int userHandle) {
2134         if (isSeparateProfileChallengeEnabled(userHandle)) {
2135             sendAdminCommandLocked(action, reqPolicy, userHandle);
2136         } else {
2137             sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle);
2138         }
2139     }
2140
2141     void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) {
2142         final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2143         DevicePolicyData policy = getUserData(userHandle);
2144         if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) {
2145             policy.mRemovingAdmins.add(adminReceiver);
2146             sendAdminCommandLocked(admin,
2147                     DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED,
2148                     new BroadcastReceiver() {
2149                         @Override
2150                         public void onReceive(Context context, Intent intent) {
2151                             removeAdminArtifacts(adminReceiver, userHandle);
2152                             removePackageIfRequired(adminReceiver.getPackageName(), userHandle);
2153                         }
2154                     });
2155         }
2156     }
2157
2158
2159     public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle,
2160             boolean throwForMissiongPermission) {
2161         if (!mHasFeature) {
2162             return null;
2163         }
2164         enforceFullCrossUsersPermission(userHandle);
2165         ActivityInfo ai = null;
2166         try {
2167             ai = mIPackageManager.getReceiverInfo(adminName,
2168                     PackageManager.GET_META_DATA |
2169                     PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS |
2170                     PackageManager.MATCH_DIRECT_BOOT_AWARE |
2171                     PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle);
2172         } catch (RemoteException e) {
2173             // shouldn't happen.
2174         }
2175         if (ai == null) {
2176             throw new IllegalArgumentException("Unknown admin: " + adminName);
2177         }
2178
2179         if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) {
2180             final String message = "DeviceAdminReceiver " + adminName + " must be protected with "
2181                     + permission.BIND_DEVICE_ADMIN;
2182             Slog.w(LOG_TAG, message);
2183             if (throwForMissiongPermission &&
2184                     ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) {
2185                 throw new IllegalArgumentException(message);
2186             }
2187         }
2188
2189         try {
2190             return new DeviceAdminInfo(mContext, ai);
2191         } catch (XmlPullParserException | IOException e) {
2192             Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName,
2193                     e);
2194             return null;
2195         }
2196     }
2197
2198     private JournaledFile makeJournaledFile(int userHandle) {
2199         final String base = userHandle == UserHandle.USER_SYSTEM
2200                 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML
2201                 : new File(mInjector.environmentGetUserSystemDirectory(userHandle),
2202                         DEVICE_POLICIES_XML).getAbsolutePath();
2203         if (VERBOSE_LOG) {
2204             Log.v(LOG_TAG, "Opening " + base);
2205         }
2206         return new JournaledFile(new File(base), new File(base + ".tmp"));
2207     }
2208
2209     private void saveSettingsLocked(int userHandle) {
2210         DevicePolicyData policy = getUserData(userHandle);
2211         JournaledFile journal = makeJournaledFile(userHandle);
2212         FileOutputStream stream = null;
2213         try {
2214             stream = new FileOutputStream(journal.chooseForWrite(), false);
2215             XmlSerializer out = new FastXmlSerializer();
2216             out.setOutput(stream, StandardCharsets.UTF_8.name());
2217             out.startDocument(null, true);
2218
2219             out.startTag(null, "policies");
2220             if (policy.mRestrictionsProvider != null) {
2221                 out.attribute(null, ATTR_PERMISSION_PROVIDER,
2222                         policy.mRestrictionsProvider.flattenToString());
2223             }
2224             if (policy.mUserSetupComplete) {
2225                 out.attribute(null, ATTR_SETUP_COMPLETE,
2226                         Boolean.toString(true));
2227             }
2228             if (policy.mPaired) {
2229                 out.attribute(null, ATTR_DEVICE_PAIRED,
2230                         Boolean.toString(true));
2231             }
2232             if (policy.mDeviceProvisioningConfigApplied) {
2233                 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED,
2234                         Boolean.toString(true));
2235             }
2236             if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) {
2237                 out.attribute(null, ATTR_PROVISIONING_STATE,
2238                         Integer.toString(policy.mUserProvisioningState));
2239             }
2240             if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) {
2241                 out.attribute(null, ATTR_PERMISSION_POLICY,
2242                         Integer.toString(policy.mPermissionPolicy));
2243             }
2244             if (policy.mDelegatedCertInstallerPackage != null) {
2245                 out.attribute(null, ATTR_DELEGATED_CERT_INSTALLER,
2246                         policy.mDelegatedCertInstallerPackage);
2247             }
2248             if (policy.mApplicationRestrictionsManagingPackage != null) {
2249                 out.attribute(null, ATTR_APPLICATION_RESTRICTIONS_MANAGER,
2250                         policy.mApplicationRestrictionsManagingPackage);
2251             }
2252
2253             final int N = policy.mAdminList.size();
2254             for (int i=0; i<N; i++) {
2255                 ActiveAdmin ap = policy.mAdminList.get(i);
2256                 if (ap != null) {
2257                     out.startTag(null, "admin");
2258                     out.attribute(null, "name", ap.info.getComponent().flattenToString());
2259                     ap.writeToXml(out);
2260                     out.endTag(null, "admin");
2261                 }
2262             }
2263
2264             if (policy.mPasswordOwner >= 0) {
2265                 out.startTag(null, "password-owner");
2266                 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner));
2267                 out.endTag(null, "password-owner");
2268             }
2269
2270             if (policy.mFailedPasswordAttempts != 0) {
2271                 out.startTag(null, "failed-password-attempts");
2272                 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts));
2273                 out.endTag(null, "failed-password-attempts");
2274             }
2275
2276             // Don't save metrics for FBE devices
2277             if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()
2278                     && (policy.mActivePasswordQuality != 0 || policy.mActivePasswordLength != 0
2279                     || policy.mActivePasswordUpperCase != 0 || policy.mActivePasswordLowerCase != 0
2280                     || policy.mActivePasswordLetters != 0 || policy.mActivePasswordNumeric != 0
2281                     || policy.mActivePasswordSymbols != 0
2282                     || policy.mActivePasswordNonLetter != 0)) {
2283                 out.startTag(null, "active-password");
2284                 out.attribute(null, "quality", Integer.toString(policy.mActivePasswordQuality));
2285                 out.attribute(null, "length", Integer.toString(policy.mActivePasswordLength));
2286                 out.attribute(null, "uppercase", Integer.toString(policy.mActivePasswordUpperCase));
2287                 out.attribute(null, "lowercase", Integer.toString(policy.mActivePasswordLowerCase));
2288                 out.attribute(null, "letters", Integer.toString(policy.mActivePasswordLetters));
2289                 out.attribute(null, "numeric", Integer
2290                         .toString(policy.mActivePasswordNumeric));
2291                 out.attribute(null, "symbols", Integer.toString(policy.mActivePasswordSymbols));
2292                 out.attribute(null, "nonletter", Integer.toString(policy.mActivePasswordNonLetter));
2293                 out.endTag(null, "active-password");
2294             }
2295
2296             for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) {
2297                 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2298                 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i));
2299                 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES);
2300             }
2301
2302             for (int i=0; i<policy.mLockTaskPackages.size(); i++) {
2303                 String component = policy.mLockTaskPackages.get(i);
2304                 out.startTag(null, TAG_LOCK_TASK_COMPONENTS);
2305                 out.attribute(null, "name", component);
2306                 out.endTag(null, TAG_LOCK_TASK_COMPONENTS);
2307             }
2308
2309             if (policy.mStatusBarDisabled) {
2310                 out.startTag(null, TAG_STATUS_BAR);
2311                 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled));
2312                 out.endTag(null, TAG_STATUS_BAR);
2313             }
2314
2315             if (policy.doNotAskCredentialsOnBoot) {
2316                 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2317                 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML);
2318             }
2319
2320             for (String id : policy.mAffiliationIds) {
2321                 out.startTag(null, TAG_AFFILIATION_ID);
2322                 out.attribute(null, "id", id);
2323                 out.endTag(null, TAG_AFFILIATION_ID);
2324             }
2325
2326             if (policy.mAdminBroadcastPending) {
2327                 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING);
2328                 out.attribute(null, ATTR_VALUE,
2329                         Boolean.toString(policy.mAdminBroadcastPending));
2330                 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING);
2331             }
2332
2333             if (policy.mInitBundle != null) {
2334                 out.startTag(null, TAG_INITIALIZATION_BUNDLE);
2335                 policy.mInitBundle.saveToXml(out);
2336                 out.endTag(null, TAG_INITIALIZATION_BUNDLE);
2337             }
2338
2339             out.endTag(null, "policies");
2340
2341             out.endDocument();
2342             stream.flush();
2343             FileUtils.sync(stream);
2344             stream.close();
2345             journal.commit();
2346             sendChangedNotification(userHandle);
2347         } catch (XmlPullParserException | IOException e) {
2348             Slog.w(LOG_TAG, "failed writing file", e);
2349             try {
2350                 if (stream != null) {
2351                     stream.close();
2352                 }
2353             } catch (IOException ex) {
2354                 // Ignore
2355             }
2356             journal.rollback();
2357         }
2358     }
2359
2360     private void sendChangedNotification(int userHandle) {
2361         Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
2362         intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2363         long ident = mInjector.binderClearCallingIdentity();
2364         try {
2365             mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle));
2366         } finally {
2367             mInjector.binderRestoreCallingIdentity(ident);
2368         }
2369     }
2370
2371     private void loadSettingsLocked(DevicePolicyData policy, int userHandle) {
2372         JournaledFile journal = makeJournaledFile(userHandle);
2373         FileInputStream stream = null;
2374         File file = journal.chooseForRead();
2375         boolean needsRewrite = false;
2376         try {
2377             stream = new FileInputStream(file);
2378             XmlPullParser parser = Xml.newPullParser();
2379             parser.setInput(stream, StandardCharsets.UTF_8.name());
2380
2381             int type;
2382             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2383                     && type != XmlPullParser.START_TAG) {
2384             }
2385             String tag = parser.getName();
2386             if (!"policies".equals(tag)) {
2387                 throw new XmlPullParserException(
2388                         "Settings do not start with policies tag: found " + tag);
2389             }
2390
2391             // Extract the permission provider component name if available
2392             String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER);
2393             if (permissionProvider != null) {
2394                 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider);
2395             }
2396             String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE);
2397             if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) {
2398                 policy.mUserSetupComplete = true;
2399             }
2400             String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED);
2401             if (paired != null && Boolean.toString(true).equals(paired)) {
2402                 policy.mPaired = true;
2403             }
2404             String deviceProvisioningConfigApplied = parser.getAttributeValue(null,
2405                     ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED);
2406             if (deviceProvisioningConfigApplied != null
2407                     && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) {
2408                 policy.mDeviceProvisioningConfigApplied = true;
2409             }
2410             String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE);
2411             if (!TextUtils.isEmpty(provisioningState)) {
2412                 policy.mUserProvisioningState = Integer.parseInt(provisioningState);
2413             }
2414             String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY);
2415             if (!TextUtils.isEmpty(permissionPolicy)) {
2416                 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy);
2417             }
2418             policy.mDelegatedCertInstallerPackage = parser.getAttributeValue(null,
2419                     ATTR_DELEGATED_CERT_INSTALLER);
2420             policy.mApplicationRestrictionsManagingPackage = parser.getAttributeValue(null,
2421                     ATTR_APPLICATION_RESTRICTIONS_MANAGER);
2422
2423             type = parser.next();
2424             int outerDepth = parser.getDepth();
2425             policy.mLockTaskPackages.clear();
2426             policy.mAdminList.clear();
2427             policy.mAdminMap.clear();
2428             policy.mAffiliationIds.clear();
2429             while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2430                    && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2431                 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2432                     continue;
2433                 }
2434                 tag = parser.getName();
2435                 if ("admin".equals(tag)) {
2436                     String name = parser.getAttributeValue(null, "name");
2437                     try {
2438                         DeviceAdminInfo dai = findAdmin(
2439                                 ComponentName.unflattenFromString(name), userHandle,
2440                                 /* throwForMissionPermission= */ false);
2441                         if (VERBOSE_LOG
2442                                 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid)
2443                                 != userHandle)) {
2444                             Slog.w(LOG_TAG, "findAdmin returned an incorrect uid "
2445                                     + dai.getActivityInfo().applicationInfo.uid + " for user "
2446                                     + userHandle);
2447                         }
2448                         if (dai != null) {
2449                             ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false);
2450                             ap.readFromXml(parser);
2451                             policy.mAdminMap.put(ap.info.getComponent(), ap);
2452                         }
2453                     } catch (RuntimeException e) {
2454                         Slog.w(LOG_TAG, "Failed loading admin " + name, e);
2455                     }
2456                 } else if ("failed-password-attempts".equals(tag)) {
2457                     policy.mFailedPasswordAttempts = Integer.parseInt(
2458                             parser.getAttributeValue(null, "value"));
2459                 } else if ("password-owner".equals(tag)) {
2460                     policy.mPasswordOwner = Integer.parseInt(
2461                             parser.getAttributeValue(null, "value"));
2462                 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) {
2463                     policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME));
2464                 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) {
2465                     policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name"));
2466                 } else if (TAG_STATUS_BAR.equals(tag)) {
2467                     policy.mStatusBarDisabled = Boolean.parseBoolean(
2468                             parser.getAttributeValue(null, ATTR_DISABLED));
2469                 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) {
2470                     policy.doNotAskCredentialsOnBoot = true;
2471                 } else if (TAG_AFFILIATION_ID.equals(tag)) {
2472                     policy.mAffiliationIds.add(parser.getAttributeValue(null, "id"));
2473                 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) {
2474                     String pending = parser.getAttributeValue(null, ATTR_VALUE);
2475                     policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending);
2476                 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) {
2477                     policy.mInitBundle = PersistableBundle.restoreFromXml(parser);
2478                 } else if ("active-password".equals(tag)) {
2479                     if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
2480                         // Remove this from FBE devices
2481                         needsRewrite = true;
2482                     } else {
2483                         policy.mActivePasswordQuality = Integer.parseInt(
2484                             parser.getAttributeValue(null, "quality"));
2485                         policy.mActivePasswordLength = Integer.parseInt(
2486                                 parser.getAttributeValue(null, "length"));
2487                         policy.mActivePasswordUpperCase = Integer.parseInt(
2488                                 parser.getAttributeValue(null, "uppercase"));
2489                         policy.mActivePasswordLowerCase = Integer.parseInt(
2490                                 parser.getAttributeValue(null, "lowercase"));
2491                         policy.mActivePasswordLetters = Integer.parseInt(
2492                                 parser.getAttributeValue(null, "letters"));
2493                         policy.mActivePasswordNumeric = Integer.parseInt(
2494                                 parser.getAttributeValue(null, "numeric"));
2495                         policy.mActivePasswordSymbols = Integer.parseInt(
2496                                 parser.getAttributeValue(null, "symbols"));
2497                         policy.mActivePasswordNonLetter = Integer.parseInt(
2498                                 parser.getAttributeValue(null, "nonletter"));
2499                     }
2500                 } else {
2501                     Slog.w(LOG_TAG, "Unknown tag: " + tag);
2502                     XmlUtils.skipCurrentTag(parser);
2503                 }
2504             }
2505         } catch (FileNotFoundException e) {
2506             // Don't be noisy, this is normal if we haven't defined any policies.
2507         } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException
2508                 | IndexOutOfBoundsException e) {
2509             Slog.w(LOG_TAG, "failed parsing " + file, e);
2510         }
2511         try {
2512             if (stream != null) {
2513                 stream.close();
2514             }
2515         } catch (IOException e) {
2516             // Ignore
2517         }
2518
2519         // Generate a list of admins from the admin map
2520         policy.mAdminList.addAll(policy.mAdminMap.values());
2521
2522         // Might need to upgrade the file by rewriting it
2523         if (needsRewrite) {
2524             saveSettingsLocked(userHandle);
2525         }
2526
2527         validatePasswordOwnerLocked(policy);
2528         updateMaximumTimeToLockLocked(userHandle);
2529         updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle);
2530         if (policy.mStatusBarDisabled) {
2531             setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle);
2532         }
2533     }
2534
2535     private void updateLockTaskPackagesLocked(List<String> packages, int userId) {
2536         long ident = mInjector.binderClearCallingIdentity();
2537         try {
2538             mInjector.getIActivityManager()
2539                     .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()]));
2540         } catch (RemoteException e) {
2541             // Not gonna happen.
2542         } finally {
2543             mInjector.binderRestoreCallingIdentity(ident);
2544         }
2545     }
2546
2547     private void updateDeviceOwnerLocked() {
2548         long ident = mInjector.binderClearCallingIdentity();
2549         try {
2550             // TODO This is to prevent DO from getting "clear data"ed, but it should also check the
2551             // user id and also protect all other DAs too.
2552             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
2553             if (deviceOwnerComponent != null) {
2554                 mInjector.getIActivityManager()
2555                         .updateDeviceOwner(deviceOwnerComponent.getPackageName());
2556             }
2557         } catch (RemoteException e) {
2558             // Not gonna happen.
2559         } finally {
2560             mInjector.binderRestoreCallingIdentity(ident);
2561         }
2562     }
2563
2564     static void validateQualityConstant(int quality) {
2565         switch (quality) {
2566             case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED:
2567             case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK:
2568             case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING:
2569             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC:
2570             case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX:
2571             case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC:
2572             case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC:
2573             case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX:
2574             case DevicePolicyManager.PASSWORD_QUALITY_MANAGED:
2575                 return;
2576         }
2577         throw new IllegalArgumentException("Invalid quality constant: 0x"
2578                 + Integer.toHexString(quality));
2579     }
2580
2581     void validatePasswordOwnerLocked(DevicePolicyData policy) {
2582         if (policy.mPasswordOwner >= 0) {
2583             boolean haveOwner = false;
2584             for (int i = policy.mAdminList.size() - 1; i >= 0; i--) {
2585                 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) {
2586                     haveOwner = true;
2587                     break;
2588                 }
2589             }
2590             if (!haveOwner) {
2591                 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner
2592                         + " no longer active; disabling");
2593                 policy.mPasswordOwner = -1;
2594             }
2595         }
2596     }
2597
2598     @VisibleForTesting
2599     void systemReady(int phase) {
2600         if (!mHasFeature) {
2601             return;
2602         }
2603         switch (phase) {
2604             case SystemService.PHASE_LOCK_SETTINGS_READY:
2605                 onLockSettingsReady();
2606                 break;
2607             case SystemService.PHASE_BOOT_COMPLETED:
2608                 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this.
2609                 break;
2610         }
2611     }
2612
2613     private void onLockSettingsReady() {
2614         getUserData(UserHandle.USER_SYSTEM);
2615         loadOwners();
2616         cleanUpOldUsers();
2617
2618         onStartUser(UserHandle.USER_SYSTEM);
2619
2620         // Register an observer for watching for user setup complete.
2621         new SetupContentObserver(mHandler).register();
2622         // Initialize the user setup state, to handle the upgrade case.
2623         updateUserSetupCompleteAndPaired();
2624
2625         List<String> packageList;
2626         synchronized (this) {
2627             packageList = getKeepUninstalledPackagesLocked();
2628         }
2629         if (packageList != null) {
2630             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
2631         }
2632
2633         synchronized (this) {
2634             // push the force-ephemeral-users policy to the user manager.
2635             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
2636             if (deviceOwner != null) {
2637                 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers);
2638             }
2639         }
2640     }
2641
2642     private void ensureDeviceOwnerUserStarted() {
2643         final int userId;
2644         synchronized (this) {
2645             if (!mOwners.hasDeviceOwner()) {
2646                 return;
2647             }
2648             userId = mOwners.getDeviceOwnerUserId();
2649         }
2650         if (VERBOSE_LOG) {
2651             Log.v(LOG_TAG, "Starting non-system DO user: " + userId);
2652         }
2653         if (userId != UserHandle.USER_SYSTEM) {
2654             try {
2655                 mInjector.getIActivityManager().startUserInBackground(userId);
2656
2657                 // STOPSHIP Prevent the DO user from being killed.
2658
2659             } catch (RemoteException e) {
2660                 Slog.w(LOG_TAG, "Exception starting user", e);
2661             }
2662         }
2663     }
2664
2665     private void onStartUser(int userId) {
2666         updateScreenCaptureDisabledInWindowManager(userId,
2667                 getScreenCaptureDisabled(null, userId));
2668         pushUserRestrictions(userId);
2669     }
2670
2671     private void cleanUpOldUsers() {
2672         // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled
2673         // before reboot
2674         Set<Integer> usersWithProfileOwners;
2675         Set<Integer> usersWithData;
2676         synchronized(this) {
2677             usersWithProfileOwners = mOwners.getProfileOwnerKeys();
2678             usersWithData = new ArraySet<>();
2679             for (int i = 0; i < mUserData.size(); i++) {
2680                 usersWithData.add(mUserData.keyAt(i));
2681             }
2682         }
2683         List<UserInfo> allUsers = mUserManager.getUsers();
2684
2685         Set<Integer> deletedUsers = new ArraySet<>();
2686         deletedUsers.addAll(usersWithProfileOwners);
2687         deletedUsers.addAll(usersWithData);
2688         for (UserInfo userInfo : allUsers) {
2689             deletedUsers.remove(userInfo.id);
2690         }
2691         for (Integer userId : deletedUsers) {
2692             removeUserData(userId);
2693         }
2694     }
2695
2696     private void handlePasswordExpirationNotification(int userHandle) {
2697         synchronized (this) {
2698             final long now = System.currentTimeMillis();
2699
2700             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
2701                     userHandle, /* parent */ false);
2702             final int N = admins.size();
2703             for (int i = 0; i < N; i++) {
2704                 ActiveAdmin admin = admins.get(i);
2705                 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)
2706                         && admin.passwordExpirationTimeout > 0L
2707                         && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS
2708                         && admin.passwordExpirationDate > 0L) {
2709                     sendAdminCommandLocked(admin,
2710                             DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING);
2711                 }
2712             }
2713             setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false);
2714         }
2715     }
2716
2717     private class MonitoringCertNotificationTask extends AsyncTask<Integer, Void, Void> {
2718         @Override
2719         protected Void doInBackground(Integer... params) {
2720             int userHandle = params[0];
2721
2722             if (userHandle == UserHandle.USER_ALL) {
2723                 for (UserInfo userInfo : mUserManager.getUsers(true)) {
2724                     manageNotification(userInfo.getUserHandle());
2725                 }
2726             } else {
2727                 manageNotification(UserHandle.of(userHandle));
2728             }
2729             return null;
2730         }
2731
2732         private void manageNotification(UserHandle userHandle) {
2733             if (!mUserManager.isUserUnlocked(userHandle)) {
2734                 return;
2735             }
2736
2737             // Call out to KeyChain to check for CAs which are waiting for approval.
2738             final List<String> pendingCertificates;
2739             try {
2740                 pendingCertificates = getInstalledCaCertificates(userHandle);
2741             } catch (RemoteException | RuntimeException e) {
2742                 Log.e(LOG_TAG, "Could not retrieve certificates from KeyChain service", e);
2743                 return;
2744             }
2745
2746             synchronized (DevicePolicyManagerService.this) {
2747                 final DevicePolicyData policy = getUserData(userHandle.getIdentifier());
2748
2749                 // Remove deleted certificates. Flush xml if necessary.
2750                 if (policy.mAcceptedCaCertificates.retainAll(pendingCertificates)) {
2751                     saveSettingsLocked(userHandle.getIdentifier());
2752                 }
2753                 // Trim to approved certificates.
2754                 pendingCertificates.removeAll(policy.mAcceptedCaCertificates);
2755             }
2756
2757             if (pendingCertificates.isEmpty()) {
2758                 mInjector.getNotificationManager().cancelAsUser(
2759                         null, MONITORING_CERT_NOTIFICATION_ID, userHandle);
2760                 return;
2761             }
2762
2763             // Build and show a warning notification
2764             int smallIconId;
2765             String contentText;
2766             int parentUserId = userHandle.getIdentifier();
2767             if (getProfileOwner(userHandle.getIdentifier()) != null) {
2768                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2769                         getProfileOwnerName(userHandle.getIdentifier()));
2770                 smallIconId = R.drawable.stat_sys_certificate_info;
2771                 parentUserId = getProfileParentId(userHandle.getIdentifier());
2772             } else if (getDeviceOwnerUserId() == userHandle.getIdentifier()) {
2773                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed,
2774                         getDeviceOwnerName());
2775                 smallIconId = R.drawable.stat_sys_certificate_info;
2776             } else {
2777                 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown);
2778                 smallIconId = android.R.drawable.stat_sys_warning;
2779             }
2780
2781             final int numberOfCertificates = pendingCertificates.size();
2782             Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO);
2783             dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
2784             dialogIntent.setPackage("com.android.settings");
2785             dialogIntent.putExtra(Settings.EXTRA_NUMBER_OF_CERTIFICATES, numberOfCertificates);
2786             dialogIntent.putExtra(Intent.EXTRA_USER_ID, userHandle.getIdentifier());
2787             PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0,
2788                     dialogIntent, PendingIntent.FLAG_UPDATE_CURRENT, null,
2789                     new UserHandle(parentUserId));
2790
2791             final Context userContext;
2792             try {
2793                 final String packageName = mContext.getPackageName();
2794                 userContext = mContext.createPackageContextAsUser(packageName, 0, userHandle);
2795             } catch (PackageManager.NameNotFoundException e) {
2796                 Log.e(LOG_TAG, "Create context as " + userHandle + " failed", e);
2797                 return;
2798             }
2799             final Notification noti = new Notification.Builder(userContext)
2800                 .setSmallIcon(smallIconId)
2801                 .setContentTitle(mContext.getResources().getQuantityText(
2802                         R.plurals.ssl_ca_cert_warning, numberOfCertificates))
2803                 .setContentText(contentText)
2804                 .setContentIntent(notifyIntent)
2805                 .setPriority(Notification.PRIORITY_HIGH)
2806                 .setShowWhen(false)
2807                 .setColor(mContext.getColor(
2808                         com.android.internal.R.color.system_notification_accent_color))
2809                 .build();
2810
2811             mInjector.getNotificationManager().notifyAsUser(
2812                     null, MONITORING_CERT_NOTIFICATION_ID, noti, userHandle);
2813         }
2814
2815         private List<String> getInstalledCaCertificates(UserHandle userHandle)
2816                 throws RemoteException, RuntimeException {
2817             KeyChainConnection conn = null;
2818             try {
2819                 conn = KeyChain.bindAsUser(mContext, userHandle);
2820                 List<ParcelableString> aliases = conn.getService().getUserCaAliases().getList();
2821                 List<String> result = new ArrayList<>(aliases.size());
2822                 for (int i = 0; i < aliases.size(); i++) {
2823                     result.add(aliases.get(i).string);
2824                 }
2825                 return result;
2826             } catch (InterruptedException e) {
2827                 Thread.currentThread().interrupt();
2828                 return null;
2829             } catch (AssertionError e) {
2830                 throw new RuntimeException(e);
2831             } finally {
2832                 if (conn != null) {
2833                     conn.close();
2834                 }
2835             }
2836         }
2837     }
2838
2839     /**
2840      * @param adminReceiver The admin to add
2841      * @param refreshing true = update an active admin, no error
2842      */
2843     @Override
2844     public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) {
2845         if (!mHasFeature) {
2846             return;
2847         }
2848         setActiveAdmin(adminReceiver, refreshing, userHandle, null);
2849     }
2850
2851     private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle,
2852             Bundle onEnableData) {
2853         mContext.enforceCallingOrSelfPermission(
2854                 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
2855         enforceFullCrossUsersPermission(userHandle);
2856
2857         DevicePolicyData policy = getUserData(userHandle);
2858         DeviceAdminInfo info = findAdmin(adminReceiver, userHandle,
2859                 /* throwForMissionPermission= */ true);
2860         if (info == null) {
2861             throw new IllegalArgumentException("Bad admin: " + adminReceiver);
2862         }
2863         if (!info.getActivityInfo().applicationInfo.isInternal()) {
2864             throw new IllegalArgumentException("Only apps in internal storage can be active admin: "
2865                     + adminReceiver);
2866         }
2867         synchronized (this) {
2868             long ident = mInjector.binderClearCallingIdentity();
2869             try {
2870                 final ActiveAdmin existingAdmin
2871                         = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2872                 if (!refreshing && existingAdmin != null) {
2873                     throw new IllegalArgumentException("Admin is already added");
2874                 }
2875                 if (policy.mRemovingAdmins.contains(adminReceiver)) {
2876                     throw new IllegalArgumentException(
2877                             "Trying to set an admin which is being removed");
2878                 }
2879                 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false);
2880                 newAdmin.testOnlyAdmin =
2881                         (existingAdmin != null) ? existingAdmin.testOnlyAdmin
2882                                 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle);
2883                 policy.mAdminMap.put(adminReceiver, newAdmin);
2884                 int replaceIndex = -1;
2885                 final int N = policy.mAdminList.size();
2886                 for (int i=0; i < N; i++) {
2887                     ActiveAdmin oldAdmin = policy.mAdminList.get(i);
2888                     if (oldAdmin.info.getComponent().equals(adminReceiver)) {
2889                         replaceIndex = i;
2890                         break;
2891                     }
2892                 }
2893                 if (replaceIndex == -1) {
2894                     policy.mAdminList.add(newAdmin);
2895                     enableIfNecessary(info.getPackageName(), userHandle);
2896                 } else {
2897                     policy.mAdminList.set(replaceIndex, newAdmin);
2898                 }
2899                 saveSettingsLocked(userHandle);
2900                 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
2901                         onEnableData, null);
2902             } finally {
2903                 mInjector.binderRestoreCallingIdentity(ident);
2904             }
2905         }
2906     }
2907
2908     @Override
2909     public boolean isAdminActive(ComponentName adminReceiver, int userHandle) {
2910         if (!mHasFeature) {
2911             return false;
2912         }
2913         enforceFullCrossUsersPermission(userHandle);
2914         synchronized (this) {
2915             return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null;
2916         }
2917     }
2918
2919     @Override
2920     public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) {
2921         if (!mHasFeature) {
2922             return false;
2923         }
2924         enforceFullCrossUsersPermission(userHandle);
2925         synchronized (this) {
2926             DevicePolicyData policyData = getUserData(userHandle);
2927             return policyData.mRemovingAdmins.contains(adminReceiver);
2928         }
2929     }
2930
2931     @Override
2932     public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) {
2933         if (!mHasFeature) {
2934             return false;
2935         }
2936         enforceFullCrossUsersPermission(userHandle);
2937         synchronized (this) {
2938             ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
2939             if (administrator == null) {
2940                 throw new SecurityException("No active admin " + adminReceiver);
2941             }
2942             return administrator.info.usesPolicy(policyId);
2943         }
2944     }
2945
2946     @Override
2947     @SuppressWarnings("unchecked")
2948     public List<ComponentName> getActiveAdmins(int userHandle) {
2949         if (!mHasFeature) {
2950             return Collections.EMPTY_LIST;
2951         }
2952
2953         enforceFullCrossUsersPermission(userHandle);
2954         synchronized (this) {
2955             DevicePolicyData policy = getUserData(userHandle);
2956             final int N = policy.mAdminList.size();
2957             if (N <= 0) {
2958                 return null;
2959             }
2960             ArrayList<ComponentName> res = new ArrayList<ComponentName>(N);
2961             for (int i=0; i<N; i++) {
2962                 res.add(policy.mAdminList.get(i).info.getComponent());
2963             }
2964             return res;
2965         }
2966     }
2967
2968     @Override
2969     public boolean packageHasActiveAdmins(String packageName, int userHandle) {
2970         if (!mHasFeature) {
2971             return false;
2972         }
2973         enforceFullCrossUsersPermission(userHandle);
2974         synchronized (this) {
2975             DevicePolicyData policy = getUserData(userHandle);
2976             final int N = policy.mAdminList.size();
2977             for (int i=0; i<N; i++) {
2978                 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) {
2979                     return true;
2980                 }
2981             }
2982             return false;
2983         }
2984     }
2985
2986     public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) {
2987         if (!mHasFeature) {
2988             return;
2989         }
2990         Preconditions.checkNotNull(adminReceiver, "ComponentName is null");
2991         enforceShell("forceRemoveActiveAdmin");
2992         long ident = mInjector.binderClearCallingIdentity();
2993         try {
2994             synchronized (this)  {
2995                 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) {
2996                     throw new SecurityException("Attempt to remove non-test admin "
2997                             + adminReceiver + " " + userHandle);
2998                 }
2999
3000                 // If admin is a device or profile owner tidy that up first.
3001                 if (isDeviceOwner(adminReceiver, userHandle)) {
3002                     clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle);
3003                 }
3004                 if (isProfileOwner(adminReceiver, userHandle)) {
3005                     final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver,
3006                             userHandle, /* parent */ false);
3007                     clearProfileOwnerLocked(admin, userHandle);
3008                 }
3009             }
3010             // Remove the admin skipping sending the broadcast.
3011             removeAdminArtifacts(adminReceiver, userHandle);
3012             Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle);
3013         } finally {
3014             mInjector.binderRestoreCallingIdentity(ident);
3015         }
3016     }
3017
3018     /**
3019      * Return if a given package has testOnly="true", in which case we'll relax certain rules
3020      * for CTS.
3021      *
3022      * DO NOT use this method except in {@link #setActiveAdmin}.  Use {@link #isAdminTestOnlyLocked}
3023      * to check wehter an active admin is test-only or not.
3024      *
3025      * The system allows this flag to be changed when an app is updated, which is not good
3026      * for us.  So we persist the flag in {@link ActiveAdmin} when an admin is first installed,
3027      * and used the persisted version in actual checks. (See b/31382361 and b/28928996)
3028      */
3029     private boolean isPackageTestOnly(String packageName, int userHandle) {
3030         final ApplicationInfo ai;
3031         try {
3032             ai = mIPackageManager.getApplicationInfo(packageName,
3033                     (PackageManager.MATCH_DIRECT_BOOT_AWARE
3034                             | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle);
3035         } catch (RemoteException e) {
3036             throw new IllegalStateException(e);
3037         }
3038         if (ai == null) {
3039             throw new IllegalStateException("Couldn't find package: "
3040                     + packageName + " on user " + userHandle);
3041         }
3042         return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0;
3043     }
3044
3045     /**
3046      * See {@link #isPackageTestOnly}.
3047      */
3048     private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) {
3049         final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
3050         return (admin != null) && admin.testOnlyAdmin;
3051     }
3052
3053     private void enforceShell(String method) {
3054         final int callingUid = Binder.getCallingUid();
3055         if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) {
3056             throw new SecurityException("Non-shell user attempted to call " + method);
3057         }
3058     }
3059
3060     @Override
3061     public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) {
3062         if (!mHasFeature) {
3063             return;
3064         }
3065         enforceFullCrossUsersPermission(userHandle);
3066         enforceUserUnlocked(userHandle);
3067         synchronized (this) {
3068             ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
3069             if (admin == null) {
3070                 return;
3071             }
3072             // Active device/profile owners must remain active admins.
3073             if (isDeviceOwner(adminReceiver, userHandle)
3074                     || isProfileOwner(adminReceiver, userHandle)) {
3075                 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" +
3076                         adminReceiver);
3077                 return;
3078             }
3079             if (admin.getUid() != mInjector.binderGetCallingUid()) {
3080                 mContext.enforceCallingOrSelfPermission(
3081                         android.Manifest.permission.MANAGE_DEVICE_ADMINS, null);
3082             }
3083             long ident = mInjector.binderClearCallingIdentity();
3084             try {
3085                 removeActiveAdminLocked(adminReceiver, userHandle);
3086             } finally {
3087                 mInjector.binderRestoreCallingIdentity(ident);
3088             }
3089         }
3090     }
3091
3092     @Override
3093     public boolean isSeparateProfileChallengeAllowed(int userHandle) {
3094         ComponentName profileOwner = getProfileOwner(userHandle);
3095         // Profile challenge is supported on N or newer release.
3096         return profileOwner != null &&
3097                 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M;
3098     }
3099
3100     @Override
3101     public void setPasswordQuality(ComponentName who, int quality, boolean parent) {
3102         if (!mHasFeature) {
3103             return;
3104         }
3105         Preconditions.checkNotNull(who, "ComponentName is null");
3106         validateQualityConstant(quality);
3107
3108         synchronized (this) {
3109             ActiveAdmin ap = getActiveAdminForCallerLocked(
3110                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3111             if (ap.passwordQuality != quality) {
3112                 ap.passwordQuality = quality;
3113                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3114             }
3115         }
3116     }
3117
3118     @Override
3119     public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) {
3120         if (!mHasFeature) {
3121             return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3122         }
3123         enforceFullCrossUsersPermission(userHandle);
3124         synchronized (this) {
3125             int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3126
3127             if (who != null) {
3128                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3129                 return admin != null ? admin.passwordQuality : mode;
3130             }
3131
3132             // Return the strictest policy across all participating admins.
3133             List<ActiveAdmin> admins =
3134                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3135             final int N = admins.size();
3136             for (int i = 0; i < N; i++) {
3137                 ActiveAdmin admin = admins.get(i);
3138                 if (mode < admin.passwordQuality) {
3139                     mode = admin.passwordQuality;
3140                 }
3141             }
3142             return mode;
3143         }
3144     }
3145
3146     private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked(
3147             int userHandle, boolean parent) {
3148         if (!parent && isSeparateProfileChallengeEnabled(userHandle)) {
3149             // If this user has a separate challenge, only return its restrictions.
3150             return getUserDataUnchecked(userHandle).mAdminList;
3151         } else {
3152             // Return all admins for this user and the profiles that are visible from this
3153             // user that do not use a separate work challenge.
3154             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
3155             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3156                 DevicePolicyData policy = getUserData(userInfo.id);
3157                 if (!userInfo.isManagedProfile()) {
3158                     admins.addAll(policy.mAdminList);
3159                 } else {
3160                     // For managed profiles, we always include the policies set on the parent
3161                     // profile. Additionally, we include the ones set on the managed profile
3162                     // if no separate challenge is in place.
3163                     boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id);
3164                     final int N = policy.mAdminList.size();
3165                     for (int i = 0; i < N; i++) {
3166                         ActiveAdmin admin = policy.mAdminList.get(i);
3167                         if (admin.hasParentActiveAdmin()) {
3168                             admins.add(admin.getParentActiveAdmin());
3169                         }
3170                         if (!hasSeparateChallenge) {
3171                             admins.add(admin);
3172                         }
3173                     }
3174                 }
3175             }
3176             return admins;
3177         }
3178     }
3179
3180     private boolean isSeparateProfileChallengeEnabled(int userHandle) {
3181         long ident = mInjector.binderClearCallingIdentity();
3182         try {
3183             return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle);
3184         } finally {
3185             mInjector.binderRestoreCallingIdentity(ident);
3186         }
3187     }
3188
3189     @Override
3190     public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) {
3191         if (!mHasFeature) {
3192             return;
3193         }
3194         Preconditions.checkNotNull(who, "ComponentName is null");
3195         synchronized (this) {
3196             ActiveAdmin ap = getActiveAdminForCallerLocked(
3197                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3198             if (ap.minimumPasswordLength != length) {
3199                 ap.minimumPasswordLength = length;
3200                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3201             }
3202         }
3203     }
3204
3205     @Override
3206     public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) {
3207         if (!mHasFeature) {
3208             return 0;
3209         }
3210         enforceFullCrossUsersPermission(userHandle);
3211         synchronized (this) {
3212             int length = 0;
3213
3214             if (who != null) {
3215                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3216                 return admin != null ? admin.minimumPasswordLength : length;
3217             }
3218
3219             // Return the strictest policy across all participating admins.
3220             List<ActiveAdmin> admins =
3221                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3222             final int N = admins.size();
3223             for (int i = 0; i < N; i++) {
3224                 ActiveAdmin admin = admins.get(i);
3225                 if (length < admin.minimumPasswordLength) {
3226                     length = admin.minimumPasswordLength;
3227                 }
3228             }
3229             return length;
3230         }
3231     }
3232
3233     @Override
3234     public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) {
3235         if (!mHasFeature) {
3236             return;
3237         }
3238         Preconditions.checkNotNull(who, "ComponentName is null");
3239         synchronized (this) {
3240             ActiveAdmin ap = getActiveAdminForCallerLocked(
3241                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3242             if (ap.passwordHistoryLength != length) {
3243                 ap.passwordHistoryLength = length;
3244                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3245             }
3246         }
3247     }
3248
3249     @Override
3250     public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) {
3251         if (!mHasFeature) {
3252             return 0;
3253         }
3254         enforceFullCrossUsersPermission(userHandle);
3255         synchronized (this) {
3256             int length = 0;
3257
3258             if (who != null) {
3259                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3260                 return admin != null ? admin.passwordHistoryLength : length;
3261             }
3262
3263             // Return the strictest policy across all participating admins.
3264             List<ActiveAdmin> admins =
3265                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3266             final int N = admins.size();
3267             for (int i = 0; i < N; i++) {
3268                 ActiveAdmin admin = admins.get(i);
3269                 if (length < admin.passwordHistoryLength) {
3270                     length = admin.passwordHistoryLength;
3271                 }
3272             }
3273
3274             return length;
3275         }
3276     }
3277
3278     @Override
3279     public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) {
3280         if (!mHasFeature) {
3281             return;
3282         }
3283         Preconditions.checkNotNull(who, "ComponentName is null");
3284         Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms");
3285         final int userHandle = mInjector.userHandleGetCallingUserId();
3286         synchronized (this) {
3287             ActiveAdmin ap = getActiveAdminForCallerLocked(
3288                     who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent);
3289             // Calling this API automatically bumps the expiration date
3290             final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
3291             ap.passwordExpirationDate = expiration;
3292             ap.passwordExpirationTimeout = timeout;
3293             if (timeout > 0L) {
3294                 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on "
3295                         + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT)
3296                         .format(new Date(expiration)));
3297             }
3298             saveSettingsLocked(userHandle);
3299
3300             // in case this is the first one, set the alarm on the appropriate user.
3301             setExpirationAlarmCheckLocked(mContext, userHandle, parent);
3302         }
3303     }
3304
3305     /**
3306      * Return a single admin's expiration cycle time, or the min of all cycle times.
3307      * Returns 0 if not configured.
3308      */
3309     @Override
3310     public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) {
3311         if (!mHasFeature) {
3312             return 0L;
3313         }
3314         enforceFullCrossUsersPermission(userHandle);
3315         synchronized (this) {
3316             long timeout = 0L;
3317
3318             if (who != null) {
3319                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3320                 return admin != null ? admin.passwordExpirationTimeout : timeout;
3321             }
3322
3323             // Return the strictest policy across all participating admins.
3324             List<ActiveAdmin> admins =
3325                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3326             final int N = admins.size();
3327             for (int i = 0; i < N; i++) {
3328                 ActiveAdmin admin = admins.get(i);
3329                 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L
3330                         && timeout > admin.passwordExpirationTimeout)) {
3331                     timeout = admin.passwordExpirationTimeout;
3332                 }
3333             }
3334             return timeout;
3335         }
3336     }
3337
3338     @Override
3339     public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3340         final int userId = UserHandle.getCallingUserId();
3341         List<String> changedProviders = null;
3342
3343         synchronized (this) {
3344             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3345                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3346             if (activeAdmin.crossProfileWidgetProviders == null) {
3347                 activeAdmin.crossProfileWidgetProviders = new ArrayList<>();
3348             }
3349             List<String> providers = activeAdmin.crossProfileWidgetProviders;
3350             if (!providers.contains(packageName)) {
3351                 providers.add(packageName);
3352                 changedProviders = new ArrayList<>(providers);
3353                 saveSettingsLocked(userId);
3354             }
3355         }
3356
3357         if (changedProviders != null) {
3358             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3359             return true;
3360         }
3361
3362         return false;
3363     }
3364
3365     @Override
3366     public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) {
3367         final int userId = UserHandle.getCallingUserId();
3368         List<String> changedProviders = null;
3369
3370         synchronized (this) {
3371             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3372                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3373             if (activeAdmin.crossProfileWidgetProviders == null) {
3374                 return false;
3375             }
3376             List<String> providers = activeAdmin.crossProfileWidgetProviders;
3377             if (providers.remove(packageName)) {
3378                 changedProviders = new ArrayList<>(providers);
3379                 saveSettingsLocked(userId);
3380             }
3381         }
3382
3383         if (changedProviders != null) {
3384             mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders);
3385             return true;
3386         }
3387
3388         return false;
3389     }
3390
3391     @Override
3392     public List<String> getCrossProfileWidgetProviders(ComponentName admin) {
3393         synchronized (this) {
3394             ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin,
3395                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
3396             if (activeAdmin.crossProfileWidgetProviders == null
3397                     || activeAdmin.crossProfileWidgetProviders.isEmpty()) {
3398                 return null;
3399             }
3400             if (mInjector.binderIsCallingUidMyUid()) {
3401                 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders);
3402             } else {
3403                 return activeAdmin.crossProfileWidgetProviders;
3404             }
3405         }
3406     }
3407
3408     /**
3409      * Return a single admin's expiration date/time, or the min (soonest) for all admins.
3410      * Returns 0 if not configured.
3411      */
3412     private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) {
3413         long timeout = 0L;
3414
3415         if (who != null) {
3416             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3417             return admin != null ? admin.passwordExpirationDate : timeout;
3418         }
3419
3420         // Return the strictest policy across all participating admins.
3421         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3422         final int N = admins.size();
3423         for (int i = 0; i < N; i++) {
3424             ActiveAdmin admin = admins.get(i);
3425             if (timeout == 0L || (admin.passwordExpirationDate != 0
3426                     && timeout > admin.passwordExpirationDate)) {
3427                 timeout = admin.passwordExpirationDate;
3428             }
3429         }
3430         return timeout;
3431     }
3432
3433     @Override
3434     public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) {
3435         if (!mHasFeature) {
3436             return 0L;
3437         }
3438         enforceFullCrossUsersPermission(userHandle);
3439         synchronized (this) {
3440             return getPasswordExpirationLocked(who, userHandle, parent);
3441         }
3442     }
3443
3444     @Override
3445     public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) {
3446         if (!mHasFeature) {
3447             return;
3448         }
3449         Preconditions.checkNotNull(who, "ComponentName is null");
3450         synchronized (this) {
3451             ActiveAdmin ap = getActiveAdminForCallerLocked(
3452                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3453             if (ap.minimumPasswordUpperCase != length) {
3454                 ap.minimumPasswordUpperCase = length;
3455                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3456             }
3457         }
3458     }
3459
3460     @Override
3461     public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) {
3462         if (!mHasFeature) {
3463             return 0;
3464         }
3465         enforceFullCrossUsersPermission(userHandle);
3466         synchronized (this) {
3467             int length = 0;
3468
3469             if (who != null) {
3470                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3471                 return admin != null ? admin.minimumPasswordUpperCase : length;
3472             }
3473
3474             // Return the strictest policy across all participating admins.
3475             List<ActiveAdmin> admins =
3476                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3477             final int N = admins.size();
3478             for (int i = 0; i < N; i++) {
3479                 ActiveAdmin admin = admins.get(i);
3480                 if (length < admin.minimumPasswordUpperCase) {
3481                     length = admin.minimumPasswordUpperCase;
3482                 }
3483             }
3484             return length;
3485         }
3486     }
3487
3488     @Override
3489     public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) {
3490         Preconditions.checkNotNull(who, "ComponentName is null");
3491         synchronized (this) {
3492             ActiveAdmin ap = getActiveAdminForCallerLocked(
3493                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3494             if (ap.minimumPasswordLowerCase != length) {
3495                 ap.minimumPasswordLowerCase = length;
3496                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3497             }
3498         }
3499     }
3500
3501     @Override
3502     public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) {
3503         if (!mHasFeature) {
3504             return 0;
3505         }
3506         enforceFullCrossUsersPermission(userHandle);
3507         synchronized (this) {
3508             int length = 0;
3509
3510             if (who != null) {
3511                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3512                 return admin != null ? admin.minimumPasswordLowerCase : length;
3513             }
3514
3515             // Return the strictest policy across all participating admins.
3516             List<ActiveAdmin> admins =
3517                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3518             final int N = admins.size();
3519             for (int i = 0; i < N; i++) {
3520                 ActiveAdmin admin = admins.get(i);
3521                 if (length < admin.minimumPasswordLowerCase) {
3522                     length = admin.minimumPasswordLowerCase;
3523                 }
3524             }
3525             return length;
3526         }
3527     }
3528
3529     @Override
3530     public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) {
3531         if (!mHasFeature) {
3532             return;
3533         }
3534         Preconditions.checkNotNull(who, "ComponentName is null");
3535         synchronized (this) {
3536             ActiveAdmin ap = getActiveAdminForCallerLocked(
3537                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3538             if (ap.minimumPasswordLetters != length) {
3539                 ap.minimumPasswordLetters = length;
3540                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3541             }
3542         }
3543     }
3544
3545     @Override
3546     public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) {
3547         if (!mHasFeature) {
3548             return 0;
3549         }
3550         enforceFullCrossUsersPermission(userHandle);
3551         synchronized (this) {
3552             int length = 0;
3553
3554             if (who != null) {
3555                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3556                 return admin != null ? admin.minimumPasswordLetters : length;
3557             }
3558
3559             // Return the strictest policy across all participating admins.
3560             List<ActiveAdmin> admins =
3561                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3562             final int N = admins.size();
3563             for (int i = 0; i < N; i++) {
3564                 ActiveAdmin admin = admins.get(i);
3565                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3566                     continue;
3567                 }
3568                 if (length < admin.minimumPasswordLetters) {
3569                     length = admin.minimumPasswordLetters;
3570                 }
3571             }
3572             return length;
3573         }
3574     }
3575
3576     @Override
3577     public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) {
3578         if (!mHasFeature) {
3579             return;
3580         }
3581         Preconditions.checkNotNull(who, "ComponentName is null");
3582         synchronized (this) {
3583             ActiveAdmin ap = getActiveAdminForCallerLocked(
3584                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3585             if (ap.minimumPasswordNumeric != length) {
3586                 ap.minimumPasswordNumeric = length;
3587                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3588             }
3589         }
3590     }
3591
3592     @Override
3593     public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) {
3594         if (!mHasFeature) {
3595             return 0;
3596         }
3597         enforceFullCrossUsersPermission(userHandle);
3598         synchronized (this) {
3599             int length = 0;
3600
3601             if (who != null) {
3602                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3603                 return admin != null ? admin.minimumPasswordNumeric : length;
3604             }
3605
3606             // Return the strictest policy across all participating admins.
3607             List<ActiveAdmin> admins =
3608                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3609             final int N = admins.size();
3610             for (int i = 0; i < N; i++) {
3611                 ActiveAdmin admin = admins.get(i);
3612                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3613                     continue;
3614                 }
3615                 if (length < admin.minimumPasswordNumeric) {
3616                     length = admin.minimumPasswordNumeric;
3617                 }
3618             }
3619             return length;
3620         }
3621     }
3622
3623     @Override
3624     public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) {
3625         if (!mHasFeature) {
3626             return;
3627         }
3628         Preconditions.checkNotNull(who, "ComponentName is null");
3629         synchronized (this) {
3630             ActiveAdmin ap = getActiveAdminForCallerLocked(
3631                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3632             if (ap.minimumPasswordSymbols != length) {
3633                 ap.minimumPasswordSymbols = length;
3634                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3635             }
3636         }
3637     }
3638
3639     @Override
3640     public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) {
3641         if (!mHasFeature) {
3642             return 0;
3643         }
3644         enforceFullCrossUsersPermission(userHandle);
3645         synchronized (this) {
3646             int length = 0;
3647
3648             if (who != null) {
3649                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3650                 return admin != null ? admin.minimumPasswordSymbols : length;
3651             }
3652
3653             // Return the strictest policy across all participating admins.
3654             List<ActiveAdmin> admins =
3655                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3656             final int N = admins.size();
3657             for (int i = 0; i < N; i++) {
3658                 ActiveAdmin admin = admins.get(i);
3659                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3660                     continue;
3661                 }
3662                 if (length < admin.minimumPasswordSymbols) {
3663                     length = admin.minimumPasswordSymbols;
3664                 }
3665             }
3666             return length;
3667         }
3668     }
3669
3670     @Override
3671     public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) {
3672         if (!mHasFeature) {
3673             return;
3674         }
3675         Preconditions.checkNotNull(who, "ComponentName is null");
3676         synchronized (this) {
3677             ActiveAdmin ap = getActiveAdminForCallerLocked(
3678                     who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3679             if (ap.minimumPasswordNonLetter != length) {
3680                 ap.minimumPasswordNonLetter = length;
3681                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3682             }
3683         }
3684     }
3685
3686     @Override
3687     public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) {
3688         if (!mHasFeature) {
3689             return 0;
3690         }
3691         enforceFullCrossUsersPermission(userHandle);
3692         synchronized (this) {
3693             int length = 0;
3694
3695             if (who != null) {
3696                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
3697                 return admin != null ? admin.minimumPasswordNonLetter : length;
3698             }
3699
3700             // Return the strictest policy across all participating admins.
3701             List<ActiveAdmin> admins =
3702                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3703             final int N = admins.size();
3704             for (int i = 0; i < N; i++) {
3705                 ActiveAdmin admin = admins.get(i);
3706                 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) {
3707                     continue;
3708                 }
3709                 if (length < admin.minimumPasswordNonLetter) {
3710                     length = admin.minimumPasswordNonLetter;
3711                 }
3712             }
3713             return length;
3714         }
3715     }
3716
3717     @Override
3718     public boolean isActivePasswordSufficient(int userHandle, boolean parent) {
3719         if (!mHasFeature) {
3720             return true;
3721         }
3722         enforceFullCrossUsersPermission(userHandle);
3723
3724         synchronized (this) {
3725             // This API can only be called by an active device admin,
3726             // so try to retrieve it to check that the caller is one.
3727             getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent);
3728             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3729             return isActivePasswordSufficientForUserLocked(policy, userHandle, parent);
3730         }
3731     }
3732
3733     @Override
3734     public boolean isProfileActivePasswordSufficientForParent(int userHandle) {
3735         if (!mHasFeature) {
3736             return true;
3737         }
3738         enforceFullCrossUsersPermission(userHandle);
3739         enforceManagedProfile(userHandle, "call APIs refering to the parent profile");
3740
3741         synchronized (this) {
3742             int targetUser = getProfileParentId(userHandle);
3743             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false));
3744             return isActivePasswordSufficientForUserLocked(policy, targetUser, false);
3745         }
3746     }
3747
3748     private boolean isActivePasswordSufficientForUserLocked(
3749             DevicePolicyData policy, int userHandle, boolean parent) {
3750         enforceUserUnlocked(userHandle, parent);
3751
3752         final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent);
3753         if (policy.mActivePasswordQuality < requiredPasswordQuality) {
3754             return false;
3755         }
3756         if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC
3757                 && policy.mActivePasswordLength < getPasswordMinimumLength(
3758                         null, userHandle, parent)) {
3759             return false;
3760         }
3761         if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3762             return true;
3763         }
3764         return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(
3765                     null, userHandle, parent)
3766                 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(
3767                         null, userHandle, parent)
3768                 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(
3769                         null, userHandle, parent)
3770                 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(
3771                         null, userHandle, parent)
3772                 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(
3773                         null, userHandle, parent)
3774                 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(
3775                         null, userHandle, parent);
3776     }
3777
3778     @Override
3779     public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) {
3780         enforceFullCrossUsersPermission(userHandle);
3781         synchronized (this) {
3782             if (!isCallerWithSystemUid()) {
3783                 // This API can only be called by an active device admin,
3784                 // so try to retrieve it to check that the caller is one.
3785                 getActiveAdminForCallerLocked(
3786                         null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3787             }
3788
3789             DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent));
3790
3791             return policy.mFailedPasswordAttempts;
3792         }
3793     }
3794
3795     @Override
3796     public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) {
3797         if (!mHasFeature) {
3798             return;
3799         }
3800         Preconditions.checkNotNull(who, "ComponentName is null");
3801         synchronized (this) {
3802             // This API can only be called by an active device admin,
3803             // so try to retrieve it to check that the caller is one.
3804             getActiveAdminForCallerLocked(
3805                     who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent);
3806             ActiveAdmin ap = getActiveAdminForCallerLocked(
3807                     who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent);
3808             if (ap.maximumFailedPasswordsForWipe != num) {
3809                 ap.maximumFailedPasswordsForWipe = num;
3810                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
3811             }
3812         }
3813     }
3814
3815     @Override
3816     public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) {
3817         if (!mHasFeature) {
3818             return 0;
3819         }
3820         enforceFullCrossUsersPermission(userHandle);
3821         synchronized (this) {
3822             ActiveAdmin admin = (who != null)
3823                     ? getActiveAdminUncheckedLocked(who, userHandle, parent)
3824                     : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent);
3825             return admin != null ? admin.maximumFailedPasswordsForWipe : 0;
3826         }
3827     }
3828
3829     @Override
3830     public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) {
3831         if (!mHasFeature) {
3832             return UserHandle.USER_NULL;
3833         }
3834         enforceFullCrossUsersPermission(userHandle);
3835         synchronized (this) {
3836             ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked(
3837                     userHandle, parent);
3838             return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL;
3839         }
3840     }
3841
3842     /**
3843      * Returns the admin with the strictest policy on maximum failed passwords for:
3844      * <ul>
3845      *   <li>this user if it has a separate profile challenge, or
3846      *   <li>this user and all profiles that don't have their own challenge otherwise.
3847      * </ul>
3848      * <p>If the policy for the primary and any other profile are equal, it returns the admin for
3849      * the primary profile.
3850      * Returns {@code null} if no participating admin has that policy set.
3851      */
3852     private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked(
3853             int userHandle, boolean parent) {
3854         int count = 0;
3855         ActiveAdmin strictestAdmin = null;
3856
3857         // Return the strictest policy across all participating admins.
3858         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
3859         final int N = admins.size();
3860         for (int i = 0; i < N; i++) {
3861             ActiveAdmin admin = admins.get(i);
3862             if (admin.maximumFailedPasswordsForWipe ==
3863                     ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) {
3864                 continue;  // No max number of failed passwords policy set for this profile.
3865             }
3866
3867             // We always favor the primary profile if several profiles have the same value set.
3868             int userId = admin.getUserHandle().getIdentifier();
3869             if (count == 0 ||
3870                     count > admin.maximumFailedPasswordsForWipe ||
3871                     (count == admin.maximumFailedPasswordsForWipe &&
3872                             getUserInfo(userId).isPrimary())) {
3873                 count = admin.maximumFailedPasswordsForWipe;
3874                 strictestAdmin = admin;
3875             }
3876         }
3877         return strictestAdmin;
3878     }
3879
3880     private UserInfo getUserInfo(@UserIdInt int userId) {
3881         final long token = mInjector.binderClearCallingIdentity();
3882         try {
3883             return mUserManager.getUserInfo(userId);
3884         } finally {
3885             mInjector.binderRestoreCallingIdentity(token);
3886         }
3887     }
3888
3889     @Override
3890     public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException {
3891         if (!mHasFeature) {
3892             return false;
3893         }
3894         final int callingUid = mInjector.binderGetCallingUid();
3895         final int userHandle = mInjector.userHandleGetCallingUserId();
3896
3897         String password = passwordOrNull != null ? passwordOrNull : "";
3898
3899         // Password resetting to empty/null is not allowed for managed profiles.
3900         if (TextUtils.isEmpty(password)) {
3901             enforceNotManagedProfile(userHandle, "clear the active password");
3902         }
3903
3904         int quality;
3905         synchronized (this) {
3906             // If caller has PO (or DO) it can change the password, so see if that's the case first.
3907             ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked(
3908                     null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid);
3909             final boolean preN;
3910             if (admin != null) {
3911                 preN = getTargetSdk(admin.info.getPackageName(),
3912                         userHandle) <= android.os.Build.VERSION_CODES.M;
3913             } else {
3914                 // Otherwise, make sure the caller has any active admin with the right policy.
3915                 admin = getActiveAdminForCallerLocked(null,
3916                         DeviceAdminInfo.USES_POLICY_RESET_PASSWORD);
3917                 preN = getTargetSdk(admin.info.getPackageName(),
3918                         userHandle) <= android.os.Build.VERSION_CODES.M;
3919
3920                 // As of N, password resetting to empty/null is not allowed anymore.
3921                 // TODO Should we allow DO/PO to set an empty password?
3922                 if (TextUtils.isEmpty(password)) {
3923                     if (!preN) {
3924                         throw new SecurityException("Cannot call with null password");
3925                     } else {
3926                         Slog.e(LOG_TAG, "Cannot call with null password");
3927                         return false;
3928                     }
3929                 }
3930                 // As of N, password cannot be changed by the admin if it is already set.
3931                 if (isLockScreenSecureUnchecked(userHandle)) {
3932                     if (!preN) {
3933                         throw new SecurityException("Admin cannot change current password");
3934                     } else {
3935                         Slog.e(LOG_TAG, "Admin cannot change current password");
3936                         return false;
3937                     }
3938                 }
3939             }
3940             // Do not allow to reset password when current user has a managed profile
3941             if (!isManagedProfile(userHandle)) {
3942                 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
3943                     if (userInfo.isManagedProfile()) {
3944                         if (!preN) {
3945                             throw new IllegalStateException(
3946                                     "Cannot reset password on user has managed profile");
3947                         } else {
3948                             Slog.e(LOG_TAG, "Cannot reset password on user has managed profile");
3949                             return false;
3950                         }
3951                     }
3952                 }
3953             }
3954             // Do not allow to reset password when user is locked
3955             if (!mUserManager.isUserUnlocked(userHandle)) {
3956                 if (!preN) {
3957                     throw new IllegalStateException("Cannot reset password when user is locked");
3958                 } else {
3959                     Slog.e(LOG_TAG, "Cannot reset password when user is locked");
3960                     return false;
3961                 }
3962             }
3963
3964             quality = getPasswordQuality(null, userHandle, /* parent */ false);
3965             if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) {
3966                 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
3967             }
3968             if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
3969                 int realQuality = LockPatternUtils.computePasswordQuality(password);
3970                 if (realQuality < quality
3971                         && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3972                     Slog.w(LOG_TAG, "resetPassword: password quality 0x"
3973                             + Integer.toHexString(realQuality)
3974                             + " does not meet required quality 0x"
3975                             + Integer.toHexString(quality));
3976                     return false;
3977                 }
3978                 quality = Math.max(realQuality, quality);
3979             }
3980             int length = getPasswordMinimumLength(null, userHandle, /* parent */ false);
3981             if (password.length() < length) {
3982                 Slog.w(LOG_TAG, "resetPassword: password length " + password.length()
3983                         + " does not meet required length " + length);
3984                 return false;
3985             }
3986             if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) {
3987                 int letters = 0;
3988                 int uppercase = 0;
3989                 int lowercase = 0;
3990                 int numbers = 0;
3991                 int symbols = 0;
3992                 int nonletter = 0;
3993                 for (int i = 0; i < password.length(); i++) {
3994                     char c = password.charAt(i);
3995                     if (c >= 'A' && c <= 'Z') {
3996                         letters++;
3997                         uppercase++;
3998                     } else if (c >= 'a' && c <= 'z') {
3999                         letters++;
4000                         lowercase++;
4001                     } else if (c >= '0' && c <= '9') {
4002                         numbers++;
4003                         nonletter++;
4004                     } else {
4005                         symbols++;
4006                         nonletter++;
4007                     }
4008                 }
4009                 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false);
4010                 if(letters < neededLetters) {
4011                     Slog.w(LOG_TAG, "resetPassword: number of letters " + letters
4012                             + " does not meet required number of letters " + neededLetters);
4013                     return false;
4014                 }
4015                 int neededNumbers = getPasswordMinimumNumeric(null, userHandle, /* parent */ false);
4016                 if (numbers < neededNumbers) {
4017                     Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers
4018                             + " does not meet required number of numerical digits "
4019                             + neededNumbers);
4020                     return false;
4021                 }
4022                 int neededLowerCase = getPasswordMinimumLowerCase(
4023                         null, userHandle, /* parent */ false);
4024                 if (lowercase < neededLowerCase) {
4025                     Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase
4026                             + " does not meet required number of lowercase letters "
4027                             + neededLowerCase);
4028                     return false;
4029                 }
4030                 int neededUpperCase = getPasswordMinimumUpperCase(
4031                         null, userHandle, /* parent */ false);
4032                 if (uppercase < neededUpperCase) {
4033                     Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase
4034                             + " does not meet required number of uppercase letters "
4035                             + neededUpperCase);
4036                     return false;
4037                 }
4038                 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false);
4039                 if (symbols < neededSymbols) {
4040                     Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols
4041                             + " does not meet required number of special symbols " + neededSymbols);
4042                     return false;
4043                 }
4044                 int neededNonLetter = getPasswordMinimumNonLetter(
4045                         null, userHandle, /* parent */ false);
4046                 if (nonletter < neededNonLetter) {
4047                     Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter
4048                             + " does not meet required number of non-letter characters "
4049                             + neededNonLetter);
4050                     return false;
4051                 }
4052             }
4053         }
4054
4055         DevicePolicyData policy = getUserData(userHandle);
4056         if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) {
4057             Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user");
4058             return false;
4059         }
4060
4061         boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid);
4062         boolean doNotAskCredentialsOnBoot =
4063                 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0;
4064         if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) {
4065             setDoNotAskCredentialsOnBoot();
4066         }
4067
4068         // Don't do this with the lock held, because it is going to call
4069         // back in to the service.
4070         final long ident = mInjector.binderClearCallingIdentity();
4071         try {
4072             if (!TextUtils.isEmpty(password)) {
4073                 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle);
4074             } else {
4075                 mLockPatternUtils.clearLock(userHandle);
4076             }
4077             boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0;
4078             if (requireEntry) {
4079                 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW,
4080                         UserHandle.USER_ALL);
4081             }
4082             synchronized (this) {
4083                 int newOwner = requireEntry ? callingUid : -1;
4084                 if (policy.mPasswordOwner != newOwner) {
4085                     policy.mPasswordOwner = newOwner;
4086                     saveSettingsLocked(userHandle);
4087                 }
4088             }
4089         } finally {
4090             mInjector.binderRestoreCallingIdentity(ident);
4091         }
4092
4093         return true;
4094     }
4095
4096     private boolean isLockScreenSecureUnchecked(int userId) {
4097         long ident = mInjector.binderClearCallingIdentity();
4098         try {
4099             return mLockPatternUtils.isSecure(userId);
4100         } finally {
4101             mInjector.binderRestoreCallingIdentity(ident);
4102         }
4103     }
4104
4105     private void setDoNotAskCredentialsOnBoot() {
4106         synchronized (this) {
4107             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4108             if (!policyData.doNotAskCredentialsOnBoot) {
4109                 policyData.doNotAskCredentialsOnBoot = true;
4110                 saveSettingsLocked(UserHandle.USER_SYSTEM);
4111             }
4112         }
4113     }
4114
4115     @Override
4116     public boolean getDoNotAskCredentialsOnBoot() {
4117         mContext.enforceCallingOrSelfPermission(
4118                 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null);
4119         synchronized (this) {
4120             DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM);
4121             return policyData.doNotAskCredentialsOnBoot;
4122         }
4123     }
4124
4125     @Override
4126     public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) {
4127         if (!mHasFeature) {
4128             return;
4129         }
4130         Preconditions.checkNotNull(who, "ComponentName is null");
4131         final int userHandle = mInjector.userHandleGetCallingUserId();
4132         synchronized (this) {
4133             ActiveAdmin ap = getActiveAdminForCallerLocked(
4134                     who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4135             if (ap.maximumTimeToUnlock != timeMs) {
4136                 ap.maximumTimeToUnlock = timeMs;
4137                 saveSettingsLocked(userHandle);
4138                 updateMaximumTimeToLockLocked(userHandle);
4139             }
4140         }
4141     }
4142
4143     void updateMaximumTimeToLockLocked(int userHandle) {
4144         // Calculate the min timeout for all profiles - including the ones with a separate
4145         // challenge. Ideally if the timeout only affected the profile challenge we'd lock that
4146         // challenge only and keep the screen on. However there is no easy way of doing that at the
4147         // moment so we set the screen off timeout regardless of whether it affects the parent user
4148         // or the profile challenge only.
4149         long timeMs = Long.MAX_VALUE;
4150         int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle);
4151         for (int profileId : profileIds) {
4152             DevicePolicyData policy = getUserDataUnchecked(profileId);
4153             final int N = policy.mAdminList.size();
4154             for (int i = 0; i < N; i++) {
4155                 ActiveAdmin admin = policy.mAdminList.get(i);
4156                 if (admin.maximumTimeToUnlock > 0
4157                         && timeMs > admin.maximumTimeToUnlock) {
4158                     timeMs = admin.maximumTimeToUnlock;
4159                 }
4160                 // If userInfo.id is a managed profile, we also need to look at
4161                 // the policies set on the parent.
4162                 if (admin.hasParentActiveAdmin()) {
4163                     final ActiveAdmin parentAdmin = admin.getParentActiveAdmin();
4164                     if (parentAdmin.maximumTimeToUnlock > 0
4165                             && timeMs > parentAdmin.maximumTimeToUnlock) {
4166                         timeMs = parentAdmin.maximumTimeToUnlock;
4167                     }
4168                 }
4169             }
4170         }
4171
4172         // We only store the last maximum time to lock on the parent profile. So if calling from a
4173         // managed profile, retrieve the policy for the parent.
4174         DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle));
4175         if (policy.mLastMaximumTimeToLock == timeMs) {
4176             return;
4177         }
4178         policy.mLastMaximumTimeToLock = timeMs;
4179
4180         final long ident = mInjector.binderClearCallingIdentity();
4181         try {
4182             if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) {
4183                 // Make sure KEEP_SCREEN_ON is disabled, since that
4184                 // would allow bypassing of the maximum time to lock.
4185                 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0);
4186             }
4187
4188             mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin(
4189                     (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE));
4190         } finally {
4191             mInjector.binderRestoreCallingIdentity(ident);
4192         }
4193     }
4194
4195     @Override
4196     public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) {
4197         if (!mHasFeature) {
4198             return 0;
4199         }
4200         enforceFullCrossUsersPermission(userHandle);
4201         synchronized (this) {
4202             if (who != null) {
4203                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
4204                 return admin != null ? admin.maximumTimeToUnlock : 0;
4205             }
4206             // Return the strictest policy across all participating admins.
4207             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4208                     userHandle, parent);
4209             return getMaximumTimeToLockPolicyFromAdmins(admins);
4210         }
4211     }
4212
4213     @Override
4214     public long getMaximumTimeToLockForUserAndProfiles(int userHandle) {
4215         if (!mHasFeature) {
4216             return 0;
4217         }
4218         enforceFullCrossUsersPermission(userHandle);
4219         synchronized (this) {
4220             // All admins for this user.
4221             ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>();
4222             for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) {
4223                 DevicePolicyData policy = getUserData(userInfo.id);
4224                 admins.addAll(policy.mAdminList);
4225                 // If it is a managed profile, it may have parent active admins
4226                 if (userInfo.isManagedProfile()) {
4227                     for (ActiveAdmin admin : policy.mAdminList) {
4228                         if (admin.hasParentActiveAdmin()) {
4229                             admins.add(admin.getParentActiveAdmin());
4230                         }
4231                     }
4232                 }
4233             }
4234             return getMaximumTimeToLockPolicyFromAdmins(admins);
4235         }
4236     }
4237
4238     private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) {
4239         long time = 0;
4240         final int N = admins.size();
4241         for (int i = 0; i < N; i++) {
4242             ActiveAdmin admin = admins.get(i);
4243             if (time == 0) {
4244                 time = admin.maximumTimeToUnlock;
4245             } else if (admin.maximumTimeToUnlock != 0
4246                     && time > admin.maximumTimeToUnlock) {
4247                 time = admin.maximumTimeToUnlock;
4248             }
4249         }
4250         return time;
4251     }
4252
4253     @Override
4254     public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs,
4255             boolean parent) {
4256         if (!mHasFeature) {
4257             return;
4258         }
4259         Preconditions.checkNotNull(who, "ComponentName is null");
4260         Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number.");
4261         // timeoutMs with value 0 means that the admin doesn't participate
4262         // timeoutMs is clamped to the interval in case the internal constants change in the future
4263         if (timeoutMs != 0 && timeoutMs < MINIMUM_STRONG_AUTH_TIMEOUT_MS) {
4264             timeoutMs = MINIMUM_STRONG_AUTH_TIMEOUT_MS;
4265         }
4266         if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) {
4267             timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4268         }
4269
4270         final int userHandle = mInjector.userHandleGetCallingUserId();
4271         synchronized (this) {
4272             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
4273                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent);
4274             if (ap.strongAuthUnlockTimeout != timeoutMs) {
4275                 ap.strongAuthUnlockTimeout = timeoutMs;
4276                 saveSettingsLocked(userHandle);
4277             }
4278         }
4279     }
4280
4281     /**
4282      * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all
4283      * admins if who is null.
4284      * Returns 0 if not configured for the provided admin.
4285      */
4286     @Override
4287     public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
4288         if (!mHasFeature) {
4289             return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4290         }
4291         enforceFullCrossUsersPermission(userId);
4292         synchronized (this) {
4293             if (who != null) {
4294                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
4295                 return admin != null ? admin.strongAuthUnlockTimeout : 0;
4296             }
4297
4298             // Return the strictest policy across all participating admins.
4299             List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);
4300
4301             long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
4302             for (int i = 0; i < admins.size(); i++) {
4303                 final long timeout = admins.get(i).strongAuthUnlockTimeout;
4304                 if (timeout != 0) { // take only participating admins into account
4305                     strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
4306                 }
4307             }
4308             return Math.max(strongAuthUnlockTimeout, MINIMUM_STRONG_AUTH_TIMEOUT_MS);
4309         }
4310     }
4311
4312     @Override
4313     public void lockNow(boolean parent) {
4314         if (!mHasFeature) {
4315             return;
4316         }
4317         synchronized (this) {
4318             // This API can only be called by an active device admin,
4319             // so try to retrieve it to check that the caller is one.
4320             getActiveAdminForCallerLocked(
4321                     null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent);
4322
4323             int userToLock = mInjector.userHandleGetCallingUserId();
4324
4325             // Unless this is a managed profile with work challenge enabled, lock all users.
4326             if (parent || !isSeparateProfileChallengeEnabled(userToLock)) {
4327                 userToLock = UserHandle.USER_ALL;
4328             }
4329             final long ident = mInjector.binderClearCallingIdentity();
4330             try {
4331                 mLockPatternUtils.requireStrongAuth(
4332                         STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock);
4333                 if (userToLock == UserHandle.USER_ALL) {
4334                     // Power off the display
4335                     mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(),
4336                             PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0);
4337                     mInjector.getIWindowManager().lockNow(null);
4338                 } else {
4339                     mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true);
4340                 }
4341             } catch (RemoteException e) {
4342             } finally {
4343                 mInjector.binderRestoreCallingIdentity(ident);
4344             }
4345         }
4346     }
4347
4348     @Override
4349     public void enforceCanManageCaCerts(ComponentName who) {
4350         if (who == null) {
4351             if (!isCallerDelegatedCertInstaller()) {
4352                 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null);
4353             }
4354         } else {
4355             synchronized (this) {
4356                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4357             }
4358         }
4359     }
4360
4361     private void enforceCanManageInstalledKeys(ComponentName who) {
4362         if (who == null) {
4363             if (!isCallerDelegatedCertInstaller()) {
4364                 throw new SecurityException("who == null, but caller is not cert installer");
4365             }
4366         } else {
4367             synchronized (this) {
4368                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4369             }
4370         }
4371     }
4372
4373     private boolean isCallerDelegatedCertInstaller() {
4374         final int callingUid = mInjector.binderGetCallingUid();
4375         final int userHandle = UserHandle.getUserId(callingUid);
4376         synchronized (this) {
4377             final DevicePolicyData policy = getUserData(userHandle);
4378             if (policy.mDelegatedCertInstallerPackage == null) {
4379                 return false;
4380             }
4381
4382             try {
4383                 int uid = mContext.getPackageManager().getPackageUidAsUser(
4384                         policy.mDelegatedCertInstallerPackage, userHandle);
4385                 return uid == callingUid;
4386             } catch (NameNotFoundException e) {
4387                 return false;
4388             }
4389         }
4390     }
4391
4392     @Override
4393     public boolean approveCaCert(String alias, int userId, boolean approval) {
4394         enforceManageUsers();
4395         synchronized (this) {
4396             Set<String> certs = getUserData(userId).mAcceptedCaCertificates;
4397             boolean changed = (approval ? certs.add(alias) : certs.remove(alias));
4398             if (!changed) {
4399                 return false;
4400             }
4401             saveSettingsLocked(userId);
4402         }
4403         new MonitoringCertNotificationTask().execute(userId);
4404         return true;
4405     }
4406
4407     @Override
4408     public boolean isCaCertApproved(String alias, int userId) {
4409         enforceManageUsers();
4410         synchronized (this) {
4411             return getUserData(userId).mAcceptedCaCertificates.contains(alias);
4412         }
4413     }
4414
4415     private void removeCaApprovalsIfNeeded(int userId) {
4416         for (UserInfo userInfo : mUserManager.getProfiles(userId)) {
4417             boolean isSecure = mLockPatternUtils.isSecure(userInfo.id);
4418             if (userInfo.isManagedProfile()){
4419                 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id));
4420             }
4421             if (!isSecure) {
4422                 synchronized (this) {
4423                     getUserData(userInfo.id).mAcceptedCaCertificates.clear();
4424                     saveSettingsLocked(userInfo.id);
4425                 }
4426
4427                 new MonitoringCertNotificationTask().execute(userInfo.id);
4428             }
4429         }
4430     }
4431
4432     @Override
4433     public boolean installCaCert(ComponentName admin, byte[] certBuffer) throws RemoteException {
4434         enforceCanManageCaCerts(admin);
4435
4436         byte[] pemCert;
4437         try {
4438             X509Certificate cert = parseCert(certBuffer);
4439             pemCert = Credentials.convertToPem(cert);
4440         } catch (CertificateException ce) {
4441             Log.e(LOG_TAG, "Problem converting cert", ce);
4442             return false;
4443         } catch (IOException ioe) {
4444             Log.e(LOG_TAG, "Problem reading cert", ioe);
4445             return false;
4446         }
4447
4448         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4449         final long id = mInjector.binderClearCallingIdentity();
4450         try {
4451             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4452             try {
4453                 keyChainConnection.getService().installCaCertificate(pemCert);
4454                 return true;
4455             } catch (RemoteException e) {
4456                 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e);
4457             } finally {
4458                 keyChainConnection.close();
4459             }
4460         } catch (InterruptedException e1) {
4461             Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1);
4462             Thread.currentThread().interrupt();
4463         } finally {
4464             mInjector.binderRestoreCallingIdentity(id);
4465         }
4466         return false;
4467     }
4468
4469     private static X509Certificate parseCert(byte[] certBuffer) throws CertificateException {
4470         CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
4471         return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(
4472                 certBuffer));
4473     }
4474
4475     @Override
4476     public void uninstallCaCerts(ComponentName admin, String[] aliases) {
4477         enforceCanManageCaCerts(admin);
4478
4479         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4480         final long id = mInjector.binderClearCallingIdentity();
4481         try {
4482             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4483             try {
4484                 for (int i = 0 ; i < aliases.length; i++) {
4485                     keyChainConnection.getService().deleteCaCertificate(aliases[i]);
4486                 }
4487             } catch (RemoteException e) {
4488                 Log.e(LOG_TAG, "from CaCertUninstaller: ", e);
4489             } finally {
4490                 keyChainConnection.close();
4491             }
4492         } catch (InterruptedException ie) {
4493             Log.w(LOG_TAG, "CaCertUninstaller: ", ie);
4494             Thread.currentThread().interrupt();
4495         } finally {
4496             mInjector.binderRestoreCallingIdentity(id);
4497         }
4498     }
4499
4500     @Override
4501     public boolean installKeyPair(ComponentName who, byte[] privKey, byte[] cert, byte[] chain,
4502             String alias, boolean requestAccess) {
4503         enforceCanManageInstalledKeys(who);
4504
4505         final int callingUid = mInjector.binderGetCallingUid();
4506         final long id = mInjector.binderClearCallingIdentity();
4507         try {
4508             final KeyChainConnection keyChainConnection =
4509                     KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid));
4510             try {
4511                 IKeyChainService keyChain = keyChainConnection.getService();
4512                 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) {
4513                     return false;
4514                 }
4515                 if (requestAccess) {
4516                     keyChain.setGrant(callingUid, alias, true);
4517                 }
4518                 return true;
4519             } catch (RemoteException e) {
4520                 Log.e(LOG_TAG, "Installing certificate", e);
4521             } finally {
4522                 keyChainConnection.close();
4523             }
4524         } catch (InterruptedException e) {
4525             Log.w(LOG_TAG, "Interrupted while installing certificate", e);
4526             Thread.currentThread().interrupt();
4527         } finally {
4528             mInjector.binderRestoreCallingIdentity(id);
4529         }
4530         return false;
4531     }
4532
4533     @Override
4534     public boolean removeKeyPair(ComponentName who, String alias) {
4535         enforceCanManageInstalledKeys(who);
4536
4537         final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId());
4538         final long id = Binder.clearCallingIdentity();
4539         try {
4540             final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle);
4541             try {
4542                 IKeyChainService keyChain = keyChainConnection.getService();
4543                 return keyChain.removeKeyPair(alias);
4544             } catch (RemoteException e) {
4545                 Log.e(LOG_TAG, "Removing keypair", e);
4546             } finally {
4547                 keyChainConnection.close();
4548             }
4549         } catch (InterruptedException e) {
4550             Log.w(LOG_TAG, "Interrupted while removing keypair", e);
4551             Thread.currentThread().interrupt();
4552         } finally {
4553             Binder.restoreCallingIdentity(id);
4554         }
4555         return false;
4556     }
4557
4558     @Override
4559     public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias,
4560             final IBinder response) {
4561         // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers.
4562         if (!isCallerWithSystemUid()) {
4563             return;
4564         }
4565
4566         final UserHandle caller = mInjector.binderGetCallingUserHandle();
4567         // If there is a profile owner, redirect to that; otherwise query the device owner.
4568         ComponentName aliasChooser = getProfileOwner(caller.getIdentifier());
4569         if (aliasChooser == null && caller.isSystem()) {
4570             ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked();
4571             if (deviceOwnerAdmin != null) {
4572                 aliasChooser = deviceOwnerAdmin.info.getComponent();
4573             }
4574         }
4575         if (aliasChooser == null) {
4576             sendPrivateKeyAliasResponse(null, response);
4577             return;
4578         }
4579
4580         Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS);
4581         intent.setComponent(aliasChooser);
4582         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid);
4583         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri);
4584         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias);
4585         intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response);
4586         intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4587
4588         final long id = mInjector.binderClearCallingIdentity();
4589         try {
4590             mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() {
4591                 @Override
4592                 public void onReceive(Context context, Intent intent) {
4593                     final String chosenAlias = getResultData();
4594                     sendPrivateKeyAliasResponse(chosenAlias, response);
4595                 }
4596             }, null, Activity.RESULT_OK, null, null);
4597         } finally {
4598             mInjector.binderRestoreCallingIdentity(id);
4599         }
4600     }
4601
4602     private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) {
4603         final IKeyChainAliasCallback keyChainAliasResponse =
4604                 IKeyChainAliasCallback.Stub.asInterface(responseBinder);
4605         new AsyncTask<Void, Void, Void>() {
4606             @Override
4607             protected Void doInBackground(Void... unused) {
4608                 try {
4609                     keyChainAliasResponse.alias(alias);
4610                 } catch (Exception e) {
4611                     // Catch everything (not just RemoteException): caller could throw a
4612                     // RuntimeException back across processes.
4613                     Log.e(LOG_TAG, "error while responding to callback", e);
4614                 }
4615                 return null;
4616             }
4617         }.execute();
4618     }
4619
4620     @Override
4621     public void setCertInstallerPackage(ComponentName who, String installerPackage)
4622             throws SecurityException {
4623         int userHandle = UserHandle.getCallingUserId();
4624         synchronized (this) {
4625             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4626             if (getTargetSdk(who.getPackageName(), userHandle) >= Build.VERSION_CODES.N) {
4627                 if (installerPackage != null &&
4628                         !isPackageInstalledForUser(installerPackage, userHandle)) {
4629                     throw new IllegalArgumentException("Package " + installerPackage
4630                             + " is not installed on the current user");
4631                 }
4632             }
4633             DevicePolicyData policy = getUserData(userHandle);
4634             policy.mDelegatedCertInstallerPackage = installerPackage;
4635             saveSettingsLocked(userHandle);
4636         }
4637     }
4638
4639     @Override
4640     public String getCertInstallerPackage(ComponentName who) throws SecurityException {
4641         int userHandle = UserHandle.getCallingUserId();
4642         synchronized (this) {
4643             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4644             DevicePolicyData policy = getUserData(userHandle);
4645             return policy.mDelegatedCertInstallerPackage;
4646         }
4647     }
4648
4649     /**
4650      * @return {@code true} if the package is installed and set as always-on, {@code false} if it is
4651      * not installed and therefore not available.
4652      *
4653      * @throws SecurityException if the caller is not a profile or device owner.
4654      * @throws UnsupportedOperationException if the package does not support being set as always-on.
4655      */
4656     @Override
4657     public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown)
4658             throws SecurityException {
4659         synchronized (this) {
4660             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4661         }
4662
4663         final int userId = mInjector.userHandleGetCallingUserId();
4664         final long token = mInjector.binderClearCallingIdentity();
4665         try {
4666             if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) {
4667                 return false;
4668             }
4669             ConnectivityManager connectivityManager = (ConnectivityManager)
4670                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4671             if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) {
4672                 throw new UnsupportedOperationException();
4673             }
4674         } finally {
4675             mInjector.binderRestoreCallingIdentity(token);
4676         }
4677         return true;
4678     }
4679
4680     @Override
4681     public String getAlwaysOnVpnPackage(ComponentName admin)
4682             throws SecurityException {
4683         synchronized (this) {
4684             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
4685         }
4686
4687         final int userId = mInjector.userHandleGetCallingUserId();
4688         final long token = mInjector.binderClearCallingIdentity();
4689         try{
4690             ConnectivityManager connectivityManager = (ConnectivityManager)
4691                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
4692             return connectivityManager.getAlwaysOnVpnPackageForUser(userId);
4693         } finally {
4694             mInjector.binderRestoreCallingIdentity(token);
4695         }
4696     }
4697
4698     private void wipeDataNoLock(boolean wipeExtRequested, String reason) {
4699         if (wipeExtRequested) {
4700             StorageManager sm = (StorageManager) mContext.getSystemService(
4701                     Context.STORAGE_SERVICE);
4702             sm.wipeAdoptableDisks();
4703         }
4704         try {
4705             RecoverySystem.rebootWipeUserData(mContext, reason);
4706         } catch (IOException | SecurityException e) {
4707             Slog.w(LOG_TAG, "Failed requesting data wipe", e);
4708         }
4709     }
4710
4711     @Override
4712     public void wipeData(int flags) {
4713         if (!mHasFeature) {
4714             return;
4715         }
4716         final int userHandle = mInjector.userHandleGetCallingUserId();
4717         enforceFullCrossUsersPermission(userHandle);
4718
4719         final String source;
4720         synchronized (this) {
4721             // This API can only be called by an active device admin,
4722             // so try to retrieve it to check that the caller is one.
4723             final ActiveAdmin admin = getActiveAdminForCallerLocked(null,
4724                     DeviceAdminInfo.USES_POLICY_WIPE_DATA);
4725             source = admin.info.getComponent().flattenToShortString();
4726
4727             long ident = mInjector.binderClearCallingIdentity();
4728             try {
4729                 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) {
4730                     if (!isDeviceOwner(admin.info.getComponent(), userHandle)) {
4731                         throw new SecurityException(
4732                                "Only device owner admins can set WIPE_RESET_PROTECTION_DATA");
4733                     }
4734                     PersistentDataBlockManager manager = (PersistentDataBlockManager)
4735                             mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
4736                     if (manager != null) {
4737                         manager.wipe();
4738                     }
4739                 }
4740             } finally {
4741                 mInjector.binderRestoreCallingIdentity(ident);
4742             }
4743         }
4744         final boolean wipeExtRequested = (flags & WIPE_EXTERNAL_STORAGE) != 0;
4745         wipeDeviceNoLock(wipeExtRequested, userHandle,
4746                 "DevicePolicyManager.wipeData() from " + source);
4747     }
4748
4749     private void wipeDeviceNoLock(boolean wipeExtRequested, final int userHandle, String reason) {
4750         final long ident = mInjector.binderClearCallingIdentity();
4751         try {
4752             if (userHandle == UserHandle.USER_SYSTEM) {
4753                 wipeDataNoLock(wipeExtRequested, reason);
4754             } else {
4755                 mHandler.post(new Runnable() {
4756                     @Override
4757                     public void run() {
4758                         try {
4759                             IActivityManager am = mInjector.getIActivityManager();
4760                             if (am.getCurrentUser().id == userHandle) {
4761                                 am.switchUser(UserHandle.USER_SYSTEM);
4762                             }
4763
4764                             boolean isManagedProfile = isManagedProfile(userHandle);
4765                             if (!mUserManager.removeUser(userHandle)) {
4766                                 Slog.w(LOG_TAG, "Couldn't remove user " + userHandle);
4767                             } else if (isManagedProfile) {
4768                                 sendWipeProfileNotification();
4769                             }
4770                         } catch (RemoteException re) {
4771                             // Shouldn't happen
4772                         }
4773                     }
4774                 });
4775             }
4776         } finally {
4777             mInjector.binderRestoreCallingIdentity(ident);
4778         }
4779     }
4780
4781     private void sendWipeProfileNotification() {
4782         String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe);
4783         Notification notification = new Notification.Builder(mContext)
4784                 .setSmallIcon(android.R.drawable.stat_sys_warning)
4785                 .setContentTitle(mContext.getString(R.string.work_profile_deleted))
4786                 .setContentText(contentText)
4787                 .setColor(mContext.getColor(R.color.system_notification_accent_color))
4788                 .setStyle(new Notification.BigTextStyle().bigText(contentText))
4789                 .build();
4790         mInjector.getNotificationManager().notify(PROFILE_WIPED_NOTIFICATION_ID, notification);
4791     }
4792
4793     private void clearWipeProfileNotification() {
4794         mInjector.getNotificationManager().cancel(PROFILE_WIPED_NOTIFICATION_ID);
4795     }
4796
4797     @Override
4798     public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) {
4799         if (!mHasFeature) {
4800             return;
4801         }
4802         enforceFullCrossUsersPermission(userHandle);
4803         mContext.enforceCallingOrSelfPermission(
4804                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4805
4806         synchronized (this) {
4807             ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle);
4808             if (admin == null) {
4809                 result.sendResult(null);
4810                 return;
4811             }
4812             Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED);
4813             intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4814             intent.setComponent(admin.info.getComponent());
4815             mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle),
4816                     null, new BroadcastReceiver() {
4817                 @Override
4818                 public void onReceive(Context context, Intent intent) {
4819                     result.sendResult(getResultExtras(false));
4820                 }
4821             }, null, Activity.RESULT_OK, null, null);
4822         }
4823     }
4824
4825     @Override
4826     public void setActivePasswordState(int quality, int length, int letters, int uppercase,
4827             int lowercase, int numbers, int symbols, int nonletter, int userHandle) {
4828         if (!mHasFeature) {
4829             return;
4830         }
4831         enforceFullCrossUsersPermission(userHandle);
4832         mContext.enforceCallingOrSelfPermission(
4833                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4834
4835         // If the managed profile doesn't have a separate password, set the metrics to default
4836         if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) {
4837             quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
4838             length = 0;
4839             letters = 0;
4840             uppercase = 0;
4841             lowercase = 0;
4842             numbers = 0;
4843             symbols = 0;
4844             nonletter = 0;
4845         }
4846
4847         validateQualityConstant(quality);
4848         DevicePolicyData policy = getUserData(userHandle);
4849         synchronized (this) {
4850             policy.mActivePasswordQuality = quality;
4851             policy.mActivePasswordLength = length;
4852             policy.mActivePasswordLetters = letters;
4853             policy.mActivePasswordLowerCase = lowercase;
4854             policy.mActivePasswordUpperCase = uppercase;
4855             policy.mActivePasswordNumeric = numbers;
4856             policy.mActivePasswordSymbols = symbols;
4857             policy.mActivePasswordNonLetter = nonletter;
4858         }
4859     }
4860
4861     @Override
4862     public void reportPasswordChanged(int userId) {
4863         if (!mHasFeature) {
4864             return;
4865         }
4866         enforceFullCrossUsersPermission(userId);
4867
4868         // Managed Profile password can only be changed when it has a separate challenge.
4869         if (!isSeparateProfileChallengeEnabled(userId)) {
4870             enforceNotManagedProfile(userId, "set the active password");
4871         }
4872
4873         mContext.enforceCallingOrSelfPermission(
4874                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4875
4876         DevicePolicyData policy = getUserData(userId);
4877
4878         long ident = mInjector.binderClearCallingIdentity();
4879         try {
4880             synchronized (this) {
4881                 policy.mFailedPasswordAttempts = 0;
4882                 saveSettingsLocked(userId);
4883                 updatePasswordExpirationsLocked(userId);
4884                 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false);
4885
4886                 // Send a broadcast to each profile using this password as its primary unlock.
4887                 sendAdminCommandForLockscreenPoliciesLocked(
4888                         DeviceAdminReceiver.ACTION_PASSWORD_CHANGED,
4889                         DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId);
4890             }
4891             removeCaApprovalsIfNeeded(userId);
4892         } finally {
4893             mInjector.binderRestoreCallingIdentity(ident);
4894         }
4895     }
4896
4897     /**
4898      * Called any time the device password is updated. Resets all password expiration clocks.
4899      */
4900     private void updatePasswordExpirationsLocked(int userHandle) {
4901         ArraySet<Integer> affectedUserIds = new ArraySet<Integer>();
4902         List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(
4903                 userHandle, /* parent */ false);
4904         final int N = admins.size();
4905         for (int i = 0; i < N; i++) {
4906             ActiveAdmin admin = admins.get(i);
4907             if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) {
4908                 affectedUserIds.add(admin.getUserHandle().getIdentifier());
4909                 long timeout = admin.passwordExpirationTimeout;
4910                 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L;
4911                 admin.passwordExpirationDate = expiration;
4912             }
4913         }
4914         for (int affectedUserId : affectedUserIds) {
4915             saveSettingsLocked(affectedUserId);
4916         }
4917     }
4918
4919     @Override
4920     public void reportFailedPasswordAttempt(int userHandle) {
4921         enforceFullCrossUsersPermission(userHandle);
4922         if (!isSeparateProfileChallengeEnabled(userHandle)) {
4923             enforceNotManagedProfile(userHandle,
4924                     "report failed password attempt if separate profile challenge is not in place");
4925         }
4926         mContext.enforceCallingOrSelfPermission(
4927                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4928
4929         final long ident = mInjector.binderClearCallingIdentity();
4930         try {
4931             boolean wipeData = false;
4932             int identifier = 0;
4933             synchronized (this) {
4934                 DevicePolicyData policy = getUserData(userHandle);
4935                 policy.mFailedPasswordAttempts++;
4936                 saveSettingsLocked(userHandle);
4937                 if (mHasFeature) {
4938                     ActiveAdmin strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked(
4939                             userHandle, /* parent */ false);
4940                     int max = strictestAdmin != null
4941                             ? strictestAdmin.maximumFailedPasswordsForWipe : 0;
4942                     if (max > 0 && policy.mFailedPasswordAttempts >= max) {
4943                         // Wipe the user/profile associated with the policy that was violated. This
4944                         // is not necessarily calling user: if the policy that fired was from a
4945                         // managed profile rather than the main user profile, we wipe former only.
4946                         wipeData = true;
4947                         identifier = strictestAdmin.getUserHandle().getIdentifier();
4948                     }
4949
4950                     sendAdminCommandForLockscreenPoliciesLocked(
4951                             DeviceAdminReceiver.ACTION_PASSWORD_FAILED,
4952                             DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4953                 }
4954             }
4955             if (wipeData) {
4956                 // Call without holding lock.
4957                 wipeDeviceNoLock(false, identifier,
4958                         "reportFailedPasswordAttempt()");
4959             }
4960         } finally {
4961             mInjector.binderRestoreCallingIdentity(ident);
4962         }
4963
4964         if (mInjector.securityLogIsLoggingEnabled()) {
4965             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
4966                     /*method strength*/ 1);
4967         }
4968     }
4969
4970     @Override
4971     public void reportSuccessfulPasswordAttempt(int userHandle) {
4972         enforceFullCrossUsersPermission(userHandle);
4973         mContext.enforceCallingOrSelfPermission(
4974                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
4975
4976         synchronized (this) {
4977             DevicePolicyData policy = getUserData(userHandle);
4978             if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) {
4979                 long ident = mInjector.binderClearCallingIdentity();
4980                 try {
4981                     policy.mFailedPasswordAttempts = 0;
4982                     policy.mPasswordOwner = -1;
4983                     saveSettingsLocked(userHandle);
4984                     if (mHasFeature) {
4985                         sendAdminCommandForLockscreenPoliciesLocked(
4986                                 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED,
4987                                 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle);
4988                     }
4989                 } finally {
4990                     mInjector.binderRestoreCallingIdentity(ident);
4991                 }
4992             }
4993         }
4994
4995         if (mInjector.securityLogIsLoggingEnabled()) {
4996             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
4997                     /*method strength*/ 1);
4998         }
4999     }
5000
5001     @Override
5002     public void reportFailedFingerprintAttempt(int userHandle) {
5003         enforceFullCrossUsersPermission(userHandle);
5004         mContext.enforceCallingOrSelfPermission(
5005                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5006         if (mInjector.securityLogIsLoggingEnabled()) {
5007             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0,
5008                     /*method strength*/ 0);
5009         }
5010     }
5011
5012     @Override
5013     public void reportSuccessfulFingerprintAttempt(int userHandle) {
5014         enforceFullCrossUsersPermission(userHandle);
5015         mContext.enforceCallingOrSelfPermission(
5016                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5017         if (mInjector.securityLogIsLoggingEnabled()) {
5018             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1,
5019                     /*method strength*/ 0);
5020         }
5021     }
5022
5023     @Override
5024     public void reportKeyguardDismissed(int userHandle) {
5025         enforceFullCrossUsersPermission(userHandle);
5026         mContext.enforceCallingOrSelfPermission(
5027                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5028
5029         if (mInjector.securityLogIsLoggingEnabled()) {
5030             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED);
5031         }
5032     }
5033
5034     @Override
5035     public void reportKeyguardSecured(int userHandle) {
5036         enforceFullCrossUsersPermission(userHandle);
5037         mContext.enforceCallingOrSelfPermission(
5038                 android.Manifest.permission.BIND_DEVICE_ADMIN, null);
5039
5040         if (mInjector.securityLogIsLoggingEnabled()) {
5041             SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED);
5042         }
5043     }
5044
5045     @Override
5046     public ComponentName setGlobalProxy(ComponentName who, String proxySpec,
5047             String exclusionList) {
5048         if (!mHasFeature) {
5049             return null;
5050         }
5051         synchronized(this) {
5052             Preconditions.checkNotNull(who, "ComponentName is null");
5053
5054             // Only check if system user has set global proxy. We don't allow other users to set it.
5055             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5056             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5057                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
5058
5059             // Scan through active admins and find if anyone has already
5060             // set the global proxy.
5061             Set<ComponentName> compSet = policy.mAdminMap.keySet();
5062             for (ComponentName component : compSet) {
5063                 ActiveAdmin ap = policy.mAdminMap.get(component);
5064                 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) {
5065                     // Another admin already sets the global proxy
5066                     // Return it to the caller.
5067                     return component;
5068                 }
5069             }
5070
5071             // If the user is not system, don't set the global proxy. Fail silently.
5072             if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
5073                 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User "
5074                         + UserHandle.getCallingUserId() + " is not permitted.");
5075                 return null;
5076             }
5077             if (proxySpec == null) {
5078                 admin.specifiesGlobalProxy = false;
5079                 admin.globalProxySpec = null;
5080                 admin.globalProxyExclusionList = null;
5081             } else {
5082
5083                 admin.specifiesGlobalProxy = true;
5084                 admin.globalProxySpec = proxySpec;
5085                 admin.globalProxyExclusionList = exclusionList;
5086             }
5087
5088             // Reset the global proxy accordingly
5089             // Do this using system permissions, as apps cannot write to secure settings
5090             long origId = mInjector.binderClearCallingIdentity();
5091             try {
5092                 resetGlobalProxyLocked(policy);
5093             } finally {
5094                 mInjector.binderRestoreCallingIdentity(origId);
5095             }
5096             return null;
5097         }
5098     }
5099
5100     @Override
5101     public ComponentName getGlobalProxyAdmin(int userHandle) {
5102         if (!mHasFeature) {
5103             return null;
5104         }
5105         enforceFullCrossUsersPermission(userHandle);
5106         synchronized(this) {
5107             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5108             // Scan through active admins and find if anyone has already
5109             // set the global proxy.
5110             final int N = policy.mAdminList.size();
5111             for (int i = 0; i < N; i++) {
5112                 ActiveAdmin ap = policy.mAdminList.get(i);
5113                 if (ap.specifiesGlobalProxy) {
5114                     // Device admin sets the global proxy
5115                     // Return it to the caller.
5116                     return ap.info.getComponent();
5117                 }
5118             }
5119         }
5120         // No device admin sets the global proxy.
5121         return null;
5122     }
5123
5124     @Override
5125     public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) {
5126         synchronized (this) {
5127             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5128         }
5129         long token = mInjector.binderClearCallingIdentity();
5130         try {
5131             ConnectivityManager connectivityManager = (ConnectivityManager)
5132                     mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
5133             connectivityManager.setGlobalProxy(proxyInfo);
5134         } finally {
5135             mInjector.binderRestoreCallingIdentity(token);
5136         }
5137     }
5138
5139     private void resetGlobalProxyLocked(DevicePolicyData policy) {
5140         final int N = policy.mAdminList.size();
5141         for (int i = 0; i < N; i++) {
5142             ActiveAdmin ap = policy.mAdminList.get(i);
5143             if (ap.specifiesGlobalProxy) {
5144                 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList);
5145                 return;
5146             }
5147         }
5148         // No device admins defining global proxies - reset global proxy settings to none
5149         saveGlobalProxyLocked(null, null);
5150     }
5151
5152     private void saveGlobalProxyLocked(String proxySpec, String exclusionList) {
5153         if (exclusionList == null) {
5154             exclusionList = "";
5155         }
5156         if (proxySpec == null) {
5157             proxySpec = "";
5158         }
5159         // Remove white spaces
5160         proxySpec = proxySpec.trim();
5161         String data[] = proxySpec.split(":");
5162         int proxyPort = 8080;
5163         if (data.length > 1) {
5164             try {
5165                 proxyPort = Integer.parseInt(data[1]);
5166             } catch (NumberFormatException e) {}
5167         }
5168         exclusionList = exclusionList.trim();
5169
5170         ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList);
5171         if (!proxyProperties.isValid()) {
5172             Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString());
5173             return;
5174         }
5175         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]);
5176         mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort);
5177         mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
5178                 exclusionList);
5179     }
5180
5181     /**
5182      * Set the storage encryption request for a single admin.  Returns the new total request
5183      * status (for all admins).
5184      */
5185     @Override
5186     public int setStorageEncryption(ComponentName who, boolean encrypt) {
5187         if (!mHasFeature) {
5188             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5189         }
5190         Preconditions.checkNotNull(who, "ComponentName is null");
5191         final int userHandle = UserHandle.getCallingUserId();
5192         synchronized (this) {
5193             // Check for permissions
5194             // Only system user can set storage encryption
5195             if (userHandle != UserHandle.USER_SYSTEM) {
5196                 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User "
5197                         + UserHandle.getCallingUserId() + " is not permitted.");
5198                 return 0;
5199             }
5200
5201             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5202                     DeviceAdminInfo.USES_ENCRYPTED_STORAGE);
5203
5204             // Quick exit:  If the filesystem does not support encryption, we can exit early.
5205             if (!isEncryptionSupported()) {
5206                 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5207             }
5208
5209             // (1) Record the value for the admin so it's sticky
5210             if (ap.encryptionRequested != encrypt) {
5211                 ap.encryptionRequested = encrypt;
5212                 saveSettingsLocked(userHandle);
5213             }
5214
5215             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
5216             // (2) Compute "max" for all admins
5217             boolean newRequested = false;
5218             final int N = policy.mAdminList.size();
5219             for (int i = 0; i < N; i++) {
5220                 newRequested |= policy.mAdminList.get(i).encryptionRequested;
5221             }
5222
5223             // Notify OS of new request
5224             setEncryptionRequested(newRequested);
5225
5226             // Return the new global request status
5227             return newRequested
5228                     ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE
5229                     : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5230         }
5231     }
5232
5233     /**
5234      * Get the current storage encryption request status for a given admin, or aggregate of all
5235      * active admins.
5236      */
5237     @Override
5238     public boolean getStorageEncryption(ComponentName who, int userHandle) {
5239         if (!mHasFeature) {
5240             return false;
5241         }
5242         enforceFullCrossUsersPermission(userHandle);
5243         synchronized (this) {
5244             // Check for permissions if a particular caller is specified
5245             if (who != null) {
5246                 // When checking for a single caller, status is based on caller's request
5247                 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle);
5248                 return ap != null ? ap.encryptionRequested : false;
5249             }
5250
5251             // If no particular caller is specified, return the aggregate set of requests.
5252             // This is short circuited by returning true on the first hit.
5253             DevicePolicyData policy = getUserData(userHandle);
5254             final int N = policy.mAdminList.size();
5255             for (int i = 0; i < N; i++) {
5256                 if (policy.mAdminList.get(i).encryptionRequested) {
5257                     return true;
5258                 }
5259             }
5260             return false;
5261         }
5262     }
5263
5264     /**
5265      * Get the current encryption status of the device.
5266      */
5267     @Override
5268     public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) {
5269         if (!mHasFeature) {
5270             // Ok to return current status.
5271         }
5272         enforceFullCrossUsersPermission(userHandle);
5273
5274         // It's not critical here, but let's make sure the package name is correct, in case
5275         // we start using it for different purposes.
5276         ensureCallerPackage(callerPackage);
5277
5278         final ApplicationInfo ai;
5279         try {
5280             ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle);
5281         } catch (RemoteException e) {
5282             throw new SecurityException(e);
5283         }
5284
5285         boolean legacyApp = false;
5286         if (ai.targetSdkVersion <= Build.VERSION_CODES.M) {
5287             legacyApp = true;
5288         }
5289
5290         final int rawStatus = getEncryptionStatus();
5291         if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) {
5292             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5293         }
5294         return rawStatus;
5295     }
5296
5297     /**
5298      * Hook to low-levels:  This should report if the filesystem supports encrypted storage.
5299      */
5300     private boolean isEncryptionSupported() {
5301         // Note, this can be implemented as
5302         //   return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5303         // But is provided as a separate internal method if there's a faster way to do a
5304         // simple check for supported-or-not.
5305         return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5306     }
5307
5308     /**
5309      * Hook to low-levels:  Reporting the current status of encryption.
5310      * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED},
5311      * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE},
5312      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY},
5313      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or
5314      * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}.
5315      */
5316     private int getEncryptionStatus() {
5317         if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) {
5318             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER;
5319         } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) {
5320             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE;
5321         } else if (mInjector.storageManagerIsEncrypted()) {
5322             return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY;
5323         } else if (mInjector.storageManagerIsEncryptable()) {
5324             return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE;
5325         } else {
5326             return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED;
5327         }
5328     }
5329
5330     /**
5331      * Hook to low-levels:  If needed, record the new admin setting for encryption.
5332      */
5333     private void setEncryptionRequested(boolean encrypt) {
5334     }
5335
5336     /**
5337      * Set whether the screen capture is disabled for the user managed by the specified admin.
5338      */
5339     @Override
5340     public void setScreenCaptureDisabled(ComponentName who, boolean disabled) {
5341         if (!mHasFeature) {
5342             return;
5343         }
5344         Preconditions.checkNotNull(who, "ComponentName is null");
5345         final int userHandle = UserHandle.getCallingUserId();
5346         synchronized (this) {
5347             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5348                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
5349             if (ap.disableScreenCapture != disabled) {
5350                 ap.disableScreenCapture = disabled;
5351                 saveSettingsLocked(userHandle);
5352                 updateScreenCaptureDisabledInWindowManager(userHandle, disabled);
5353             }
5354         }
5355     }
5356
5357     /**
5358      * Returns whether or not screen capture is disabled for a given admin, or disabled for any
5359      * active admin (if given admin is null).
5360      */
5361     @Override
5362     public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) {
5363         if (!mHasFeature) {
5364             return false;
5365         }
5366         synchronized (this) {
5367             if (who != null) {
5368                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5369                 return (admin != null) ? admin.disableScreenCapture : false;
5370             }
5371
5372             DevicePolicyData policy = getUserData(userHandle);
5373             final int N = policy.mAdminList.size();
5374             for (int i = 0; i < N; i++) {
5375                 ActiveAdmin admin = policy.mAdminList.get(i);
5376                 if (admin.disableScreenCapture) {
5377                     return true;
5378                 }
5379             }
5380             return false;
5381         }
5382     }
5383
5384     private void updateScreenCaptureDisabledInWindowManager(final int userHandle,
5385             final boolean disabled) {
5386         mHandler.post(new Runnable() {
5387             @Override
5388             public void run() {
5389                 try {
5390                     mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled);
5391                 } catch (RemoteException e) {
5392                     Log.w(LOG_TAG, "Unable to notify WindowManager.", e);
5393                 }
5394             }
5395         });
5396     }
5397
5398     /**
5399      * Set whether auto time is required by the specified admin (must be device owner).
5400      */
5401     @Override
5402     public void setAutoTimeRequired(ComponentName who, boolean required) {
5403         if (!mHasFeature) {
5404             return;
5405         }
5406         Preconditions.checkNotNull(who, "ComponentName is null");
5407         final int userHandle = UserHandle.getCallingUserId();
5408         synchronized (this) {
5409             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5410                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5411             if (admin.requireAutoTime != required) {
5412                 admin.requireAutoTime = required;
5413                 saveSettingsLocked(userHandle);
5414             }
5415         }
5416
5417         // Turn AUTO_TIME on in settings if it is required
5418         if (required) {
5419             long ident = mInjector.binderClearCallingIdentity();
5420             try {
5421                 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */);
5422             } finally {
5423                 mInjector.binderRestoreCallingIdentity(ident);
5424             }
5425         }
5426     }
5427
5428     /**
5429      * Returns whether or not auto time is required by the device owner.
5430      */
5431     @Override
5432     public boolean getAutoTimeRequired() {
5433         if (!mHasFeature) {
5434             return false;
5435         }
5436         synchronized (this) {
5437             ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5438             return (deviceOwner != null) ? deviceOwner.requireAutoTime : false;
5439         }
5440     }
5441
5442     @Override
5443     public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) {
5444         if (!mHasFeature) {
5445             return;
5446         }
5447         Preconditions.checkNotNull(who, "ComponentName is null");
5448         // Allow setting this policy to true only if there is a split system user.
5449         if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) {
5450             throw new UnsupportedOperationException(
5451                     "Cannot force ephemeral users on systems without split system user.");
5452         }
5453         boolean removeAllUsers = false;
5454         synchronized (this) {
5455             final ActiveAdmin deviceOwner =
5456                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5457             if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) {
5458                 deviceOwner.forceEphemeralUsers = forceEphemeralUsers;
5459                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
5460                 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers);
5461                 removeAllUsers = forceEphemeralUsers;
5462             }
5463         }
5464         if (removeAllUsers) {
5465             long identitity = mInjector.binderClearCallingIdentity();
5466             try {
5467                 mUserManagerInternal.removeAllUsers();
5468             } finally {
5469                 mInjector.binderRestoreCallingIdentity(identitity);
5470             }
5471         }
5472     }
5473
5474     @Override
5475     public boolean getForceEphemeralUsers(ComponentName who) {
5476         if (!mHasFeature) {
5477             return false;
5478         }
5479         Preconditions.checkNotNull(who, "ComponentName is null");
5480         synchronized (this) {
5481             final ActiveAdmin deviceOwner =
5482                     getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5483             return deviceOwner.forceEphemeralUsers;
5484         }
5485     }
5486
5487     private boolean isDeviceOwnerManagedSingleUserDevice() {
5488         synchronized (this) {
5489             if (!mOwners.hasDeviceOwner()) {
5490                 return false;
5491             }
5492         }
5493         final long callingIdentity = mInjector.binderClearCallingIdentity();
5494         try {
5495             if (mInjector.userManagerIsSplitSystemUser()) {
5496                 // In split system user mode, only allow the case where the device owner is managing
5497                 // the only non-system user of the device
5498                 return (mUserManager.getUserCount() == 2
5499                         && mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM);
5500             } else  {
5501                 return mUserManager.getUserCount() == 1;
5502             }
5503         } finally {
5504             mInjector.binderRestoreCallingIdentity(callingIdentity);
5505         }
5506     }
5507
5508     private void ensureDeviceOwnerManagingSingleUser(ComponentName who) throws SecurityException {
5509         synchronized (this) {
5510             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5511         }
5512         if (!isDeviceOwnerManagedSingleUserDevice()) {
5513             throw new SecurityException(
5514                     "There should only be one user, managed by Device Owner");
5515         }
5516     }
5517
5518     @Override
5519     public boolean requestBugreport(ComponentName who) {
5520         if (!mHasFeature) {
5521             return false;
5522         }
5523         Preconditions.checkNotNull(who, "ComponentName is null");
5524         ensureDeviceOwnerManagingSingleUser(who);
5525
5526         if (mRemoteBugreportServiceIsActive.get()
5527                 || (getDeviceOwnerRemoteBugreportUri() != null)) {
5528             Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running.");
5529             return false;
5530         }
5531
5532         final long callingIdentity = mInjector.binderClearCallingIdentity();
5533         try {
5534             ActivityManagerNative.getDefault().requestBugReport(
5535                     ActivityManager.BUGREPORT_OPTION_REMOTE);
5536
5537             mRemoteBugreportServiceIsActive.set(true);
5538             mRemoteBugreportSharingAccepted.set(false);
5539             registerRemoteBugreportReceivers();
5540             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5541                     RemoteBugreportUtils.buildNotification(mContext,
5542                             DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL);
5543             mHandler.postDelayed(mRemoteBugreportTimeoutRunnable,
5544                     RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS);
5545             return true;
5546         } catch (RemoteException re) {
5547             // should never happen
5548             Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re);
5549             return false;
5550         } finally {
5551             mInjector.binderRestoreCallingIdentity(callingIdentity);
5552         }
5553     }
5554
5555     synchronized void sendDeviceOwnerCommand(String action, Bundle extras) {
5556         Intent intent = new Intent(action);
5557         intent.setComponent(mOwners.getDeviceOwnerComponent());
5558         if (extras != null) {
5559             intent.putExtras(extras);
5560         }
5561         mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5562     }
5563
5564     private synchronized String getDeviceOwnerRemoteBugreportUri() {
5565         return mOwners.getDeviceOwnerRemoteBugreportUri();
5566     }
5567
5568     private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri,
5569             String bugreportHash) {
5570         mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash);
5571     }
5572
5573     private void registerRemoteBugreportReceivers() {
5574         try {
5575             IntentFilter filterFinished = new IntentFilter(
5576                     DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH,
5577                     RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5578             mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished);
5579         } catch (IntentFilter.MalformedMimeTypeException e) {
5580             // should never happen, as setting a constant
5581             Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e);
5582         }
5583         IntentFilter filterConsent = new IntentFilter();
5584         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED);
5585         filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED);
5586         mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent);
5587     }
5588
5589     private void onBugreportFinished(Intent intent) {
5590         mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5591         mRemoteBugreportServiceIsActive.set(false);
5592         Uri bugreportUri = intent.getData();
5593         String bugreportUriString = null;
5594         if (bugreportUri != null) {
5595             bugreportUriString = bugreportUri.toString();
5596         }
5597         String bugreportHash = intent.getStringExtra(
5598                 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH);
5599         if (mRemoteBugreportSharingAccepted.get()) {
5600             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5601             mInjector.getNotificationManager().cancel(LOG_TAG,
5602                     RemoteBugreportUtils.NOTIFICATION_ID);
5603         } else {
5604             setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash);
5605             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5606                     RemoteBugreportUtils.buildNotification(mContext,
5607                             DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED),
5608                             UserHandle.ALL);
5609         }
5610         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5611     }
5612
5613     private void onBugreportFailed() {
5614         mRemoteBugreportServiceIsActive.set(false);
5615         mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5616                 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5617         mRemoteBugreportSharingAccepted.set(false);
5618         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5619         mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID);
5620         Bundle extras = new Bundle();
5621         extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5622                 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING);
5623         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5624         mContext.unregisterReceiver(mRemoteBugreportConsentReceiver);
5625         mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5626     }
5627
5628     private void onBugreportSharingAccepted() {
5629         mRemoteBugreportSharingAccepted.set(true);
5630         String bugreportUriString = null;
5631         String bugreportHash = null;
5632         synchronized (this) {
5633             bugreportUriString = getDeviceOwnerRemoteBugreportUri();
5634             bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash();
5635         }
5636         if (bugreportUriString != null) {
5637             shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash);
5638         } else if (mRemoteBugreportServiceIsActive.get()) {
5639             mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID,
5640                     RemoteBugreportUtils.buildNotification(mContext,
5641                             DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED),
5642                             UserHandle.ALL);
5643         }
5644     }
5645
5646     private void onBugreportSharingDeclined() {
5647         if (mRemoteBugreportServiceIsActive.get()) {
5648             mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP,
5649                     RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE);
5650             mRemoteBugreportServiceIsActive.set(false);
5651             mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable);
5652             mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver);
5653         }
5654         mRemoteBugreportSharingAccepted.set(false);
5655         setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5656         sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null);
5657     }
5658
5659     private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString,
5660             String bugreportHash) {
5661         ParcelFileDescriptor pfd = null;
5662         try {
5663             if (bugreportUriString == null) {
5664                 throw new FileNotFoundException();
5665             }
5666             Uri bugreportUri = Uri.parse(bugreportUriString);
5667             pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r");
5668
5669             synchronized (this) {
5670                 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE);
5671                 intent.setComponent(mOwners.getDeviceOwnerComponent());
5672                 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE);
5673                 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash);
5674                 mContext.grantUriPermission(mOwners.getDeviceOwnerComponent().getPackageName(),
5675                         bugreportUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5676                 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId()));
5677             }
5678         } catch (FileNotFoundException e) {
5679             Bundle extras = new Bundle();
5680             extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON,
5681                     DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE);
5682             sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras);
5683         } finally {
5684             try {
5685                 if (pfd != null) {
5686                     pfd.close();
5687                 }
5688             } catch (IOException ex) {
5689                 // Ignore
5690             }
5691             mRemoteBugreportSharingAccepted.set(false);
5692             setDeviceOwnerRemoteBugreportUriAndHash(null, null);
5693         }
5694     }
5695
5696     /**
5697      * Disables all device cameras according to the specified admin.
5698      */
5699     @Override
5700     public void setCameraDisabled(ComponentName who, boolean disabled) {
5701         if (!mHasFeature) {
5702             return;
5703         }
5704         Preconditions.checkNotNull(who, "ComponentName is null");
5705         final int userHandle = mInjector.userHandleGetCallingUserId();
5706         synchronized (this) {
5707             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
5708                     DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA);
5709             if (ap.disableCamera != disabled) {
5710                 ap.disableCamera = disabled;
5711                 saveSettingsLocked(userHandle);
5712             }
5713         }
5714         // Tell the user manager that the restrictions have changed.
5715         pushUserRestrictions(userHandle);
5716     }
5717
5718     /**
5719      * Gets whether or not all device cameras are disabled for a given admin, or disabled for any
5720      * active admins.
5721      */
5722     @Override
5723     public boolean getCameraDisabled(ComponentName who, int userHandle) {
5724         return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true);
5725     }
5726
5727     private boolean getCameraDisabled(ComponentName who, int userHandle,
5728             boolean mergeDeviceOwnerRestriction) {
5729         if (!mHasFeature) {
5730             return false;
5731         }
5732         synchronized (this) {
5733             if (who != null) {
5734                 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
5735                 return (admin != null) ? admin.disableCamera : false;
5736             }
5737             // First, see if DO has set it.  If so, it's device-wide.
5738             if (mergeDeviceOwnerRestriction) {
5739                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5740                 if (deviceOwner != null && deviceOwner.disableCamera) {
5741                     return true;
5742                 }
5743             }
5744
5745             // Then check each device admin on the user.
5746             DevicePolicyData policy = getUserData(userHandle);
5747             // Determine whether or not the device camera is disabled for any active admins.
5748             final int N = policy.mAdminList.size();
5749             for (int i = 0; i < N; i++) {
5750                 ActiveAdmin admin = policy.mAdminList.get(i);
5751                 if (admin.disableCamera) {
5752                     return true;
5753                 }
5754             }
5755             return false;
5756         }
5757     }
5758
5759     @Override
5760     public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) {
5761         if (!mHasFeature) {
5762             return;
5763         }
5764         Preconditions.checkNotNull(who, "ComponentName is null");
5765         final int userHandle = mInjector.userHandleGetCallingUserId();
5766         if (isManagedProfile(userHandle)) {
5767             if (parent) {
5768                 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER;
5769             } else {
5770                 which = which & PROFILE_KEYGUARD_FEATURES;
5771             }
5772         }
5773         synchronized (this) {
5774             ActiveAdmin ap = getActiveAdminForCallerLocked(
5775                     who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
5776             if (ap.disabledKeyguardFeatures != which) {
5777                 ap.disabledKeyguardFeatures = which;
5778                 saveSettingsLocked(userHandle);
5779             }
5780         }
5781     }
5782
5783     /**
5784      * Gets the disabled state for features in keyguard for the given admin,
5785      * or the aggregate of all active admins if who is null.
5786      */
5787     @Override
5788     public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) {
5789         if (!mHasFeature) {
5790             return 0;
5791         }
5792         enforceFullCrossUsersPermission(userHandle);
5793         final long ident = mInjector.binderClearCallingIdentity();
5794         try {
5795             synchronized (this) {
5796                 if (who != null) {
5797                     ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent);
5798                     return (admin != null) ? admin.disabledKeyguardFeatures : 0;
5799                 }
5800
5801                 final List<ActiveAdmin> admins;
5802                 if (!parent && isManagedProfile(userHandle)) {
5803                     // If we are being asked about a managed profile, just return keyguard features
5804                     // disabled by admins in the profile.
5805                     admins = getUserDataUnchecked(userHandle).mAdminList;
5806                 } else {
5807                     // Otherwise return those set by admins in the user and its profiles.
5808                     admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
5809                 }
5810
5811                 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE;
5812                 final int N = admins.size();
5813                 for (int i = 0; i < N; i++) {
5814                     ActiveAdmin admin = admins.get(i);
5815                     int userId = admin.getUserHandle().getIdentifier();
5816                     boolean isRequestedUser = !parent && (userId == userHandle);
5817                     if (isRequestedUser || !isManagedProfile(userId)) {
5818                         // If we are being asked explicitly about this user
5819                         // return all disabled features even if its a managed profile.
5820                         which |= admin.disabledKeyguardFeatures;
5821                     } else {
5822                         // Otherwise a managed profile is only allowed to disable
5823                         // some features on the parent user.
5824                         which |= (admin.disabledKeyguardFeatures
5825                                 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER);
5826                     }
5827                 }
5828                 return which;
5829             }
5830         } finally {
5831             mInjector.binderRestoreCallingIdentity(ident);
5832         }
5833     }
5834
5835     @Override
5836     public void setKeepUninstalledPackages(ComponentName who, List<String> packageList) {
5837         if (!mHasFeature) {
5838             return;
5839         }
5840         Preconditions.checkNotNull(who, "ComponentName is null");
5841         Preconditions.checkNotNull(packageList, "packageList is null");
5842         final int userHandle = UserHandle.getCallingUserId();
5843         synchronized (this) {
5844             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
5845                     DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5846             admin.keepUninstalledPackages = packageList;
5847             saveSettingsLocked(userHandle);
5848             mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList);
5849         }
5850     }
5851
5852     @Override
5853     public List<String> getKeepUninstalledPackages(ComponentName who) {
5854         Preconditions.checkNotNull(who, "ComponentName is null");
5855         if (!mHasFeature) {
5856             return null;
5857         }
5858         // TODO In split system user mode, allow apps on user 0 to query the list
5859         synchronized (this) {
5860             // Check if this is the device owner who is calling
5861             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
5862             return getKeepUninstalledPackagesLocked();
5863         }
5864     }
5865
5866     private List<String> getKeepUninstalledPackagesLocked() {
5867         ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
5868         return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null;
5869     }
5870
5871     @Override
5872     public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) {
5873         if (!mHasFeature) {
5874             return false;
5875         }
5876         if (admin == null
5877                 || !isPackageInstalledForUser(admin.getPackageName(), userId)) {
5878             throw new IllegalArgumentException("Invalid component " + admin
5879                     + " for device owner");
5880         }
5881         synchronized (this) {
5882             enforceCanSetDeviceOwnerLocked(admin, userId);
5883             if (getActiveAdminUncheckedLocked(admin, userId) == null
5884                     || getUserData(userId).mRemovingAdmins.contains(admin)) {
5885                 throw new IllegalArgumentException("Not active admin: " + admin);
5886             }
5887
5888             // Shutting down backup manager service permanently.
5889             long ident = mInjector.binderClearCallingIdentity();
5890             try {
5891                 if (mInjector.getIBackupManager() != null) {
5892                     mInjector.getIBackupManager()
5893                             .setBackupServiceActive(UserHandle.USER_SYSTEM, false);
5894                 }
5895             } catch (RemoteException e) {
5896                 throw new IllegalStateException("Failed deactivating backup service.", e);
5897             } finally {
5898                 mInjector.binderRestoreCallingIdentity(ident);
5899             }
5900
5901             mOwners.setDeviceOwner(admin, ownerName, userId);
5902             mOwners.writeDeviceOwner();
5903             updateDeviceOwnerLocked();
5904             setDeviceOwnerSystemPropertyLocked();
5905             Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED);
5906
5907             ident = mInjector.binderClearCallingIdentity();
5908             try {
5909                 // TODO Send to system too?
5910                 mContext.sendBroadcastAsUser(intent, new UserHandle(userId));
5911             } finally {
5912                 mInjector.binderRestoreCallingIdentity(ident);
5913             }
5914             Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId);
5915             return true;
5916         }
5917     }
5918
5919     public boolean isDeviceOwner(ComponentName who, int userId) {
5920         synchronized (this) {
5921             return mOwners.hasDeviceOwner()
5922                     && mOwners.getDeviceOwnerUserId() == userId
5923                     && mOwners.getDeviceOwnerComponent().equals(who);
5924         }
5925     }
5926
5927     public boolean isProfileOwner(ComponentName who, int userId) {
5928         final ComponentName profileOwner = getProfileOwner(userId);
5929         return who != null && who.equals(profileOwner);
5930     }
5931
5932     @Override
5933     public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) {
5934         if (!mHasFeature) {
5935             return null;
5936         }
5937         if (!callingUserOnly) {
5938             enforceManageUsers();
5939         }
5940         synchronized (this) {
5941             if (!mOwners.hasDeviceOwner()) {
5942                 return null;
5943             }
5944             if (callingUserOnly && mInjector.userHandleGetCallingUserId() !=
5945                     mOwners.getDeviceOwnerUserId()) {
5946                 return null;
5947             }
5948             return mOwners.getDeviceOwnerComponent();
5949         }
5950     }
5951
5952     @Override
5953     public int getDeviceOwnerUserId() {
5954         if (!mHasFeature) {
5955             return UserHandle.USER_NULL;
5956         }
5957         enforceManageUsers();
5958         synchronized (this) {
5959             return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL;
5960         }
5961     }
5962
5963     /**
5964      * Returns the "name" of the device owner.  It'll work for non-DO users too, but requires
5965      * MANAGE_USERS.
5966      */
5967     @Override
5968     public String getDeviceOwnerName() {
5969         if (!mHasFeature) {
5970             return null;
5971         }
5972         enforceManageUsers();
5973         synchronized (this) {
5974             if (!mOwners.hasDeviceOwner()) {
5975                 return null;
5976             }
5977             // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292)
5978             // Should setDeviceOwner/ProfileOwner still take a name?
5979             String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName();
5980             return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM);
5981         }
5982     }
5983
5984     // Returns the active device owner or null if there is no device owner.
5985     @VisibleForTesting
5986     ActiveAdmin getDeviceOwnerAdminLocked() {
5987         ComponentName component = mOwners.getDeviceOwnerComponent();
5988         if (component == null) {
5989             return null;
5990         }
5991
5992         DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId());
5993         final int n = policy.mAdminList.size();
5994         for (int i = 0; i < n; i++) {
5995             ActiveAdmin admin = policy.mAdminList.get(i);
5996             if (component.equals(admin.info.getComponent())) {
5997                 return admin;
5998             }
5999         }
6000         Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component);
6001         return null;
6002     }
6003
6004     @Override
6005     public void clearDeviceOwner(String packageName) {
6006         Preconditions.checkNotNull(packageName, "packageName is null");
6007         final int callingUid = mInjector.binderGetCallingUid();
6008         try {
6009             int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
6010                     UserHandle.getUserId(callingUid));
6011             if (uid != callingUid) {
6012                 throw new SecurityException("Invalid packageName");
6013             }
6014         } catch (NameNotFoundException e) {
6015             throw new SecurityException(e);
6016         }
6017         synchronized (this) {
6018             final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent();
6019             final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId();
6020             if (!mOwners.hasDeviceOwner()
6021                     || !deviceOwnerComponent.getPackageName().equals(packageName)
6022                     || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) {
6023                 throw new SecurityException(
6024                         "clearDeviceOwner can only be called by the device owner");
6025             }
6026             enforceUserUnlocked(deviceOwnerUserId);
6027
6028             final ActiveAdmin admin = getDeviceOwnerAdminLocked();
6029             long ident = mInjector.binderClearCallingIdentity();
6030             try {
6031                 clearDeviceOwnerLocked(admin, deviceOwnerUserId);
6032                 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId);
6033             } finally {
6034                 mInjector.binderRestoreCallingIdentity(ident);
6035             }
6036             Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent);
6037         }
6038     }
6039
6040     private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) {
6041         if (admin != null) {
6042             admin.disableCamera = false;
6043             admin.userRestrictions = null;
6044             admin.forceEphemeralUsers = false;
6045             mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers);
6046         }
6047         clearUserPoliciesLocked(userId);
6048
6049         mOwners.clearDeviceOwner();
6050         mOwners.writeDeviceOwner();
6051         updateDeviceOwnerLocked();
6052         disableDeviceOwnerManagedSingleUserFeaturesIfNeeded();
6053         try {
6054             if (mInjector.getIBackupManager() != null) {
6055                 // Reactivate backup service.
6056                 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true);
6057             }
6058         } catch (RemoteException e) {
6059             throw new IllegalStateException("Failed reactivating backup service.", e);
6060         }
6061     }
6062
6063     @Override
6064     public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) {
6065         if (!mHasFeature) {
6066             return false;
6067         }
6068         if (who == null
6069                 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) {
6070             throw new IllegalArgumentException("Component " + who
6071                     + " not installed for userId:" + userHandle);
6072         }
6073         synchronized (this) {
6074             enforceCanSetProfileOwnerLocked(who, userHandle);
6075
6076             if (getActiveAdminUncheckedLocked(who, userHandle) == null
6077                     || getUserData(userHandle).mRemovingAdmins.contains(who)) {
6078                 throw new IllegalArgumentException("Not active admin: " + who);
6079             }
6080
6081             mOwners.setProfileOwner(who, ownerName, userHandle);
6082             mOwners.writeProfileOwner(userHandle);
6083             Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle);
6084             return true;
6085         }
6086     }
6087
6088     @Override
6089     public void clearProfileOwner(ComponentName who) {
6090         if (!mHasFeature) {
6091             return;
6092         }
6093         final UserHandle callingUser = mInjector.binderGetCallingUserHandle();
6094         final int userId = callingUser.getIdentifier();
6095         enforceNotManagedProfile(userId, "clear profile owner");
6096         enforceUserUnlocked(userId);
6097         // Check if this is the profile owner who is calling
6098         final ActiveAdmin admin =
6099                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6100         synchronized (this) {
6101             final long ident = mInjector.binderClearCallingIdentity();
6102             try {
6103                 clearProfileOwnerLocked(admin, userId);
6104                 removeActiveAdminLocked(who, userId);
6105             } finally {
6106                 mInjector.binderRestoreCallingIdentity(ident);
6107             }
6108             Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId);
6109         }
6110     }
6111
6112     public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) {
6113         if (admin != null) {
6114             admin.disableCamera = false;
6115             admin.userRestrictions = null;
6116         }
6117         clearUserPoliciesLocked(userId);
6118         mOwners.removeProfileOwner(userId);
6119         mOwners.writeProfileOwner(userId);
6120     }
6121
6122     @Override
6123     public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) {
6124         Preconditions.checkNotNull(who, "ComponentName is null");
6125         if (!mHasFeature) {
6126             return;
6127         }
6128
6129         synchronized (this) {
6130             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
6131             long token = mInjector.binderClearCallingIdentity();
6132             try {
6133                 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null);
6134             } finally {
6135                 mInjector.binderRestoreCallingIdentity(token);
6136             }
6137         }
6138     }
6139
6140     @Override
6141     public CharSequence getDeviceOwnerLockScreenInfo() {
6142         return mLockPatternUtils.getDeviceOwnerInfo();
6143     }
6144
6145     private void clearUserPoliciesLocked(int userId) {
6146         // Reset some of the user-specific policies
6147         DevicePolicyData policy = getUserData(userId);
6148         policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT;
6149         policy.mDelegatedCertInstallerPackage = null;
6150         policy.mApplicationRestrictionsManagingPackage = null;
6151         policy.mStatusBarDisabled = false;
6152         policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED;
6153         saveSettingsLocked(userId);
6154
6155         try {
6156             mIPackageManager.updatePermissionFlagsForAllApps(
6157                     PackageManager.FLAG_PERMISSION_POLICY_FIXED,
6158                     0  /* flagValues */, userId);
6159             pushUserRestrictions(userId);
6160         } catch (RemoteException re) {
6161             // Shouldn't happen.
6162         }
6163     }
6164
6165     @Override
6166     public boolean hasUserSetupCompleted() {
6167         return hasUserSetupCompleted(UserHandle.getCallingUserId());
6168     }
6169
6170     // This checks only if the Setup Wizard has run.  Since Wear devices pair before
6171     // completing Setup Wizard, and pairing involves transferring user data, calling
6172     // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted().
6173     private boolean hasUserSetupCompleted(int userHandle) {
6174         if (!mHasFeature) {
6175             return true;
6176         }
6177         return getUserData(userHandle).mUserSetupComplete;
6178     }
6179
6180     private boolean hasPaired(int userHandle) {
6181         if (!mHasFeature) {
6182             return true;
6183         }
6184         return getUserData(userHandle).mPaired;
6185     }
6186
6187     @Override
6188     public int getUserProvisioningState() {
6189         if (!mHasFeature) {
6190             return DevicePolicyManager.STATE_USER_UNMANAGED;
6191         }
6192         int userHandle = mInjector.userHandleGetCallingUserId();
6193         return getUserProvisioningState(userHandle);
6194     }
6195
6196     private int getUserProvisioningState(int userHandle) {
6197         return getUserData(userHandle).mUserProvisioningState;
6198     }
6199
6200     @Override
6201     public void setUserProvisioningState(int newState, int userHandle) {
6202         if (!mHasFeature) {
6203             return;
6204         }
6205
6206         if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle)
6207                 && getManagedUserId(userHandle) == -1) {
6208             // No managed device, user or profile, so setting provisioning state makes no sense.
6209             throw new IllegalStateException("Not allowed to change provisioning state unless a "
6210                       + "device or profile owner is set.");
6211         }
6212
6213         synchronized (this) {
6214             boolean transitionCheckNeeded = true;
6215
6216             // Calling identity/permission checks.
6217             final int callingUid = mInjector.binderGetCallingUid();
6218             if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6219                 // ADB shell can only move directly from un-managed to finalized as part of directly
6220                 // setting profile-owner or device-owner.
6221                 if (getUserProvisioningState(userHandle) !=
6222                         DevicePolicyManager.STATE_USER_UNMANAGED
6223                         || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6224                     throw new IllegalStateException("Not allowed to change provisioning state "
6225                             + "unless current provisioning state is unmanaged, and new state is "
6226                             + "finalized.");
6227                 }
6228                 transitionCheckNeeded = false;
6229             } else {
6230                 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS.
6231                 enforceCanManageProfileAndDeviceOwners();
6232             }
6233
6234             final DevicePolicyData policyData = getUserData(userHandle);
6235             if (transitionCheckNeeded) {
6236                 // Optional state transition check for non-ADB case.
6237                 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState);
6238             }
6239             policyData.mUserProvisioningState = newState;
6240             saveSettingsLocked(userHandle);
6241         }
6242     }
6243
6244     private void checkUserProvisioningStateTransition(int currentState, int newState) {
6245         // Valid transitions for normal use-cases.
6246         switch (currentState) {
6247             case DevicePolicyManager.STATE_USER_UNMANAGED:
6248                 // Can move to any state from unmanaged (except itself as an edge case)..
6249                 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) {
6250                     return;
6251                 }
6252                 break;
6253             case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE:
6254             case DevicePolicyManager.STATE_USER_SETUP_COMPLETE:
6255                 // Can only move to finalized from these states.
6256                 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) {
6257                     return;
6258                 }
6259                 break;
6260             case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE:
6261                 // Current user has a managed-profile, but current user is not managed, so
6262                 // rather than moving to finalized state, go back to unmanaged once
6263                 // profile provisioning is complete.
6264                 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) {
6265                     return;
6266                 }
6267                 break;
6268             case DevicePolicyManager.STATE_USER_SETUP_FINALIZED:
6269                 // Cannot transition out of finalized.
6270                 break;
6271         }
6272
6273         // Didn't meet any of the accepted state transition checks above, throw appropriate error.
6274         throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] "
6275                 + "from state [" + currentState + "]");
6276     }
6277
6278     @Override
6279     public void setProfileEnabled(ComponentName who) {
6280         if (!mHasFeature) {
6281             return;
6282         }
6283         Preconditions.checkNotNull(who, "ComponentName is null");
6284         synchronized (this) {
6285             // Check if this is the profile owner who is calling
6286             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6287             final int userId = UserHandle.getCallingUserId();
6288             enforceManagedProfile(userId, "enable the profile");
6289
6290             long id = mInjector.binderClearCallingIdentity();
6291             try {
6292                 mUserManager.setUserEnabled(userId);
6293                 UserInfo parent = mUserManager.getProfileParent(userId);
6294                 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED);
6295                 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId));
6296                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY |
6297                         Intent.FLAG_RECEIVER_FOREGROUND);
6298                 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id));
6299             } finally {
6300                 mInjector.binderRestoreCallingIdentity(id);
6301             }
6302         }
6303     }
6304
6305     @Override
6306     public void setProfileName(ComponentName who, String profileName) {
6307         Preconditions.checkNotNull(who, "ComponentName is null");
6308         int userId = UserHandle.getCallingUserId();
6309         // Check if this is the profile owner (includes device owner).
6310         getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6311
6312         long id = mInjector.binderClearCallingIdentity();
6313         try {
6314             mUserManager.setUserName(userId, profileName);
6315         } finally {
6316             mInjector.binderRestoreCallingIdentity(id);
6317         }
6318     }
6319
6320     @Override
6321     public ComponentName getProfileOwner(int userHandle) {
6322         if (!mHasFeature) {
6323             return null;
6324         }
6325
6326         synchronized (this) {
6327             return mOwners.getProfileOwnerComponent(userHandle);
6328         }
6329     }
6330
6331     // Returns the active profile owner for this user or null if the current user has no
6332     // profile owner.
6333     @VisibleForTesting
6334     ActiveAdmin getProfileOwnerAdminLocked(int userHandle) {
6335         ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle);
6336         if (profileOwner == null) {
6337             return null;
6338         }
6339         DevicePolicyData policy = getUserData(userHandle);
6340         final int n = policy.mAdminList.size();
6341         for (int i = 0; i < n; i++) {
6342             ActiveAdmin admin = policy.mAdminList.get(i);
6343             if (profileOwner.equals(admin.info.getComponent())) {
6344                 return admin;
6345             }
6346         }
6347         return null;
6348     }
6349
6350     @Override
6351     public String getProfileOwnerName(int userHandle) {
6352         if (!mHasFeature) {
6353             return null;
6354         }
6355         enforceManageUsers();
6356         ComponentName profileOwner = getProfileOwner(userHandle);
6357         if (profileOwner == null) {
6358             return null;
6359         }
6360         return getApplicationLabel(profileOwner.getPackageName(), userHandle);
6361     }
6362
6363     /**
6364      * Canonical name for a given package.
6365      */
6366     private String getApplicationLabel(String packageName, int userHandle) {
6367         long token = mInjector.binderClearCallingIdentity();
6368         try {
6369             final Context userContext;
6370             try {
6371                 UserHandle handle = new UserHandle(userHandle);
6372                 userContext = mContext.createPackageContextAsUser(packageName, 0, handle);
6373             } catch (PackageManager.NameNotFoundException nnfe) {
6374                 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe);
6375                 return null;
6376             }
6377             ApplicationInfo appInfo = userContext.getApplicationInfo();
6378             CharSequence result = null;
6379             if (appInfo != null) {
6380                 PackageManager pm = userContext.getPackageManager();
6381                 result = pm.getApplicationLabel(appInfo);
6382             }
6383             return result != null ? result.toString() : null;
6384         } finally {
6385             mInjector.binderRestoreCallingIdentity(token);
6386         }
6387     }
6388
6389     /**
6390      * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6391      * permission.
6392      * The profile owner can only be set before the user setup phase has completed,
6393      * except for:
6394      * - SYSTEM_UID
6395      * - adb if there are no accounts. (But see {@link #hasIncompatibleAccountsLocked})
6396      */
6397     private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle) {
6398         UserInfo info = getUserInfo(userHandle);
6399         if (info == null) {
6400             // User doesn't exist.
6401             throw new IllegalArgumentException(
6402                     "Attempted to set profile owner for invalid userId: " + userHandle);
6403         }
6404         if (info.isGuest()) {
6405             throw new IllegalStateException("Cannot set a profile owner on a guest");
6406         }
6407         if (mOwners.hasProfileOwner(userHandle)) {
6408             throw new IllegalStateException("Trying to set the profile owner, but profile owner "
6409                     + "is already set.");
6410         }
6411         if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) {
6412             throw new IllegalStateException("Trying to set the profile owner, but the user "
6413                     + "already has a device owner.");
6414         }
6415         int callingUid = mInjector.binderGetCallingUid();
6416         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID) {
6417             if ((mIsWatch || hasUserSetupCompleted(userHandle))
6418                     && hasIncompatibleAccountsLocked(userHandle, owner)) {
6419                 throw new IllegalStateException("Not allowed to set the profile owner because "
6420                         + "there are already some accounts on the profile");
6421             }
6422             return;
6423         }
6424         enforceCanManageProfileAndDeviceOwners();
6425         if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) {
6426             throw new IllegalStateException("Cannot set the profile owner on a user which is "
6427                     + "already set-up");
6428         }
6429     }
6430
6431     /**
6432      * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS
6433      * permission.
6434      */
6435     private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId) {
6436         int callingUid = mInjector.binderGetCallingUid();
6437         boolean isAdb = callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID;
6438         if (!isAdb) {
6439             enforceCanManageProfileAndDeviceOwners();
6440         }
6441
6442         final int code = checkSetDeviceOwnerPreConditionLocked(owner, userId, isAdb);
6443         switch (code) {
6444             case CODE_OK:
6445                 return;
6446             case CODE_HAS_DEVICE_OWNER:
6447                 throw new IllegalStateException(
6448                         "Trying to set the device owner, but device owner is already set.");
6449             case CODE_USER_HAS_PROFILE_OWNER:
6450                 throw new IllegalStateException("Trying to set the device owner, but the user "
6451                         + "already has a profile owner.");
6452             case CODE_USER_NOT_RUNNING:
6453                 throw new IllegalStateException("User not running: " + userId);
6454             case CODE_NOT_SYSTEM_USER:
6455                 throw new IllegalStateException("User is not system user");
6456             case CODE_USER_SETUP_COMPLETED:
6457                 throw new IllegalStateException(
6458                         "Cannot set the device owner if the device is already set-up");
6459             case CODE_NONSYSTEM_USER_EXISTS:
6460                 throw new IllegalStateException("Not allowed to set the device owner because there "
6461                         + "are already several users on the device");
6462             case CODE_ACCOUNTS_NOT_EMPTY:
6463                 throw new IllegalStateException("Not allowed to set the device owner because there "
6464                         + "are already some accounts on the device");
6465             case CODE_HAS_PAIRED:
6466                 throw new IllegalStateException("Not allowed to set the device owner because this "
6467                         + "device has already paired");
6468             default:
6469                 throw new IllegalStateException("Unknown @DeviceOwnerPreConditionCode " + code);
6470         }
6471     }
6472
6473     private void enforceUserUnlocked(int userId) {
6474         // Since we're doing this operation on behalf of an app, we only
6475         // want to use the actual "unlocked" state.
6476         Preconditions.checkState(mUserManager.isUserUnlocked(userId),
6477                 "User must be running and unlocked");
6478     }
6479
6480     private void enforceUserUnlocked(int userId, boolean parent) {
6481         if (parent) {
6482             enforceUserUnlocked(getProfileParentId(userId));
6483         } else {
6484             enforceUserUnlocked(userId);
6485         }
6486     }
6487
6488     private void enforceManageUsers() {
6489         final int callingUid = mInjector.binderGetCallingUid();
6490         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6491             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
6492         }
6493     }
6494
6495     private void enforceFullCrossUsersPermission(int userHandle) {
6496         enforceSystemUserOrPermission(userHandle,
6497                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
6498     }
6499
6500     private void enforceCrossUsersPermission(int userHandle) {
6501         enforceSystemUserOrPermission(userHandle,
6502                 android.Manifest.permission.INTERACT_ACROSS_USERS);
6503     }
6504
6505     private void enforceSystemUserOrPermission(int userHandle, String permission) {
6506         if (userHandle < 0) {
6507             throw new IllegalArgumentException("Invalid userId " + userHandle);
6508         }
6509         final int callingUid = mInjector.binderGetCallingUid();
6510         if (userHandle == UserHandle.getUserId(callingUid)) {
6511             return;
6512         }
6513         if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) {
6514             mContext.enforceCallingOrSelfPermission(permission,
6515                     "Must be system or have " + permission + " permission");
6516         }
6517     }
6518
6519     private void enforceManagedProfile(int userHandle, String message) {
6520         if(!isManagedProfile(userHandle)) {
6521             throw new SecurityException("You can not " + message + " outside a managed profile.");
6522         }
6523     }
6524
6525     private void enforceNotManagedProfile(int userHandle, String message) {
6526         if(isManagedProfile(userHandle)) {
6527             throw new SecurityException("You can not " + message + " for a managed profile.");
6528         }
6529     }
6530
6531     private void ensureCallerPackage(@Nullable String packageName) {
6532         if (packageName == null) {
6533             Preconditions.checkState(isCallerWithSystemUid(),
6534                     "Only caller can omit package name");
6535         } else {
6536             final int callingUid = mInjector.binderGetCallingUid();
6537             final int userId = mInjector.userHandleGetCallingUserId();
6538             try {
6539                 final ApplicationInfo ai = mIPackageManager.getApplicationInfo(
6540                         packageName, 0, userId);
6541                 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name");
6542             } catch (RemoteException e) {
6543                 // Shouldn't happen
6544             }
6545         }
6546     }
6547
6548     private boolean isCallerWithSystemUid() {
6549         return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID);
6550     }
6551
6552     private int getProfileParentId(int userHandle) {
6553         final long ident = mInjector.binderClearCallingIdentity();
6554         try {
6555             UserInfo parentUser = mUserManager.getProfileParent(userHandle);
6556             return parentUser != null ? parentUser.id : userHandle;
6557         } finally {
6558             mInjector.binderRestoreCallingIdentity(ident);
6559         }
6560     }
6561
6562     private int getCredentialOwner(int userHandle, boolean parent) {
6563         final long ident = mInjector.binderClearCallingIdentity();
6564         try {
6565             if (parent) {
6566                 UserInfo parentProfile = mUserManager.getProfileParent(userHandle);
6567                 if (parentProfile != null) {
6568                     userHandle = parentProfile.id;
6569                 }
6570             }
6571             return mUserManager.getCredentialOwnerProfile(userHandle);
6572         } finally {
6573             mInjector.binderRestoreCallingIdentity(ident);
6574         }
6575     }
6576
6577     private boolean isManagedProfile(int userHandle) {
6578         return getUserInfo(userHandle).isManagedProfile();
6579     }
6580
6581     private void enableIfNecessary(String packageName, int userId) {
6582         try {
6583             ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName,
6584                     PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS,
6585                     userId);
6586             if (ai.enabledSetting
6587                     == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
6588                 mIPackageManager.setApplicationEnabledSetting(packageName,
6589                         PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
6590                         PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager");
6591             }
6592         } catch (RemoteException e) {
6593         }
6594     }
6595
6596     @Override
6597     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6598         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6599                 != PackageManager.PERMISSION_GRANTED) {
6600
6601             pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid="
6602                     + mInjector.binderGetCallingPid()
6603                     + ", uid=" + mInjector.binderGetCallingUid());
6604             return;
6605         }
6606
6607         synchronized (this) {
6608             pw.println("Current Device Policy Manager state:");
6609             mOwners.dump("  ", pw);
6610             int userCount = mUserData.size();
6611             for (int u = 0; u < userCount; u++) {
6612                 DevicePolicyData policy = getUserData(mUserData.keyAt(u));
6613                 pw.println();
6614                 pw.println("  Enabled Device Admins (User " + policy.mUserHandle
6615                         + ", provisioningState: " + policy.mUserProvisioningState + "):");
6616                 final int N = policy.mAdminList.size();
6617                 for (int i=0; i<N; i++) {
6618                     ActiveAdmin ap = policy.mAdminList.get(i);
6619                     if (ap != null) {
6620                         pw.print("    "); pw.print(ap.info.getComponent().flattenToShortString());
6621                                 pw.println(":");
6622                         ap.dump("      ", pw);
6623                     }
6624                 }
6625                 if (!policy.mRemovingAdmins.isEmpty()) {
6626                     pw.println("    Removing Device Admins (User " + policy.mUserHandle + "): "
6627                             + policy.mRemovingAdmins);
6628                 }
6629
6630                 pw.println(" ");
6631                 pw.print("    mPasswordOwner="); pw.println(policy.mPasswordOwner);
6632             }
6633             pw.println();
6634             pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus()));
6635         }
6636     }
6637
6638     private String getEncryptionStatusName(int encryptionStatus) {
6639         switch (encryptionStatus) {
6640             case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE:
6641                 return "inactive";
6642             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY:
6643                 return "block default key";
6644             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE:
6645                 return "block";
6646             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER:
6647                 return "per-user";
6648             case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED:
6649                 return "unsupported";
6650             case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING:
6651                 return "activating";
6652             default:
6653                 return "unknown";
6654         }
6655     }
6656
6657     @Override
6658     public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter,
6659             ComponentName activity) {
6660         Preconditions.checkNotNull(who, "ComponentName is null");
6661         final int userHandle = UserHandle.getCallingUserId();
6662         synchronized (this) {
6663             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6664
6665             long id = mInjector.binderClearCallingIdentity();
6666             try {
6667                 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle);
6668             } catch (RemoteException re) {
6669                 // Shouldn't happen
6670             } finally {
6671                 mInjector.binderRestoreCallingIdentity(id);
6672             }
6673         }
6674     }
6675
6676     @Override
6677     public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) {
6678         Preconditions.checkNotNull(who, "ComponentName is null");
6679         final int userHandle = UserHandle.getCallingUserId();
6680         synchronized (this) {
6681             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6682
6683             long id = mInjector.binderClearCallingIdentity();
6684             try {
6685                 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle);
6686             } catch (RemoteException re) {
6687                 // Shouldn't happen
6688             } finally {
6689                 mInjector.binderRestoreCallingIdentity(id);
6690             }
6691         }
6692     }
6693
6694     @Override
6695     public boolean setApplicationRestrictionsManagingPackage(ComponentName admin,
6696             String packageName) {
6697         Preconditions.checkNotNull(admin, "ComponentName is null");
6698
6699         final int userHandle = mInjector.userHandleGetCallingUserId();
6700         synchronized (this) {
6701             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6702             if (packageName != null && !isPackageInstalledForUser(packageName, userHandle)) {
6703                 return false;
6704             }
6705             DevicePolicyData policy = getUserData(userHandle);
6706             policy.mApplicationRestrictionsManagingPackage = packageName;
6707             saveSettingsLocked(userHandle);
6708             return true;
6709         }
6710     }
6711
6712     @Override
6713     public String getApplicationRestrictionsManagingPackage(ComponentName admin) {
6714         Preconditions.checkNotNull(admin, "ComponentName is null");
6715
6716         final int userHandle = mInjector.userHandleGetCallingUserId();
6717         synchronized (this) {
6718             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6719             DevicePolicyData policy = getUserData(userHandle);
6720             return policy.mApplicationRestrictionsManagingPackage;
6721         }
6722     }
6723
6724     @Override
6725     public boolean isCallerApplicationRestrictionsManagingPackage() {
6726         final int callingUid = mInjector.binderGetCallingUid();
6727         final int userHandle = UserHandle.getUserId(callingUid);
6728         synchronized (this) {
6729             final DevicePolicyData policy = getUserData(userHandle);
6730             if (policy.mApplicationRestrictionsManagingPackage == null) {
6731                 return false;
6732             }
6733
6734             try {
6735                 int uid = mContext.getPackageManager().getPackageUidAsUser(
6736                         policy.mApplicationRestrictionsManagingPackage, userHandle);
6737                 return uid == callingUid;
6738             } catch (NameNotFoundException e) {
6739                 return false;
6740             }
6741         }
6742     }
6743
6744     private void enforceCanManageApplicationRestrictions(ComponentName who) {
6745         if (who != null) {
6746             synchronized (this) {
6747                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6748             }
6749         } else if (!isCallerApplicationRestrictionsManagingPackage()) {
6750             throw new SecurityException(
6751                     "No admin component given, and caller cannot manage application restrictions "
6752                     + "for other apps.");
6753         }
6754     }
6755
6756     @Override
6757     public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) {
6758         enforceCanManageApplicationRestrictions(who);
6759
6760         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
6761         final long id = mInjector.binderClearCallingIdentity();
6762         try {
6763             mUserManager.setApplicationRestrictions(packageName, settings, userHandle);
6764         } finally {
6765             mInjector.binderRestoreCallingIdentity(id);
6766         }
6767     }
6768
6769     @Override
6770     public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent,
6771             PersistableBundle args, boolean parent) {
6772         if (!mHasFeature) {
6773             return;
6774         }
6775         Preconditions.checkNotNull(admin, "admin is null");
6776         Preconditions.checkNotNull(agent, "agent is null");
6777         final int userHandle = UserHandle.getCallingUserId();
6778         synchronized (this) {
6779             ActiveAdmin ap = getActiveAdminForCallerLocked(admin,
6780                     DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent);
6781             ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args));
6782             saveSettingsLocked(userHandle);
6783         }
6784     }
6785
6786     @Override
6787     public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin,
6788             ComponentName agent, int userHandle, boolean parent) {
6789         if (!mHasFeature) {
6790             return null;
6791         }
6792         Preconditions.checkNotNull(agent, "agent null");
6793         enforceFullCrossUsersPermission(userHandle);
6794
6795         synchronized (this) {
6796             final String componentName = agent.flattenToString();
6797             if (admin != null) {
6798                 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent);
6799                 if (ap == null) return null;
6800                 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName);
6801                 if (trustAgentInfo == null || trustAgentInfo.options == null) return null;
6802                 List<PersistableBundle> result = new ArrayList<>();
6803                 result.add(trustAgentInfo.options);
6804                 return result;
6805             }
6806
6807             // Return strictest policy for this user and profiles that are visible from this user.
6808             List<PersistableBundle> result = null;
6809             // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track
6810             // of the options. If any admin doesn't have options, discard options for the rest
6811             // and return null.
6812             List<ActiveAdmin> admins =
6813                     getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent);
6814             boolean allAdminsHaveOptions = true;
6815             final int N = admins.size();
6816             for (int i = 0; i < N; i++) {
6817                 final ActiveAdmin active = admins.get(i);
6818
6819                 final boolean disablesTrust = (active.disabledKeyguardFeatures
6820                         & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
6821                 final TrustAgentInfo info = active.trustAgentInfos.get(componentName);
6822                 if (info != null && info.options != null && !info.options.isEmpty()) {
6823                     if (disablesTrust) {
6824                         if (result == null) {
6825                             result = new ArrayList<>();
6826                         }
6827                         result.add(info.options);
6828                     } else {
6829                         Log.w(LOG_TAG, "Ignoring admin " + active.info
6830                                 + " because it has trust options but doesn't declare "
6831                                 + "KEYGUARD_DISABLE_TRUST_AGENTS");
6832                     }
6833                 } else if (disablesTrust) {
6834                     allAdminsHaveOptions = false;
6835                     break;
6836                 }
6837             }
6838             return allAdminsHaveOptions ? result : null;
6839         }
6840     }
6841
6842     @Override
6843     public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) {
6844         Preconditions.checkNotNull(who, "ComponentName is null");
6845         synchronized (this) {
6846             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6847
6848             int userHandle = UserHandle.getCallingUserId();
6849             DevicePolicyData userData = getUserData(userHandle);
6850             userData.mRestrictionsProvider = permissionProvider;
6851             saveSettingsLocked(userHandle);
6852         }
6853     }
6854
6855     @Override
6856     public ComponentName getRestrictionsProvider(int userHandle) {
6857         synchronized (this) {
6858             if (!isCallerWithSystemUid()) {
6859                 throw new SecurityException("Only the system can query the permission provider");
6860             }
6861             DevicePolicyData userData = getUserData(userHandle);
6862             return userData != null ? userData.mRestrictionsProvider : null;
6863         }
6864     }
6865
6866     @Override
6867     public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) {
6868         Preconditions.checkNotNull(who, "ComponentName is null");
6869         int callingUserId = UserHandle.getCallingUserId();
6870         synchronized (this) {
6871             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6872
6873             long id = mInjector.binderClearCallingIdentity();
6874             try {
6875                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6876                 if (parent == null) {
6877                     Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no "
6878                             + "parent");
6879                     return;
6880                 }
6881                 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) {
6882                     mIPackageManager.addCrossProfileIntentFilter(
6883                             filter, who.getPackageName(), callingUserId, parent.id, 0);
6884                 }
6885                 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) {
6886                     mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(),
6887                             parent.id, callingUserId, 0);
6888                 }
6889             } catch (RemoteException re) {
6890                 // Shouldn't happen
6891             } finally {
6892                 mInjector.binderRestoreCallingIdentity(id);
6893             }
6894         }
6895     }
6896
6897     @Override
6898     public void clearCrossProfileIntentFilters(ComponentName who) {
6899         Preconditions.checkNotNull(who, "ComponentName is null");
6900         int callingUserId = UserHandle.getCallingUserId();
6901         synchronized (this) {
6902             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
6903             long id = mInjector.binderClearCallingIdentity();
6904             try {
6905                 UserInfo parent = mUserManager.getProfileParent(callingUserId);
6906                 if (parent == null) {
6907                     Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no "
6908                             + "parent");
6909                     return;
6910                 }
6911                 // Removing those that go from the managed profile to the parent.
6912                 mIPackageManager.clearCrossProfileIntentFilters(
6913                         callingUserId, who.getPackageName());
6914                 // And those that go from the parent to the managed profile.
6915                 // If we want to support multiple managed profiles, we will have to only remove
6916                 // those that have callingUserId as their target.
6917                 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName());
6918             } catch (RemoteException re) {
6919                 // Shouldn't happen
6920             } finally {
6921                 mInjector.binderRestoreCallingIdentity(id);
6922             }
6923         }
6924     }
6925
6926     /**
6927      * @return true if all packages in enabledPackages are either in the list
6928      * permittedList or are a system app.
6929      */
6930     private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages,
6931             List<String> permittedList, int userIdToCheck) {
6932         long id = mInjector.binderClearCallingIdentity();
6933         try {
6934             // If we have an enabled packages list for a managed profile the packages
6935             // we should check are installed for the parent user.
6936             UserInfo user = getUserInfo(userIdToCheck);
6937             if (user.isManagedProfile()) {
6938                 userIdToCheck = user.profileGroupId;
6939             }
6940
6941             for (String enabledPackage : enabledPackages) {
6942                 boolean systemService = false;
6943                 try {
6944                     ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo(
6945                             enabledPackage, PackageManager.GET_UNINSTALLED_PACKAGES, userIdToCheck);
6946                     systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6947                 } catch (RemoteException e) {
6948                     Log.i(LOG_TAG, "Can't talk to package managed", e);
6949                 }
6950                 if (!systemService && !permittedList.contains(enabledPackage)) {
6951                     return false;
6952                 }
6953             }
6954         } finally {
6955             mInjector.binderRestoreCallingIdentity(id);
6956         }
6957         return true;
6958     }
6959
6960     private AccessibilityManager getAccessibilityManagerForUser(int userId) {
6961         // Not using AccessibilityManager.getInstance because that guesses
6962         // at the user you require based on callingUid and caches for a given
6963         // process.
6964         IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE);
6965         IAccessibilityManager service = iBinder == null
6966                 ? null : IAccessibilityManager.Stub.asInterface(iBinder);
6967         return new AccessibilityManager(mContext, service, userId);
6968     }
6969
6970     @Override
6971     public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) {
6972         if (!mHasFeature) {
6973             return false;
6974         }
6975         Preconditions.checkNotNull(who, "ComponentName is null");
6976
6977         if (packageList != null) {
6978             int userId = UserHandle.getCallingUserId();
6979             List<AccessibilityServiceInfo> enabledServices = null;
6980             long id = mInjector.binderClearCallingIdentity();
6981             try {
6982                 UserInfo user = getUserInfo(userId);
6983                 if (user.isManagedProfile()) {
6984                     userId = user.profileGroupId;
6985                 }
6986                 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId);
6987                 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList(
6988                         AccessibilityServiceInfo.FEEDBACK_ALL_MASK);
6989             } finally {
6990                 mInjector.binderRestoreCallingIdentity(id);
6991             }
6992
6993             if (enabledServices != null) {
6994                 List<String> enabledPackages = new ArrayList<String>();
6995                 for (AccessibilityServiceInfo service : enabledServices) {
6996                     enabledPackages.add(service.getResolveInfo().serviceInfo.packageName);
6997                 }
6998                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
6999                         userId)) {
7000                     Slog.e(LOG_TAG, "Cannot set permitted accessibility services, "
7001                             + "because it contains already enabled accesibility services.");
7002                     return false;
7003                 }
7004             }
7005         }
7006
7007         synchronized (this) {
7008             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7009                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7010             admin.permittedAccessiblityServices = packageList;
7011             saveSettingsLocked(UserHandle.getCallingUserId());
7012         }
7013         return true;
7014     }
7015
7016     @Override
7017     public List getPermittedAccessibilityServices(ComponentName who) {
7018         if (!mHasFeature) {
7019             return null;
7020         }
7021         Preconditions.checkNotNull(who, "ComponentName is null");
7022
7023         synchronized (this) {
7024             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7025                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7026             return admin.permittedAccessiblityServices;
7027         }
7028     }
7029
7030     @Override
7031     public List getPermittedAccessibilityServicesForUser(int userId) {
7032         if (!mHasFeature) {
7033             return null;
7034         }
7035         synchronized (this) {
7036             List<String> result = null;
7037             // If we have multiple profiles we return the intersection of the
7038             // permitted lists. This can happen in cases where we have a device
7039             // and profile owner.
7040             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7041             for (int profileId : profileIds) {
7042                 // Just loop though all admins, only device or profiles
7043                 // owners can have permitted lists set.
7044                 DevicePolicyData policy = getUserDataUnchecked(profileId);
7045                 final int N = policy.mAdminList.size();
7046                 for (int j = 0; j < N; j++) {
7047                     ActiveAdmin admin = policy.mAdminList.get(j);
7048                     List<String> fromAdmin = admin.permittedAccessiblityServices;
7049                     if (fromAdmin != null) {
7050                         if (result == null) {
7051                             result = new ArrayList<>(fromAdmin);
7052                         } else {
7053                             result.retainAll(fromAdmin);
7054                         }
7055                     }
7056                 }
7057             }
7058
7059             // If we have a permitted list add all system accessibility services.
7060             if (result != null) {
7061                 long id = mInjector.binderClearCallingIdentity();
7062                 try {
7063                     UserInfo user = getUserInfo(userId);
7064                     if (user.isManagedProfile()) {
7065                         userId = user.profileGroupId;
7066                     }
7067                     AccessibilityManager accessibilityManager =
7068                             getAccessibilityManagerForUser(userId);
7069                     List<AccessibilityServiceInfo> installedServices =
7070                             accessibilityManager.getInstalledAccessibilityServiceList();
7071
7072                     if (installedServices != null) {
7073                         for (AccessibilityServiceInfo service : installedServices) {
7074                             ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo;
7075                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7076                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7077                                 result.add(serviceInfo.packageName);
7078                             }
7079                         }
7080                     }
7081                 } finally {
7082                     mInjector.binderRestoreCallingIdentity(id);
7083                 }
7084             }
7085
7086             return result;
7087         }
7088     }
7089
7090     @Override
7091     public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName,
7092             int userHandle) {
7093         if (!mHasFeature) {
7094             return true;
7095         }
7096         Preconditions.checkNotNull(who, "ComponentName is null");
7097         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7098         if (!isCallerWithSystemUid()){
7099             throw new SecurityException(
7100                     "Only the system can query if an accessibility service is disabled by admin");
7101         }
7102         synchronized (this) {
7103             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7104             if (admin == null) {
7105                 return false;
7106             }
7107             if (admin.permittedAccessiblityServices == null) {
7108                 return true;
7109             }
7110             return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7111                     admin.permittedAccessiblityServices, userHandle);
7112         }
7113     }
7114
7115     private boolean checkCallerIsCurrentUserOrProfile() {
7116         int callingUserId = UserHandle.getCallingUserId();
7117         long token = mInjector.binderClearCallingIdentity();
7118         try {
7119             UserInfo currentUser;
7120             UserInfo callingUser = getUserInfo(callingUserId);
7121             try {
7122                 currentUser = mInjector.getIActivityManager().getCurrentUser();
7123             } catch (RemoteException e) {
7124                 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e);
7125                 return false;
7126             }
7127
7128             if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) {
7129                 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile "
7130                         + "of a user that isn't the foreground user.");
7131                 return false;
7132             }
7133             if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) {
7134                 Slog.e(LOG_TAG, "Cannot set permitted input methods "
7135                         + "of a user that isn't the foreground user.");
7136                 return false;
7137             }
7138         } finally {
7139             mInjector.binderRestoreCallingIdentity(token);
7140         }
7141         return true;
7142     }
7143
7144     @Override
7145     public boolean setPermittedInputMethods(ComponentName who, List packageList) {
7146         if (!mHasFeature) {
7147             return false;
7148         }
7149         Preconditions.checkNotNull(who, "ComponentName is null");
7150
7151         // TODO When InputMethodManager supports per user calls remove
7152         //      this restriction.
7153         if (!checkCallerIsCurrentUserOrProfile()) {
7154             return false;
7155         }
7156
7157         if (packageList != null) {
7158             // InputMethodManager fetches input methods for current user.
7159             // So this can only be set when calling user is the current user
7160             // or parent is current user in case of managed profiles.
7161             InputMethodManager inputMethodManager =
7162                     mContext.getSystemService(InputMethodManager.class);
7163             List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList();
7164
7165             if (enabledImes != null) {
7166                 List<String> enabledPackages = new ArrayList<String>();
7167                 for (InputMethodInfo ime : enabledImes) {
7168                     enabledPackages.add(ime.getPackageName());
7169                 }
7170                 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList,
7171                         mInjector.binderGetCallingUserHandle().getIdentifier())) {
7172                     Slog.e(LOG_TAG, "Cannot set permitted input methods, "
7173                             + "because it contains already enabled input method.");
7174                     return false;
7175                 }
7176             }
7177         }
7178
7179         synchronized (this) {
7180             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7181                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7182             admin.permittedInputMethods = packageList;
7183             saveSettingsLocked(UserHandle.getCallingUserId());
7184         }
7185         return true;
7186     }
7187
7188     @Override
7189     public List getPermittedInputMethods(ComponentName who) {
7190         if (!mHasFeature) {
7191             return null;
7192         }
7193         Preconditions.checkNotNull(who, "ComponentName is null");
7194
7195         synchronized (this) {
7196             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7197                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7198             return admin.permittedInputMethods;
7199         }
7200     }
7201
7202     @Override
7203     public List getPermittedInputMethodsForCurrentUser() {
7204         UserInfo currentUser;
7205         try {
7206             currentUser = mInjector.getIActivityManager().getCurrentUser();
7207         } catch (RemoteException e) {
7208             Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e);
7209             // Activity managed is dead, just allow all IMEs
7210             return null;
7211         }
7212
7213         int userId = currentUser.id;
7214         synchronized (this) {
7215             List<String> result = null;
7216             // If we have multiple profiles we return the intersection of the
7217             // permitted lists. This can happen in cases where we have a device
7218             // and profile owner.
7219             int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId);
7220             for (int profileId : profileIds) {
7221                 // Just loop though all admins, only device or profiles
7222                 // owners can have permitted lists set.
7223                 DevicePolicyData policy = getUserDataUnchecked(profileId);
7224                 final int N = policy.mAdminList.size();
7225                 for (int j = 0; j < N; j++) {
7226                     ActiveAdmin admin = policy.mAdminList.get(j);
7227                     List<String> fromAdmin = admin.permittedInputMethods;
7228                     if (fromAdmin != null) {
7229                         if (result == null) {
7230                             result = new ArrayList<String>(fromAdmin);
7231                         } else {
7232                             result.retainAll(fromAdmin);
7233                         }
7234                     }
7235                 }
7236             }
7237
7238             // If we have a permitted list add all system input methods.
7239             if (result != null) {
7240                 InputMethodManager inputMethodManager =
7241                         mContext.getSystemService(InputMethodManager.class);
7242                 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList();
7243                 long id = mInjector.binderClearCallingIdentity();
7244                 try {
7245                     if (imes != null) {
7246                         for (InputMethodInfo ime : imes) {
7247                             ServiceInfo serviceInfo = ime.getServiceInfo();
7248                             ApplicationInfo applicationInfo = serviceInfo.applicationInfo;
7249                             if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
7250                                 result.add(serviceInfo.packageName);
7251                             }
7252                         }
7253                     }
7254                 } finally {
7255                     mInjector.binderRestoreCallingIdentity(id);
7256                 }
7257             }
7258             return result;
7259         }
7260     }
7261
7262     @Override
7263     public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName,
7264             int userHandle) {
7265         if (!mHasFeature) {
7266             return true;
7267         }
7268         Preconditions.checkNotNull(who, "ComponentName is null");
7269         Preconditions.checkStringNotEmpty(packageName, "packageName is null");
7270         if (!isCallerWithSystemUid()) {
7271             throw new SecurityException(
7272                     "Only the system can query if an input method is disabled by admin");
7273         }
7274         synchronized (this) {
7275             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
7276             if (admin == null) {
7277                 return false;
7278             }
7279             if (admin.permittedInputMethods == null) {
7280                 return true;
7281             }
7282             return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName),
7283                     admin.permittedInputMethods, userHandle);
7284         }
7285     }
7286
7287     private void sendAdminEnabledBroadcastLocked(int userHandle) {
7288         DevicePolicyData policyData = getUserData(userHandle);
7289         if (policyData.mAdminBroadcastPending) {
7290             // Send the initialization data to profile owner and delete the data
7291             ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle);
7292             if (admin != null) {
7293                 PersistableBundle initBundle = policyData.mInitBundle;
7294                 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED,
7295                         initBundle == null ? null : new Bundle(initBundle), null);
7296             }
7297             policyData.mInitBundle = null;
7298             policyData.mAdminBroadcastPending = false;
7299             saveSettingsLocked(userHandle);
7300         }
7301     }
7302
7303     @Override
7304     public UserHandle createAndManageUser(ComponentName admin, String name,
7305             ComponentName profileOwner, PersistableBundle adminExtras, int flags) {
7306         Preconditions.checkNotNull(admin, "admin is null");
7307         Preconditions.checkNotNull(profileOwner, "profileOwner is null");
7308         if (!admin.getPackageName().equals(profileOwner.getPackageName())) {
7309             throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin "
7310                     + admin + " are not in the same package");
7311         }
7312         // Only allow the system user to use this method
7313         if (!mInjector.binderGetCallingUserHandle().isSystem()) {
7314             throw new SecurityException("createAndManageUser was called from non-system user");
7315         }
7316         if (!mInjector.userManagerIsSplitSystemUser()
7317                 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7318             throw new IllegalArgumentException(
7319                     "Ephemeral users are only supported on systems with a split system user.");
7320         }
7321         // Create user.
7322         UserHandle user = null;
7323         synchronized (this) {
7324             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7325
7326             final long id = mInjector.binderClearCallingIdentity();
7327             try {
7328                 int userInfoFlags = 0;
7329                 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) {
7330                     userInfoFlags |= UserInfo.FLAG_EPHEMERAL;
7331                 }
7332                 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name,
7333                         userInfoFlags);
7334                 if (userInfo != null) {
7335                     user = userInfo.getUserHandle();
7336                 }
7337             } finally {
7338                 mInjector.binderRestoreCallingIdentity(id);
7339             }
7340         }
7341         if (user == null) {
7342             return null;
7343         }
7344         // Set admin.
7345         final long id = mInjector.binderClearCallingIdentity();
7346         try {
7347             final String adminPkg = admin.getPackageName();
7348
7349             final int userHandle = user.getIdentifier();
7350             try {
7351                 // Install the profile owner if not present.
7352                 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) {
7353                     mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle);
7354                 }
7355             } catch (RemoteException e) {
7356                 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, "
7357                         + "removing created user", e);
7358                 mUserManager.removeUser(user.getIdentifier());
7359                 return null;
7360             }
7361
7362             setActiveAdmin(profileOwner, true, userHandle);
7363             // User is not started yet, the broadcast by setActiveAdmin will not be received.
7364             // So we store adminExtras for broadcasting when the user starts for first time.
7365             synchronized(this) {
7366                 DevicePolicyData policyData = getUserData(userHandle);
7367                 policyData.mInitBundle = adminExtras;
7368                 policyData.mAdminBroadcastPending = true;
7369                 saveSettingsLocked(userHandle);
7370             }
7371             final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier());
7372             setProfileOwner(profileOwner, ownerName, userHandle);
7373
7374             if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) {
7375                 Settings.Secure.putIntForUser(mContext.getContentResolver(),
7376                         Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle);
7377             }
7378
7379             return user;
7380         } finally {
7381             mInjector.binderRestoreCallingIdentity(id);
7382         }
7383     }
7384
7385     @Override
7386     public boolean removeUser(ComponentName who, UserHandle userHandle) {
7387         Preconditions.checkNotNull(who, "ComponentName is null");
7388         synchronized (this) {
7389             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7390
7391             long id = mInjector.binderClearCallingIdentity();
7392             try {
7393                 return mUserManager.removeUser(userHandle.getIdentifier());
7394             } finally {
7395                 mInjector.binderRestoreCallingIdentity(id);
7396             }
7397         }
7398     }
7399
7400     @Override
7401     public boolean switchUser(ComponentName who, UserHandle userHandle) {
7402         Preconditions.checkNotNull(who, "ComponentName is null");
7403         synchronized (this) {
7404             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
7405
7406             long id = mInjector.binderClearCallingIdentity();
7407             try {
7408                 int userId = UserHandle.USER_SYSTEM;
7409                 if (userHandle != null) {
7410                     userId = userHandle.getIdentifier();
7411                 }
7412                 return mInjector.getIActivityManager().switchUser(userId);
7413             } catch (RemoteException e) {
7414                 Log.e(LOG_TAG, "Couldn't switch user", e);
7415                 return false;
7416             } finally {
7417                 mInjector.binderRestoreCallingIdentity(id);
7418             }
7419         }
7420     }
7421
7422     @Override
7423     public Bundle getApplicationRestrictions(ComponentName who, String packageName) {
7424         enforceCanManageApplicationRestrictions(who);
7425
7426         final UserHandle userHandle = mInjector.binderGetCallingUserHandle();
7427         final long id = mInjector.binderClearCallingIdentity();
7428         try {
7429            Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle);
7430            // if no restrictions were saved, mUserManager.getApplicationRestrictions
7431            // returns null, but DPM method should return an empty Bundle as per JavaDoc
7432            return bundle != null ? bundle : Bundle.EMPTY;
7433         } finally {
7434             mInjector.binderRestoreCallingIdentity(id);
7435         }
7436     }
7437
7438     @Override
7439     public String[] setPackagesSuspended(ComponentName who, String[] packageNames,
7440             boolean suspended) {
7441         Preconditions.checkNotNull(who, "ComponentName is null");
7442         int callingUserId = UserHandle.getCallingUserId();
7443         synchronized (this) {
7444             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7445
7446             long id = mInjector.binderClearCallingIdentity();
7447             try {
7448                 return mIPackageManager.setPackagesSuspendedAsUser(
7449                         packageNames, suspended, callingUserId);
7450             } catch (RemoteException re) {
7451                 // Shouldn't happen.
7452                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7453             } finally {
7454                 mInjector.binderRestoreCallingIdentity(id);
7455             }
7456             return packageNames;
7457         }
7458     }
7459
7460     @Override
7461     public boolean isPackageSuspended(ComponentName who, String packageName) {
7462         Preconditions.checkNotNull(who, "ComponentName is null");
7463         int callingUserId = UserHandle.getCallingUserId();
7464         synchronized (this) {
7465             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7466
7467             long id = mInjector.binderClearCallingIdentity();
7468             try {
7469                 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId);
7470             } catch (RemoteException re) {
7471                 // Shouldn't happen.
7472                 Slog.e(LOG_TAG, "Failed talking to the package manager", re);
7473             } finally {
7474                 mInjector.binderRestoreCallingIdentity(id);
7475             }
7476             return false;
7477         }
7478     }
7479
7480     @Override
7481     public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) {
7482         Preconditions.checkNotNull(who, "ComponentName is null");
7483         if (!UserRestrictionsUtils.isValidRestriction(key)) {
7484             return;
7485         }
7486
7487         final int userHandle = mInjector.userHandleGetCallingUserId();
7488         synchronized (this) {
7489             ActiveAdmin activeAdmin =
7490                     getActiveAdminForCallerLocked(who,
7491                             DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7492             final boolean isDeviceOwner = isDeviceOwner(who, userHandle);
7493             if (isDeviceOwner) {
7494                 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) {
7495                     throw new SecurityException("Device owner cannot set user restriction " + key);
7496                 }
7497             } else { // profile owner
7498                 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) {
7499                     throw new SecurityException("Profile owner cannot set user restriction " + key);
7500                 }
7501             }
7502
7503             // Save the restriction to ActiveAdmin.
7504             activeAdmin.ensureUserRestrictions().putBoolean(key, enabledFromThisOwner);
7505             saveSettingsLocked(userHandle);
7506
7507             pushUserRestrictions(userHandle);
7508
7509             sendChangedNotification(userHandle);
7510         }
7511     }
7512
7513     private void pushUserRestrictions(int userId) {
7514         synchronized (this) {
7515             final Bundle global;
7516             final Bundle local = new Bundle();
7517             if (mOwners.isDeviceOwnerUserId(userId)) {
7518                 global = new Bundle();
7519
7520                 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked();
7521                 if (deviceOwner == null) {
7522                     return; // Shouldn't happen.
7523                 }
7524
7525                 UserRestrictionsUtils.sortToGlobalAndLocal(deviceOwner.userRestrictions,
7526                         global, local);
7527                 // DO can disable camera globally.
7528                 if (deviceOwner.disableCamera) {
7529                     global.putBoolean(UserManager.DISALLOW_CAMERA, true);
7530                 }
7531             } else {
7532                 global = null;
7533
7534                 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId);
7535                 if (profileOwner != null) {
7536                     UserRestrictionsUtils.merge(local, profileOwner.userRestrictions);
7537                 }
7538             }
7539             // Also merge in *local* camera restriction.
7540             if (getCameraDisabled(/* who= */ null,
7541                     userId, /* mergeDeviceOwnerRestriction= */ false)) {
7542                 local.putBoolean(UserManager.DISALLOW_CAMERA, true);
7543             }
7544             mUserManagerInternal.setDevicePolicyUserRestrictions(userId, local, global);
7545         }
7546     }
7547
7548     @Override
7549     public Bundle getUserRestrictions(ComponentName who) {
7550         if (!mHasFeature) {
7551             return null;
7552         }
7553         Preconditions.checkNotNull(who, "ComponentName is null");
7554         synchronized (this) {
7555             final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who,
7556                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7557             return activeAdmin.userRestrictions;
7558         }
7559     }
7560
7561     @Override
7562     public boolean setApplicationHidden(ComponentName who, String packageName,
7563             boolean hidden) {
7564         Preconditions.checkNotNull(who, "ComponentName is null");
7565         int callingUserId = UserHandle.getCallingUserId();
7566         synchronized (this) {
7567             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7568
7569             long id = mInjector.binderClearCallingIdentity();
7570             try {
7571                 return mIPackageManager.setApplicationHiddenSettingAsUser(
7572                         packageName, hidden, callingUserId);
7573             } catch (RemoteException re) {
7574                 // shouldn't happen
7575                 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re);
7576             } finally {
7577                 mInjector.binderRestoreCallingIdentity(id);
7578             }
7579             return false;
7580         }
7581     }
7582
7583     @Override
7584     public boolean isApplicationHidden(ComponentName who, String packageName) {
7585         Preconditions.checkNotNull(who, "ComponentName is null");
7586         int callingUserId = UserHandle.getCallingUserId();
7587         synchronized (this) {
7588             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7589
7590             long id = mInjector.binderClearCallingIdentity();
7591             try {
7592                 return mIPackageManager.getApplicationHiddenSettingAsUser(
7593                         packageName, callingUserId);
7594             } catch (RemoteException re) {
7595                 // shouldn't happen
7596                 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re);
7597             } finally {
7598                 mInjector.binderRestoreCallingIdentity(id);
7599             }
7600             return false;
7601         }
7602     }
7603
7604     @Override
7605     public void enableSystemApp(ComponentName who, String packageName) {
7606         Preconditions.checkNotNull(who, "ComponentName is null");
7607         synchronized (this) {
7608             // This API can only be called by an active device admin,
7609             // so try to retrieve it to check that the caller is one.
7610             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7611
7612             int userId = UserHandle.getCallingUserId();
7613             long id = mInjector.binderClearCallingIdentity();
7614
7615             try {
7616                 if (VERBOSE_LOG) {
7617                     Slog.v(LOG_TAG, "installing " + packageName + " for "
7618                             + userId);
7619                 }
7620
7621                 int parentUserId = getProfileParentId(userId);
7622                 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) {
7623                     throw new IllegalArgumentException("Only system apps can be enabled this way.");
7624                 }
7625
7626                 // Install the app.
7627                 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7628
7629             } catch (RemoteException re) {
7630                 // shouldn't happen
7631                 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re);
7632             } finally {
7633                 mInjector.binderRestoreCallingIdentity(id);
7634             }
7635         }
7636     }
7637
7638     @Override
7639     public int enableSystemAppWithIntent(ComponentName who, Intent intent) {
7640         Preconditions.checkNotNull(who, "ComponentName is null");
7641         synchronized (this) {
7642             // This API can only be called by an active device admin,
7643             // so try to retrieve it to check that the caller is one.
7644             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7645
7646             int userId = UserHandle.getCallingUserId();
7647             long id = mInjector.binderClearCallingIdentity();
7648
7649             try {
7650                 int parentUserId = getProfileParentId(userId);
7651                 List<ResolveInfo> activitiesToEnable = mIPackageManager
7652                         .queryIntentActivities(intent,
7653                                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
7654                                 PackageManager.MATCH_DIRECT_BOOT_AWARE
7655                                         | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
7656                                 parentUserId)
7657                         .getList();
7658
7659                 if (VERBOSE_LOG) {
7660                     Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable);
7661                 }
7662                 int numberOfAppsInstalled = 0;
7663                 if (activitiesToEnable != null) {
7664                     for (ResolveInfo info : activitiesToEnable) {
7665                         if (info.activityInfo != null) {
7666                             String packageName = info.activityInfo.packageName;
7667                             if (isSystemApp(mIPackageManager, packageName, parentUserId)) {
7668                                 numberOfAppsInstalled++;
7669                                 mIPackageManager.installExistingPackageAsUser(packageName, userId);
7670                             } else {
7671                                 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a"
7672                                         + " system app");
7673                             }
7674                         }
7675                     }
7676                 }
7677                 return numberOfAppsInstalled;
7678             } catch (RemoteException e) {
7679                 // shouldn't happen
7680                 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent);
7681                 return 0;
7682             } finally {
7683                 mInjector.binderRestoreCallingIdentity(id);
7684             }
7685         }
7686     }
7687
7688     private boolean isSystemApp(IPackageManager pm, String packageName, int userId)
7689             throws RemoteException {
7690         ApplicationInfo appInfo = pm.getApplicationInfo(packageName, GET_UNINSTALLED_PACKAGES,
7691                 userId);
7692         if (appInfo == null) {
7693             throw new IllegalArgumentException("The application " + packageName +
7694                     " is not present on this device");
7695         }
7696         return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
7697     }
7698
7699     @Override
7700     public void setAccountManagementDisabled(ComponentName who, String accountType,
7701             boolean disabled) {
7702         if (!mHasFeature) {
7703             return;
7704         }
7705         Preconditions.checkNotNull(who, "ComponentName is null");
7706         synchronized (this) {
7707             ActiveAdmin ap = getActiveAdminForCallerLocked(who,
7708                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7709             if (disabled) {
7710                 ap.accountTypesWithManagementDisabled.add(accountType);
7711             } else {
7712                 ap.accountTypesWithManagementDisabled.remove(accountType);
7713             }
7714             saveSettingsLocked(UserHandle.getCallingUserId());
7715         }
7716     }
7717
7718     @Override
7719     public String[] getAccountTypesWithManagementDisabled() {
7720         return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId());
7721     }
7722
7723     @Override
7724     public String[] getAccountTypesWithManagementDisabledAsUser(int userId) {
7725         enforceFullCrossUsersPermission(userId);
7726         if (!mHasFeature) {
7727             return null;
7728         }
7729         synchronized (this) {
7730             DevicePolicyData policy = getUserData(userId);
7731             final int N = policy.mAdminList.size();
7732             ArraySet<String> resultSet = new ArraySet<>();
7733             for (int i = 0; i < N; i++) {
7734                 ActiveAdmin admin = policy.mAdminList.get(i);
7735                 resultSet.addAll(admin.accountTypesWithManagementDisabled);
7736             }
7737             return resultSet.toArray(new String[resultSet.size()]);
7738         }
7739     }
7740
7741     @Override
7742     public void setUninstallBlocked(ComponentName who, String packageName,
7743             boolean uninstallBlocked) {
7744         Preconditions.checkNotNull(who, "ComponentName is null");
7745         final int userId = UserHandle.getCallingUserId();
7746         synchronized (this) {
7747             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7748
7749             long id = mInjector.binderClearCallingIdentity();
7750             try {
7751                 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId);
7752             } catch (RemoteException re) {
7753                 // Shouldn't happen.
7754                 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re);
7755             } finally {
7756                 mInjector.binderRestoreCallingIdentity(id);
7757             }
7758         }
7759     }
7760
7761     @Override
7762     public boolean isUninstallBlocked(ComponentName who, String packageName) {
7763         // This function should return true if and only if the package is blocked by
7764         // setUninstallBlocked(). It should still return false for other cases of blocks, such as
7765         // when the package is a system app, or when it is an active device admin.
7766         final int userId = UserHandle.getCallingUserId();
7767
7768         synchronized (this) {
7769             if (who != null) {
7770                 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7771             }
7772
7773             long id = mInjector.binderClearCallingIdentity();
7774             try {
7775                 return mIPackageManager.getBlockUninstallForUser(packageName, userId);
7776             } catch (RemoteException re) {
7777                 // Shouldn't happen.
7778                 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re);
7779             } finally {
7780                 mInjector.binderRestoreCallingIdentity(id);
7781             }
7782         }
7783         return false;
7784     }
7785
7786     @Override
7787     public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) {
7788         if (!mHasFeature) {
7789             return;
7790         }
7791         Preconditions.checkNotNull(who, "ComponentName is null");
7792         synchronized (this) {
7793             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7794                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7795             if (admin.disableCallerId != disabled) {
7796                 admin.disableCallerId = disabled;
7797                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7798             }
7799         }
7800     }
7801
7802     @Override
7803     public boolean getCrossProfileCallerIdDisabled(ComponentName who) {
7804         if (!mHasFeature) {
7805             return false;
7806         }
7807         Preconditions.checkNotNull(who, "ComponentName is null");
7808         synchronized (this) {
7809             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7810                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7811             return admin.disableCallerId;
7812         }
7813     }
7814
7815     @Override
7816     public boolean getCrossProfileCallerIdDisabledForUser(int userId) {
7817         enforceCrossUsersPermission(userId);
7818         synchronized (this) {
7819             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7820             return (admin != null) ? admin.disableCallerId : false;
7821         }
7822     }
7823
7824     @Override
7825     public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) {
7826         if (!mHasFeature) {
7827             return;
7828         }
7829         Preconditions.checkNotNull(who, "ComponentName is null");
7830         synchronized (this) {
7831             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7832                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7833             if (admin.disableContactsSearch != disabled) {
7834                 admin.disableContactsSearch = disabled;
7835                 saveSettingsLocked(mInjector.userHandleGetCallingUserId());
7836             }
7837         }
7838     }
7839
7840     @Override
7841     public boolean getCrossProfileContactsSearchDisabled(ComponentName who) {
7842         if (!mHasFeature) {
7843             return false;
7844         }
7845         Preconditions.checkNotNull(who, "ComponentName is null");
7846         synchronized (this) {
7847             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7848                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7849             return admin.disableContactsSearch;
7850         }
7851     }
7852
7853     @Override
7854     public boolean getCrossProfileContactsSearchDisabledForUser(int userId) {
7855         enforceCrossUsersPermission(userId);
7856         synchronized (this) {
7857             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7858             return (admin != null) ? admin.disableContactsSearch : false;
7859         }
7860     }
7861
7862     @Override
7863     public void startManagedQuickContact(String actualLookupKey, long actualContactId,
7864             boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) {
7865         final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey,
7866                 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent);
7867         final int callingUserId = UserHandle.getCallingUserId();
7868
7869         final long ident = mInjector.binderClearCallingIdentity();
7870         try {
7871             synchronized (this) {
7872                 final int managedUserId = getManagedUserId(callingUserId);
7873                 if (managedUserId < 0) {
7874                     return;
7875                 }
7876                 if (isCrossProfileQuickContactDisabled(managedUserId)) {
7877                     if (VERBOSE_LOG) {
7878                         Log.v(LOG_TAG,
7879                                 "Cross-profile contacts access disabled for user " + managedUserId);
7880                     }
7881                     return;
7882                 }
7883                 ContactsInternal.startQuickContactWithErrorToastForUser(
7884                         mContext, intent, new UserHandle(managedUserId));
7885             }
7886         } finally {
7887             mInjector.binderRestoreCallingIdentity(ident);
7888         }
7889     }
7890
7891     /**
7892      * @return true if cross-profile QuickContact is disabled
7893      */
7894     private boolean isCrossProfileQuickContactDisabled(int userId) {
7895         return getCrossProfileCallerIdDisabledForUser(userId)
7896                 && getCrossProfileContactsSearchDisabledForUser(userId);
7897     }
7898
7899     /**
7900      * @return the user ID of the managed user that is linked to the current user, if any.
7901      * Otherwise -1.
7902      */
7903     public int getManagedUserId(int callingUserId) {
7904         if (VERBOSE_LOG) {
7905             Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId);
7906         }
7907
7908         for (UserInfo ui : mUserManager.getProfiles(callingUserId)) {
7909             if (ui.id == callingUserId || !ui.isManagedProfile()) {
7910                 continue; // Caller user self, or not a managed profile.  Skip.
7911             }
7912             if (VERBOSE_LOG) {
7913                 Log.v(LOG_TAG, "Managed user=" + ui.id);
7914             }
7915             return ui.id;
7916         }
7917         if (VERBOSE_LOG) {
7918             Log.v(LOG_TAG, "Managed user not found.");
7919         }
7920         return -1;
7921     }
7922
7923     @Override
7924     public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) {
7925         if (!mHasFeature) {
7926             return;
7927         }
7928         Preconditions.checkNotNull(who, "ComponentName is null");
7929         synchronized (this) {
7930             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7931                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7932             if (admin.disableBluetoothContactSharing != disabled) {
7933                 admin.disableBluetoothContactSharing = disabled;
7934                 saveSettingsLocked(UserHandle.getCallingUserId());
7935             }
7936         }
7937     }
7938
7939     @Override
7940     public boolean getBluetoothContactSharingDisabled(ComponentName who) {
7941         if (!mHasFeature) {
7942             return false;
7943         }
7944         Preconditions.checkNotNull(who, "ComponentName is null");
7945         synchronized (this) {
7946             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
7947                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
7948             return admin.disableBluetoothContactSharing;
7949         }
7950     }
7951
7952     @Override
7953     public boolean getBluetoothContactSharingDisabledForUser(int userId) {
7954         // TODO: Should there be a check to make sure this relationship is
7955         // within a profile group?
7956         // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system");
7957         synchronized (this) {
7958             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
7959             return (admin != null) ? admin.disableBluetoothContactSharing : false;
7960         }
7961     }
7962
7963     /**
7964      * Sets which packages may enter lock task mode.
7965      *
7966      * <p>This function can only be called by the device owner or alternatively by the profile owner
7967      * in case the user is affiliated.
7968      *
7969      * @param packages The list of packages allowed to enter lock task mode.
7970      */
7971     @Override
7972     public void setLockTaskPackages(ComponentName who, String[] packages)
7973             throws SecurityException {
7974         Preconditions.checkNotNull(who, "ComponentName is null");
7975         synchronized (this) {
7976             ActiveAdmin deviceOwner = getActiveAdminWithPolicyForUidLocked(
7977                 who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, mInjector.binderGetCallingUid());
7978             ActiveAdmin profileOwner = getActiveAdminWithPolicyForUidLocked(
7979                 who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid());
7980             if (deviceOwner != null || (profileOwner != null && isAffiliatedUser())) {
7981                 int userHandle = mInjector.userHandleGetCallingUserId();
7982                 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages)));
7983             } else {
7984                 throw new SecurityException("Admin " + who +
7985                     " is neither the device owner or affiliated user's profile owner.");
7986             }
7987         }
7988     }
7989
7990     private void setLockTaskPackagesLocked(int userHandle, List<String> packages) {
7991         DevicePolicyData policy = getUserData(userHandle);
7992         policy.mLockTaskPackages = packages;
7993
7994         // Store the settings persistently.
7995         saveSettingsLocked(userHandle);
7996         updateLockTaskPackagesLocked(packages, userHandle);
7997     }
7998
7999     /**
8000      * This function returns the list of components allowed to start the task lock mode.
8001      */
8002     @Override
8003     public String[] getLockTaskPackages(ComponentName who) {
8004         Preconditions.checkNotNull(who, "ComponentName is null");
8005         synchronized (this) {
8006             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8007             int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier();
8008             final List<String> packages = getLockTaskPackagesLocked(userHandle);
8009             return packages.toArray(new String[packages.size()]);
8010         }
8011     }
8012
8013     private List<String> getLockTaskPackagesLocked(int userHandle) {
8014         final DevicePolicyData policy = getUserData(userHandle);
8015         return policy.mLockTaskPackages;
8016     }
8017
8018     /**
8019      * This function lets the caller know whether the given package is allowed to start the
8020      * lock task mode.
8021      * @param pkg The package to check
8022      */
8023     @Override
8024     public boolean isLockTaskPermitted(String pkg) {
8025         // Get current user's devicepolicy
8026         int uid = mInjector.binderGetCallingUid();
8027         int userHandle = UserHandle.getUserId(uid);
8028         DevicePolicyData policy = getUserData(userHandle);
8029         synchronized (this) {
8030             for (int i = 0; i < policy.mLockTaskPackages.size(); i++) {
8031                 String lockTaskPackage = policy.mLockTaskPackages.get(i);
8032
8033                 // If the given package equals one of the packages stored our list,
8034                 // we allow this package to start lock task mode.
8035                 if (lockTaskPackage.equals(pkg)) {
8036                     return true;
8037                 }
8038             }
8039         }
8040         return false;
8041     }
8042
8043     @Override
8044     public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) {
8045         if (!isCallerWithSystemUid()) {
8046             throw new SecurityException("notifyLockTaskModeChanged can only be called by system");
8047         }
8048         synchronized (this) {
8049             final DevicePolicyData policy = getUserData(userHandle);
8050             Bundle adminExtras = new Bundle();
8051             adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg);
8052             for (ActiveAdmin admin : policy.mAdminList) {
8053                 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle);
8054                 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle);
8055                 if (ownsDevice || ownsProfile) {
8056                     if (isEnabled) {
8057                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING,
8058                                 adminExtras, null);
8059                     } else {
8060                         sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING);
8061                     }
8062                 }
8063             }
8064         }
8065     }
8066
8067     @Override
8068     public void setGlobalSetting(ComponentName who, String setting, String value) {
8069         Preconditions.checkNotNull(who, "ComponentName is null");
8070
8071         synchronized (this) {
8072             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8073
8074             // Some settings are no supported any more. However we do not want to throw a
8075             // SecurityException to avoid breaking apps.
8076             if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) {
8077                 Log.i(LOG_TAG, "Global setting no longer supported: " + setting);
8078                 return;
8079             }
8080
8081             if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) {
8082                 throw new SecurityException(String.format(
8083                         "Permission denial: device owners cannot update %1$s", setting));
8084             }
8085
8086             if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) {
8087                 // ignore if it contradicts an existing policy
8088                 long timeMs = getMaximumTimeToLock(
8089                         who, mInjector.userHandleGetCallingUserId(), /* parent */ false);
8090                 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) {
8091                     return;
8092                 }
8093             }
8094
8095             long id = mInjector.binderClearCallingIdentity();
8096             try {
8097                 mInjector.settingsGlobalPutString(setting, value);
8098             } finally {
8099                 mInjector.binderRestoreCallingIdentity(id);
8100             }
8101         }
8102     }
8103
8104     @Override
8105     public void setSecureSetting(ComponentName who, String setting, String value) {
8106         Preconditions.checkNotNull(who, "ComponentName is null");
8107         int callingUserId = mInjector.userHandleGetCallingUserId();
8108
8109         synchronized (this) {
8110             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8111
8112             if (isDeviceOwner(who, callingUserId)) {
8113                 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) {
8114                     throw new SecurityException(String.format(
8115                             "Permission denial: Device owners cannot update %1$s", setting));
8116                 }
8117             } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) {
8118                 throw new SecurityException(String.format(
8119                         "Permission denial: Profile owners cannot update %1$s", setting));
8120             }
8121
8122             long id = mInjector.binderClearCallingIdentity();
8123             try {
8124                 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId);
8125             } finally {
8126                 mInjector.binderRestoreCallingIdentity(id);
8127             }
8128         }
8129     }
8130
8131     @Override
8132     public void setMasterVolumeMuted(ComponentName who, boolean on) {
8133         Preconditions.checkNotNull(who, "ComponentName is null");
8134         synchronized (this) {
8135             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8136             setUserRestriction(who, UserManager.DISALLLOW_UNMUTE_DEVICE, on);
8137         }
8138     }
8139
8140     @Override
8141     public boolean isMasterVolumeMuted(ComponentName who) {
8142         Preconditions.checkNotNull(who, "ComponentName is null");
8143         synchronized (this) {
8144             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8145
8146             AudioManager audioManager =
8147                     (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
8148             return audioManager.isMasterMute();
8149         }
8150     }
8151
8152     @Override
8153     public void setUserIcon(ComponentName who, Bitmap icon) {
8154         synchronized (this) {
8155             Preconditions.checkNotNull(who, "ComponentName is null");
8156             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8157
8158             int userId = UserHandle.getCallingUserId();
8159             long id = mInjector.binderClearCallingIdentity();
8160             try {
8161                 mUserManagerInternal.setUserIcon(userId, icon);
8162             } finally {
8163                 mInjector.binderRestoreCallingIdentity(id);
8164             }
8165         }
8166     }
8167
8168     @Override
8169     public boolean setKeyguardDisabled(ComponentName who, boolean disabled) {
8170         Preconditions.checkNotNull(who, "ComponentName is null");
8171         synchronized (this) {
8172             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8173         }
8174         final int userId = UserHandle.getCallingUserId();
8175
8176         long ident = mInjector.binderClearCallingIdentity();
8177         try {
8178             // disallow disabling the keyguard if a password is currently set
8179             if (disabled && mLockPatternUtils.isSecure(userId)) {
8180                 return false;
8181             }
8182             mLockPatternUtils.setLockScreenDisabled(disabled, userId);
8183         } finally {
8184             mInjector.binderRestoreCallingIdentity(ident);
8185         }
8186         return true;
8187     }
8188
8189     @Override
8190     public boolean setStatusBarDisabled(ComponentName who, boolean disabled) {
8191         int userId = UserHandle.getCallingUserId();
8192         synchronized (this) {
8193             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8194             DevicePolicyData policy = getUserData(userId);
8195             if (policy.mStatusBarDisabled != disabled) {
8196                 if (!setStatusBarDisabledInternal(disabled, userId)) {
8197                     return false;
8198                 }
8199                 policy.mStatusBarDisabled = disabled;
8200                 saveSettingsLocked(userId);
8201             }
8202         }
8203         return true;
8204     }
8205
8206     private boolean setStatusBarDisabledInternal(boolean disabled, int userId) {
8207         long ident = mInjector.binderClearCallingIdentity();
8208         try {
8209             IStatusBarService statusBarService = IStatusBarService.Stub.asInterface(
8210                     ServiceManager.checkService(Context.STATUS_BAR_SERVICE));
8211             if (statusBarService != null) {
8212                 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE;
8213                 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE;
8214                 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId);
8215                 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId);
8216                 return true;
8217             }
8218         } catch (RemoteException e) {
8219             Slog.e(LOG_TAG, "Failed to disable the status bar", e);
8220         } finally {
8221             mInjector.binderRestoreCallingIdentity(ident);
8222         }
8223         return false;
8224     }
8225
8226     /**
8227      * We need to update the internal state of whether a user has completed setup or a
8228      * device has paired once. After that, we ignore any changes that reset the
8229      * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change
8230      * as we don't trust any apps that might try to reset them.
8231      * <p>
8232      * Unfortunately, we don't know which user's setup state was changed, so we write all of
8233      * them.
8234      */
8235     void updateUserSetupCompleteAndPaired() {
8236         List<UserInfo> users = mUserManager.getUsers(true);
8237         final int N = users.size();
8238         for (int i = 0; i < N; i++) {
8239             int userHandle = users.get(i).id;
8240             if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
8241                     userHandle) != 0) {
8242                 DevicePolicyData policy = getUserData(userHandle);
8243                 if (!policy.mUserSetupComplete) {
8244                     policy.mUserSetupComplete = true;
8245                     synchronized (this) {
8246                         saveSettingsLocked(userHandle);
8247                     }
8248                 }
8249             }
8250             if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0,
8251                     userHandle) != 0) {
8252                 DevicePolicyData policy = getUserData(userHandle);
8253                 if (!policy.mPaired) {
8254                     policy.mPaired = true;
8255                     synchronized (this) {
8256                         saveSettingsLocked(userHandle);
8257                     }
8258                 }
8259             }
8260         }
8261     }
8262
8263     private class SetupContentObserver extends ContentObserver {
8264
8265         private final Uri mUserSetupComplete = Settings.Secure.getUriFor(
8266                 Settings.Secure.USER_SETUP_COMPLETE);
8267         private final Uri mDeviceProvisioned = Settings.Global.getUriFor(
8268                 Settings.Global.DEVICE_PROVISIONED);
8269         private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED);
8270
8271         public SetupContentObserver(Handler handler) {
8272             super(handler);
8273         }
8274
8275         void register() {
8276             mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL);
8277             mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL);
8278             if (mIsWatch) {
8279                 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL);
8280             }
8281         }
8282
8283         @Override
8284         public void onChange(boolean selfChange, Uri uri) {
8285             if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) {
8286                 updateUserSetupCompleteAndPaired();
8287             } else if (mDeviceProvisioned.equals(uri)) {
8288                 synchronized (DevicePolicyManagerService.this) {
8289                     // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property
8290                     // is delayed until device is marked as provisioned.
8291                     setDeviceOwnerSystemPropertyLocked();
8292                 }
8293             }
8294         }
8295     }
8296
8297     @VisibleForTesting
8298     final class LocalService extends DevicePolicyManagerInternal {
8299         private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners;
8300
8301         @Override
8302         public List<String> getCrossProfileWidgetProviders(int profileId) {
8303             synchronized (DevicePolicyManagerService.this) {
8304                 if (mOwners == null) {
8305                     return Collections.emptyList();
8306                 }
8307                 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId);
8308                 if (ownerComponent == null) {
8309                     return Collections.emptyList();
8310                 }
8311
8312                 DevicePolicyData policy = getUserDataUnchecked(profileId);
8313                 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent);
8314
8315                 if (admin == null || admin.crossProfileWidgetProviders == null
8316                         || admin.crossProfileWidgetProviders.isEmpty()) {
8317                     return Collections.emptyList();
8318                 }
8319
8320                 return admin.crossProfileWidgetProviders;
8321             }
8322         }
8323
8324         @Override
8325         public void addOnCrossProfileWidgetProvidersChangeListener(
8326                 OnCrossProfileWidgetProvidersChangeListener listener) {
8327             synchronized (DevicePolicyManagerService.this) {
8328                 if (mWidgetProviderListeners == null) {
8329                     mWidgetProviderListeners = new ArrayList<>();
8330                 }
8331                 if (!mWidgetProviderListeners.contains(listener)) {
8332                     mWidgetProviderListeners.add(listener);
8333                 }
8334             }
8335         }
8336
8337         @Override
8338         public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) {
8339             synchronized(DevicePolicyManagerService.this) {
8340                 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null;
8341             }
8342         }
8343
8344         private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) {
8345             final List<OnCrossProfileWidgetProvidersChangeListener> listeners;
8346             synchronized (DevicePolicyManagerService.this) {
8347                 listeners = new ArrayList<>(mWidgetProviderListeners);
8348             }
8349             final int listenerCount = listeners.size();
8350             for (int i = 0; i < listenerCount; i++) {
8351                 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i);
8352                 listener.onCrossProfileWidgetProvidersChanged(userId, packages);
8353             }
8354         }
8355
8356         @Override
8357         public Intent createPackageSuspendedDialogIntent(String packageName, int userId) {
8358             Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS);
8359             intent.putExtra(Intent.EXTRA_USER_ID, userId);
8360             intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8361
8362             // This method is called from AM with its lock held, so don't take the DPMS lock.
8363             // b/29242568
8364
8365             ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId);
8366             if (profileOwner != null) {
8367                 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, profileOwner);
8368                 return intent;
8369             }
8370
8371             final Pair<Integer, ComponentName> deviceOwner =
8372                     mOwners.getDeviceOwnerUserIdAndComponent();
8373             if (deviceOwner != null && deviceOwner.first == userId) {
8374                 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceOwner.second);
8375                 return intent;
8376             }
8377
8378             // We're not specifying the device admin because there isn't one.
8379             return intent;
8380         }
8381     }
8382
8383     /**
8384      * Returns true if specified admin is allowed to limit passwords and has a
8385      * {@code passwordQuality} of at least {@code minPasswordQuality}
8386      */
8387     private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) {
8388         if (admin.passwordQuality < minPasswordQuality) {
8389             return false;
8390         }
8391         return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD);
8392     }
8393
8394     @Override
8395     public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) {
8396         if (policy != null && !policy.isValid()) {
8397             throw new IllegalArgumentException("Invalid system update policy.");
8398         }
8399         synchronized (this) {
8400             getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8401             if (policy == null) {
8402                 mOwners.clearSystemUpdatePolicy();
8403             } else {
8404                 mOwners.setSystemUpdatePolicy(policy);
8405             }
8406             mOwners.writeDeviceOwner();
8407         }
8408         mContext.sendBroadcastAsUser(
8409                 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED),
8410                 UserHandle.SYSTEM);
8411     }
8412
8413     @Override
8414     public SystemUpdatePolicy getSystemUpdatePolicy() {
8415         if (UserManager.isDeviceInDemoMode(mContext)) {
8416             // Pretending to have an automatic update policy when the device is in retail demo
8417             // mode. This will allow the device to download and install an ota without
8418             // any user interaction.
8419             return SystemUpdatePolicy.createAutomaticInstallPolicy();
8420         }
8421         synchronized (this) {
8422             SystemUpdatePolicy policy =  mOwners.getSystemUpdatePolicy();
8423             if (policy != null && !policy.isValid()) {
8424                 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead.");
8425                 return null;
8426             }
8427             return policy;
8428         }
8429     }
8430
8431     /**
8432      * Checks if the caller of the method is the device owner app.
8433      *
8434      * @param callerUid UID of the caller.
8435      * @return true if the caller is the device owner app
8436      */
8437     @VisibleForTesting
8438     boolean isCallerDeviceOwner(int callerUid) {
8439         synchronized (this) {
8440             if (!mOwners.hasDeviceOwner()) {
8441                 return false;
8442             }
8443             if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) {
8444                 return false;
8445             }
8446             final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent()
8447                     .getPackageName();
8448             final String[] pkgs = mContext.getPackageManager().getPackagesForUid(callerUid);
8449
8450             for (String pkg : pkgs) {
8451                 if (deviceOwnerPackageName.equals(pkg)) {
8452                     return true;
8453                 }
8454             }
8455         }
8456
8457         return false;
8458     }
8459
8460     @Override
8461     public void notifyPendingSystemUpdate(long updateReceivedTime) {
8462         mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE,
8463                 "Only the system update service can broadcast update information");
8464
8465         if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) {
8466             Slog.w(LOG_TAG, "Only the system update service in the system user " +
8467                     "can broadcast update information.");
8468             return;
8469         }
8470         Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE);
8471         intent.putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME,
8472                 updateReceivedTime);
8473
8474         synchronized (this) {
8475             final String deviceOwnerPackage =
8476                     mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerComponent().getPackageName()
8477                             : null;
8478             if (deviceOwnerPackage == null) {
8479                 return;
8480             }
8481             final UserHandle deviceOwnerUser = new UserHandle(mOwners.getDeviceOwnerUserId());
8482
8483             ActivityInfo[] receivers = null;
8484             try {
8485                 receivers  = mContext.getPackageManager().getPackageInfo(
8486                         deviceOwnerPackage, PackageManager.GET_RECEIVERS).receivers;
8487             } catch (NameNotFoundException e) {
8488                 Log.e(LOG_TAG, "Cannot find device owner package", e);
8489             }
8490             if (receivers != null) {
8491                 long ident = mInjector.binderClearCallingIdentity();
8492                 try {
8493                     for (int i = 0; i < receivers.length; i++) {
8494                         if (permission.BIND_DEVICE_ADMIN.equals(receivers[i].permission)) {
8495                             intent.setComponent(new ComponentName(deviceOwnerPackage,
8496                                     receivers[i].name));
8497                             mContext.sendBroadcastAsUser(intent, deviceOwnerUser);
8498                         }
8499                     }
8500                 } finally {
8501                     mInjector.binderRestoreCallingIdentity(ident);
8502                 }
8503             }
8504         }
8505     }
8506
8507     @Override
8508     public void setPermissionPolicy(ComponentName admin, int policy) throws RemoteException {
8509         int userId = UserHandle.getCallingUserId();
8510         synchronized (this) {
8511             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8512             DevicePolicyData userPolicy = getUserData(userId);
8513             if (userPolicy.mPermissionPolicy != policy) {
8514                 userPolicy.mPermissionPolicy = policy;
8515                 saveSettingsLocked(userId);
8516             }
8517         }
8518     }
8519
8520     @Override
8521     public int getPermissionPolicy(ComponentName admin) throws RemoteException {
8522         int userId = UserHandle.getCallingUserId();
8523         synchronized (this) {
8524             DevicePolicyData userPolicy = getUserData(userId);
8525             return userPolicy.mPermissionPolicy;
8526         }
8527     }
8528
8529     @Override
8530     public boolean setPermissionGrantState(ComponentName admin, String packageName,
8531             String permission, int grantState) throws RemoteException {
8532         UserHandle user = mInjector.binderGetCallingUserHandle();
8533         synchronized (this) {
8534             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8535             long ident = mInjector.binderClearCallingIdentity();
8536             try {
8537                 if (getTargetSdk(packageName, user.getIdentifier())
8538                         < android.os.Build.VERSION_CODES.M) {
8539                     return false;
8540                 }
8541                 final PackageManager packageManager = mContext.getPackageManager();
8542                 switch (grantState) {
8543                     case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: {
8544                         packageManager.grantRuntimePermission(packageName, permission, user);
8545                         packageManager.updatePermissionFlags(permission, packageName,
8546                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8547                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8548                     } break;
8549
8550                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: {
8551                         packageManager.revokeRuntimePermission(packageName,
8552                                 permission, user);
8553                         packageManager.updatePermissionFlags(permission, packageName,
8554                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED,
8555                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user);
8556                     } break;
8557
8558                     case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: {
8559                         packageManager.updatePermissionFlags(permission, packageName,
8560                                 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user);
8561                     } break;
8562                 }
8563                 return true;
8564             } catch (SecurityException se) {
8565                 return false;
8566             } finally {
8567                 mInjector.binderRestoreCallingIdentity(ident);
8568             }
8569         }
8570     }
8571
8572     @Override
8573     public int getPermissionGrantState(ComponentName admin, String packageName,
8574             String permission) throws RemoteException {
8575         PackageManager packageManager = mContext.getPackageManager();
8576
8577         UserHandle user = mInjector.binderGetCallingUserHandle();
8578         synchronized (this) {
8579             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8580             long ident = mInjector.binderClearCallingIdentity();
8581             try {
8582                 int granted = mIPackageManager.checkPermission(permission,
8583                         packageName, user.getIdentifier());
8584                 int permFlags = packageManager.getPermissionFlags(permission, packageName, user);
8585                 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED)
8586                         != PackageManager.FLAG_PERMISSION_POLICY_FIXED) {
8587                     // Not controlled by policy
8588                     return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT;
8589                 } else {
8590                     // Policy controlled so return result based on permission grant state
8591                     return granted == PackageManager.PERMISSION_GRANTED
8592                             ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED
8593                             : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED;
8594                 }
8595             } finally {
8596                 mInjector.binderRestoreCallingIdentity(ident);
8597             }
8598         }
8599     }
8600
8601     boolean isPackageInstalledForUser(String packageName, int userHandle) {
8602         try {
8603             PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0,
8604                     userHandle);
8605             return (pi != null) && (pi.applicationInfo.flags != 0);
8606         } catch (RemoteException re) {
8607             throw new RuntimeException("Package manager has died", re);
8608         }
8609     }
8610
8611     @Override
8612     public boolean isProvisioningAllowed(String action) {
8613         if (!mHasFeature) {
8614             return false;
8615         }
8616
8617         final int callingUserId = mInjector.userHandleGetCallingUserId();
8618         if (DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE.equals(action)) {
8619             if (!hasFeatureManagedUsers()) {
8620                 return false;
8621             }
8622             synchronized (this) {
8623                 if (mOwners.hasDeviceOwner()) {
8624                     if (!mInjector.userManagerIsSplitSystemUser()) {
8625                         // Only split-system-user systems support managed-profiles in combination with
8626                         // device-owner.
8627                         return false;
8628                     }
8629                     if (mOwners.getDeviceOwnerUserId() != UserHandle.USER_SYSTEM) {
8630                         // Only system device-owner supports managed-profiles. Non-system device-owner
8631                         // doesn't.
8632                         return false;
8633                     }
8634                     if (callingUserId == UserHandle.USER_SYSTEM) {
8635                         // Managed-profiles cannot be setup on the system user, only regular users.
8636                         return false;
8637                     }
8638                 }
8639             }
8640             if (getProfileOwner(callingUserId) != null) {
8641                 // Managed user cannot have a managed profile.
8642                 return false;
8643             }
8644             final long ident = mInjector.binderClearCallingIdentity();
8645             try {
8646                 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, true)) {
8647                     return false;
8648                 }
8649             } finally {
8650                 mInjector.binderRestoreCallingIdentity(ident);
8651             }
8652             return true;
8653         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE.equals(action)) {
8654             return isDeviceOwnerProvisioningAllowed(callingUserId);
8655         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_USER.equals(action)) {
8656             if (!hasFeatureManagedUsers()) {
8657                 return false;
8658             }
8659             if (!mInjector.userManagerIsSplitSystemUser()) {
8660                 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems.
8661                 return false;
8662             }
8663             if (callingUserId == UserHandle.USER_SYSTEM) {
8664                 // System user cannot be a managed user.
8665                 return false;
8666             }
8667             if (hasUserSetupCompleted(callingUserId)) {
8668                 return false;
8669             }
8670             if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8671                 return false;
8672             }
8673             return true;
8674         } else if (DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE.equals(action)) {
8675             if (!mInjector.userManagerIsSplitSystemUser()) {
8676                 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems.
8677                 return false;
8678             }
8679             return isDeviceOwnerProvisioningAllowed(callingUserId);
8680         }
8681         throw new IllegalArgumentException("Unknown provisioning action " + action);
8682     }
8683
8684     /*
8685      * The device owner can only be set before the setup phase of the primary user has completed,
8686      * except for adb command if no accounts or additional users are present on the device.
8687      */
8688     private synchronized @DeviceOwnerPreConditionCode int checkSetDeviceOwnerPreConditionLocked(
8689             @Nullable ComponentName owner, int deviceOwnerUserId, boolean isAdb) {
8690         if (mOwners.hasDeviceOwner()) {
8691             return CODE_HAS_DEVICE_OWNER;
8692         }
8693         if (mOwners.hasProfileOwner(deviceOwnerUserId)) {
8694             return CODE_USER_HAS_PROFILE_OWNER;
8695         }
8696         if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) {
8697             return CODE_USER_NOT_RUNNING;
8698         }
8699         if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) {
8700             return CODE_HAS_PAIRED;
8701         }
8702         if (isAdb) {
8703             // if shell command runs after user setup completed check device status. Otherwise, OK.
8704             if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8705                 if (!mInjector.userManagerIsSplitSystemUser()) {
8706                     if (mUserManager.getUserCount() > 1) {
8707                         return CODE_NONSYSTEM_USER_EXISTS;
8708                     }
8709                     if (hasIncompatibleAccountsLocked(UserHandle.USER_SYSTEM, owner)) {
8710                         return CODE_ACCOUNTS_NOT_EMPTY;
8711                     }
8712                 } else {
8713                     // STOPSHIP Do proper check in split user mode
8714                 }
8715             }
8716             return CODE_OK;
8717         } else {
8718             if (!mInjector.userManagerIsSplitSystemUser()) {
8719                 // In non-split user mode, DO has to be user 0
8720                 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) {
8721                     return CODE_NOT_SYSTEM_USER;
8722                 }
8723                 // In non-split user mode, only provision DO before setup wizard completes
8724                 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) {
8725                     return CODE_USER_SETUP_COMPLETED;
8726                 }
8727             } else {
8728                 // STOPSHIP Do proper check in split user mode
8729             }
8730             return CODE_OK;
8731         }
8732     }
8733
8734     private boolean isDeviceOwnerProvisioningAllowed(int deviceOwnerUserId) {
8735         synchronized (this) {
8736             return CODE_OK == checkSetDeviceOwnerPreConditionLocked(
8737                     /* owner unknown */ null, deviceOwnerUserId, /* isAdb */ false);
8738         }
8739     }
8740
8741     private boolean hasFeatureManagedUsers() {
8742         try {
8743             return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0);
8744         } catch (RemoteException e) {
8745             return false;
8746         }
8747     }
8748
8749     @Override
8750     public String getWifiMacAddress(ComponentName admin) {
8751         // Make sure caller has DO.
8752         synchronized (this) {
8753             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8754         }
8755
8756         final long ident = mInjector.binderClearCallingIdentity();
8757         try {
8758             final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo();
8759             if (wifiInfo == null) {
8760                 return null;
8761             }
8762             return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null;
8763         } finally {
8764             mInjector.binderRestoreCallingIdentity(ident);
8765         }
8766     }
8767
8768     /**
8769      * Returns the target sdk version number that the given packageName was built for
8770      * in the given user.
8771      */
8772     private int getTargetSdk(String packageName, int userId) {
8773         final ApplicationInfo ai;
8774         try {
8775             ai = mIPackageManager.getApplicationInfo(packageName, 0, userId);
8776             final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion;
8777             return targetSdkVersion;
8778         } catch (RemoteException e) {
8779             // Shouldn't happen
8780             return 0;
8781         }
8782     }
8783
8784     @Override
8785     public boolean isManagedProfile(ComponentName admin) {
8786         synchronized (this) {
8787             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8788         }
8789         final int callingUserId = mInjector.userHandleGetCallingUserId();
8790         final UserInfo user = getUserInfo(callingUserId);
8791         return user != null && user.isManagedProfile();
8792     }
8793
8794     @Override
8795     public boolean isSystemOnlyUser(ComponentName admin) {
8796         synchronized (this) {
8797             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8798         }
8799         final int callingUserId = mInjector.userHandleGetCallingUserId();
8800         return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM;
8801     }
8802
8803     @Override
8804     public void reboot(ComponentName admin) {
8805         Preconditions.checkNotNull(admin);
8806         // Make sure caller has DO.
8807         synchronized (this) {
8808             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
8809         }
8810         long ident = mInjector.binderClearCallingIdentity();
8811         try {
8812             // Make sure there are no ongoing calls on the device.
8813             if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) {
8814                 throw new IllegalStateException("Cannot be called with ongoing call on the device");
8815             }
8816             mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER);
8817         } finally {
8818             mInjector.binderRestoreCallingIdentity(ident);
8819         }
8820     }
8821
8822     @Override
8823     public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) {
8824         if (!mHasFeature) {
8825             return;
8826         }
8827         Preconditions.checkNotNull(who, "ComponentName is null");
8828         final int userHandle = mInjector.userHandleGetCallingUserId();
8829         synchronized (this) {
8830             ActiveAdmin admin = getActiveAdminForUidLocked(who,
8831                     mInjector.binderGetCallingUid());
8832             if (!TextUtils.equals(admin.shortSupportMessage, message)) {
8833                 admin.shortSupportMessage = message;
8834                 saveSettingsLocked(userHandle);
8835             }
8836         }
8837     }
8838
8839     @Override
8840     public CharSequence getShortSupportMessage(@NonNull ComponentName who) {
8841         if (!mHasFeature) {
8842             return null;
8843         }
8844         Preconditions.checkNotNull(who, "ComponentName is null");
8845         synchronized (this) {
8846             ActiveAdmin admin = getActiveAdminForUidLocked(who,
8847                     mInjector.binderGetCallingUid());
8848             return admin.shortSupportMessage;
8849         }
8850     }
8851
8852     @Override
8853     public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) {
8854         if (!mHasFeature) {
8855             return;
8856         }
8857         Preconditions.checkNotNull(who, "ComponentName is null");
8858         final int userHandle = mInjector.userHandleGetCallingUserId();
8859         synchronized (this) {
8860             ActiveAdmin admin = getActiveAdminForUidLocked(who,
8861                     mInjector.binderGetCallingUid());
8862             if (!TextUtils.equals(admin.longSupportMessage, message)) {
8863                 admin.longSupportMessage = message;
8864                 saveSettingsLocked(userHandle);
8865             }
8866         }
8867     }
8868
8869     @Override
8870     public CharSequence getLongSupportMessage(@NonNull ComponentName who) {
8871         if (!mHasFeature) {
8872             return null;
8873         }
8874         Preconditions.checkNotNull(who, "ComponentName is null");
8875         synchronized (this) {
8876             ActiveAdmin admin = getActiveAdminForUidLocked(who,
8877                     mInjector.binderGetCallingUid());
8878             return admin.longSupportMessage;
8879         }
8880     }
8881
8882     @Override
8883     public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8884         if (!mHasFeature) {
8885             return null;
8886         }
8887         Preconditions.checkNotNull(who, "ComponentName is null");
8888         if (!isCallerWithSystemUid()) {
8889             throw new SecurityException("Only the system can query support message for user");
8890         }
8891         synchronized (this) {
8892             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8893             if (admin != null) {
8894                 return admin.shortSupportMessage;
8895             }
8896         }
8897         return null;
8898     }
8899
8900     @Override
8901     public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) {
8902         if (!mHasFeature) {
8903             return null;
8904         }
8905         Preconditions.checkNotNull(who, "ComponentName is null");
8906         if (!isCallerWithSystemUid()) {
8907             throw new SecurityException("Only the system can query support message for user");
8908         }
8909         synchronized (this) {
8910             ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle);
8911             if (admin != null) {
8912                 return admin.longSupportMessage;
8913             }
8914         }
8915         return null;
8916     }
8917
8918     @Override
8919     public void setOrganizationColor(@NonNull ComponentName who, int color) {
8920         if (!mHasFeature) {
8921             return;
8922         }
8923         Preconditions.checkNotNull(who, "ComponentName is null");
8924         final int userHandle = mInjector.userHandleGetCallingUserId();
8925         enforceManagedProfile(userHandle, "set organization color");
8926         synchronized (this) {
8927             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8928                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8929             admin.organizationColor = color;
8930             saveSettingsLocked(userHandle);
8931         }
8932     }
8933
8934     @Override
8935     public void setOrganizationColorForUser(int color, int userId) {
8936         if (!mHasFeature) {
8937             return;
8938         }
8939         enforceFullCrossUsersPermission(userId);
8940         enforceManageUsers();
8941         enforceManagedProfile(userId, "set organization color");
8942         synchronized (this) {
8943             ActiveAdmin admin = getProfileOwnerAdminLocked(userId);
8944             admin.organizationColor = color;
8945             saveSettingsLocked(userId);
8946         }
8947     }
8948
8949     @Override
8950     public int getOrganizationColor(@NonNull ComponentName who) {
8951         if (!mHasFeature) {
8952             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8953         }
8954         Preconditions.checkNotNull(who, "ComponentName is null");
8955         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color");
8956         synchronized (this) {
8957             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8958                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8959             return admin.organizationColor;
8960         }
8961     }
8962
8963     @Override
8964     public int getOrganizationColorForUser(int userHandle) {
8965         if (!mHasFeature) {
8966             return ActiveAdmin.DEF_ORGANIZATION_COLOR;
8967         }
8968         enforceFullCrossUsersPermission(userHandle);
8969         enforceManagedProfile(userHandle, "get organization color");
8970         synchronized (this) {
8971             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
8972             return (profileOwner != null)
8973                     ? profileOwner.organizationColor
8974                     : ActiveAdmin.DEF_ORGANIZATION_COLOR;
8975         }
8976     }
8977
8978     @Override
8979     public void setOrganizationName(@NonNull ComponentName who, CharSequence text) {
8980         if (!mHasFeature) {
8981             return;
8982         }
8983         Preconditions.checkNotNull(who, "ComponentName is null");
8984         final int userHandle = mInjector.userHandleGetCallingUserId();
8985         enforceManagedProfile(userHandle, "set organization name");
8986         synchronized (this) {
8987             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
8988                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
8989             if (!TextUtils.equals(admin.organizationName, text)) {
8990                 admin.organizationName = (text == null || text.length() == 0)
8991                         ? null : text.toString();
8992                 saveSettingsLocked(userHandle);
8993             }
8994         }
8995     }
8996
8997     @Override
8998     public CharSequence getOrganizationName(@NonNull ComponentName who) {
8999         if (!mHasFeature) {
9000             return null;
9001         }
9002         Preconditions.checkNotNull(who, "ComponentName is null");
9003         enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name");
9004         synchronized(this) {
9005             ActiveAdmin admin = getActiveAdminForCallerLocked(who,
9006                     DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9007             return admin.organizationName;
9008         }
9009     }
9010
9011     @Override
9012     public CharSequence getOrganizationNameForUser(int userHandle) {
9013         if (!mHasFeature) {
9014             return null;
9015         }
9016         enforceFullCrossUsersPermission(userHandle);
9017         enforceManagedProfile(userHandle, "get organization name");
9018         synchronized (this) {
9019             ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle);
9020             return (profileOwner != null)
9021                     ? profileOwner.organizationName
9022                     : null;
9023         }
9024     }
9025
9026     @Override
9027     public void setAffiliationIds(ComponentName admin, List<String> ids) {
9028         final Set<String> affiliationIds = new ArraySet<String>(ids);
9029         final int callingUserId = mInjector.userHandleGetCallingUserId();
9030
9031         synchronized (this) {
9032             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER);
9033             getUserData(callingUserId).mAffiliationIds = affiliationIds;
9034             saveSettingsLocked(callingUserId);
9035             if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) {
9036                 // Affiliation ids specified by the device owner are additionally stored in
9037                 // UserHandle.USER_SYSTEM's DevicePolicyData.
9038                 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds;
9039                 saveSettingsLocked(UserHandle.USER_SYSTEM);
9040             }
9041         }
9042     }
9043
9044     @Override
9045     public boolean isAffiliatedUser() {
9046         final int callingUserId = mInjector.userHandleGetCallingUserId();
9047
9048         synchronized (this) {
9049             if (mOwners.getDeviceOwnerUserId() == callingUserId) {
9050                 // The user that the DO is installed on is always affiliated.
9051                 return true;
9052             }
9053             final ComponentName profileOwner = getProfileOwner(callingUserId);
9054             if (profileOwner == null
9055                     || !profileOwner.getPackageName().equals(mOwners.getDeviceOwnerPackageName())) {
9056                 return false;
9057             }
9058             final Set<String> userAffiliationIds = getUserData(callingUserId).mAffiliationIds;
9059             final Set<String> deviceAffiliationIds =
9060                     getUserData(UserHandle.USER_SYSTEM).mAffiliationIds;
9061             for (String id : userAffiliationIds) {
9062                 if (deviceAffiliationIds.contains(id)) {
9063                     return true;
9064                 }
9065             }
9066         }
9067         return false;
9068     }
9069
9070     private synchronized void disableDeviceOwnerManagedSingleUserFeaturesIfNeeded() {
9071         if (!isDeviceOwnerManagedSingleUserDevice()) {
9072             mInjector.securityLogSetLoggingEnabledProperty(false);
9073             Slog.w(LOG_TAG, "Security logging turned off as it's no longer a single user device.");
9074             if (mOwners.hasDeviceOwner()) {
9075                 setBackupServiceEnabledInternal(false);
9076                 Slog.w(LOG_TAG, "Backup is off as it's a managed device that has more that one user.");
9077             }
9078         }
9079     }
9080
9081     @Override
9082     public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) {
9083         Preconditions.checkNotNull(admin);
9084         ensureDeviceOwnerManagingSingleUser(admin);
9085
9086         synchronized (this) {
9087             if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) {
9088                 return;
9089             }
9090             mInjector.securityLogSetLoggingEnabledProperty(enabled);
9091             if (enabled) {
9092                 mSecurityLogMonitor.start();
9093             } else {
9094                 mSecurityLogMonitor.stop();
9095             }
9096         }
9097     }
9098
9099     @Override
9100     public boolean isSecurityLoggingEnabled(ComponentName admin) {
9101         Preconditions.checkNotNull(admin);
9102         synchronized (this) {
9103             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9104             return mInjector.securityLogGetLoggingEnabledProperty();
9105         }
9106     }
9107
9108     @Override
9109     public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) {
9110         Preconditions.checkNotNull(admin);
9111         ensureDeviceOwnerManagingSingleUser(admin);
9112
9113         if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs)) {
9114             return null;
9115         }
9116
9117         ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>();
9118         try {
9119             SecurityLog.readPreviousEvents(output);
9120             return new ParceledListSlice<SecurityEvent>(output);
9121         } catch (IOException e) {
9122             Slog.w(LOG_TAG, "Fail to read previous events" , e);
9123             return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList());
9124         }
9125     }
9126
9127     @Override
9128     public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) {
9129         Preconditions.checkNotNull(admin);
9130         ensureDeviceOwnerManagingSingleUser(admin);
9131
9132         List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs();
9133         return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null;
9134     }
9135
9136     private void enforceCanManageDeviceAdmin() {
9137         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS,
9138                 null);
9139     }
9140
9141     private void enforceCanManageProfileAndDeviceOwners() {
9142         mContext.enforceCallingOrSelfPermission(
9143                 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null);
9144     }
9145
9146     @Override
9147     public boolean isUninstallInQueue(final String packageName) {
9148         enforceCanManageDeviceAdmin();
9149         final int userId = mInjector.userHandleGetCallingUserId();
9150         Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9151         synchronized (this) {
9152             return mPackagesToRemove.contains(packageUserPair);
9153         }
9154     }
9155
9156     @Override
9157     public void uninstallPackageWithActiveAdmins(final String packageName) {
9158         enforceCanManageDeviceAdmin();
9159         Preconditions.checkArgument(!TextUtils.isEmpty(packageName));
9160
9161         final int userId = mInjector.userHandleGetCallingUserId();
9162
9163         enforceUserUnlocked(userId);
9164
9165         final ComponentName profileOwner = getProfileOwner(userId);
9166         if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) {
9167             throw new IllegalArgumentException("Cannot uninstall a package with a profile owner");
9168         }
9169
9170         final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false);
9171         if (getDeviceOwnerUserId() == userId && deviceOwner != null
9172                 && packageName.equals(deviceOwner.getPackageName())) {
9173             throw new IllegalArgumentException("Cannot uninstall a package with a device owner");
9174         }
9175
9176         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9177         synchronized (this) {
9178             mPackagesToRemove.add(packageUserPair);
9179         }
9180
9181         // All active admins on the user.
9182         final List<ComponentName> allActiveAdmins = getActiveAdmins(userId);
9183
9184         // Active admins in the target package.
9185         final List<ComponentName> packageActiveAdmins = new ArrayList<>();
9186         if (allActiveAdmins != null) {
9187             for (ComponentName activeAdmin : allActiveAdmins) {
9188                 if (packageName.equals(activeAdmin.getPackageName())) {
9189                     packageActiveAdmins.add(activeAdmin);
9190                     removeActiveAdmin(activeAdmin, userId);
9191                 }
9192             }
9193         }
9194         if (packageActiveAdmins.size() == 0) {
9195             startUninstallIntent(packageName, userId);
9196         } else {
9197             mHandler.postDelayed(new Runnable() {
9198                 @Override
9199                 public void run() {
9200                     for (ComponentName activeAdmin : packageActiveAdmins) {
9201                         removeAdminArtifacts(activeAdmin, userId);
9202                     }
9203                     startUninstallIntent(packageName, userId);
9204                 }
9205             }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway.
9206         }
9207     }
9208
9209     @Override
9210     public boolean isDeviceProvisioned() {
9211         return !TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT));
9212     }
9213
9214     private void removePackageIfRequired(final String packageName, final int userId) {
9215         if (!packageHasActiveAdmins(packageName, userId)) {
9216             // Will not do anything if uninstall was not requested or was already started.
9217             startUninstallIntent(packageName, userId);
9218         }
9219     }
9220
9221     private void startUninstallIntent(final String packageName, final int userId) {
9222         final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId);
9223         synchronized (this) {
9224             if (!mPackagesToRemove.contains(packageUserPair)) {
9225                 // Do nothing if uninstall was not requested or was already started.
9226                 return;
9227             }
9228             mPackagesToRemove.remove(packageUserPair);
9229         }
9230         try {
9231             if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) {
9232                 // Package does not exist. Nothing to do.
9233                 return;
9234             }
9235         } catch (RemoteException re) {
9236             Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info");
9237         }
9238
9239         try { // force stop the package before uninstalling
9240             mInjector.getIActivityManager().forceStopPackage(packageName, userId);
9241         } catch (RemoteException re) {
9242             Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package");
9243         }
9244         final Uri packageURI = Uri.parse("package:" + packageName);
9245         final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
9246         uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
9247         mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId));
9248     }
9249
9250     /**
9251      * Removes the admin from the policy. Ideally called after the admin's
9252      * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed.
9253      *
9254      * @param adminReceiver The admin to remove
9255      * @param userHandle The user for which this admin has to be removed.
9256      */
9257     private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) {
9258         synchronized (this) {
9259             final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle);
9260             if (admin == null) {
9261                 return;
9262             }
9263             final DevicePolicyData policy = getUserData(userHandle);
9264             final boolean doProxyCleanup = admin.info.usesPolicy(
9265                     DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY);
9266             policy.mAdminList.remove(admin);
9267             policy.mAdminMap.remove(adminReceiver);
9268             validatePasswordOwnerLocked(policy);
9269             if (doProxyCleanup) {
9270                 resetGlobalProxyLocked(policy);
9271             }
9272             saveSettingsLocked(userHandle);
9273             updateMaximumTimeToLockLocked(userHandle);
9274             policy.mRemovingAdmins.remove(adminReceiver);
9275
9276             Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle);
9277         }
9278         // The removed admin might have disabled camera, so update user
9279         // restrictions.
9280         pushUserRestrictions(userHandle);
9281     }
9282
9283     @Override
9284     public void setDeviceProvisioningConfigApplied() {
9285         enforceManageUsers();
9286         synchronized (this) {
9287             DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9288             policy.mDeviceProvisioningConfigApplied = true;
9289             saveSettingsLocked(UserHandle.USER_SYSTEM);
9290         }
9291     }
9292
9293     @Override
9294     public boolean isDeviceProvisioningConfigApplied() {
9295         enforceManageUsers();
9296         synchronized (this) {
9297             final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM);
9298             return policy.mDeviceProvisioningConfigApplied;
9299         }
9300     }
9301
9302     /**
9303      * Return true if a given user has any accounts that'll prevent installing a device or profile
9304      * owner {@code owner}.
9305      * - If the user has no accounts, then return false.
9306      * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true.
9307      * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have
9308      *   ..._DISALLOWED, return true.
9309      * - Otherwise return false.
9310      */
9311     private boolean hasIncompatibleAccountsLocked(int userId, @Nullable ComponentName owner) {
9312         final long token = mInjector.binderClearCallingIdentity();
9313         try {
9314             final AccountManager am = AccountManager.get(mContext);
9315             final Account accounts[] = am.getAccountsAsUser(userId);
9316             if (accounts.length == 0) {
9317                 return false;
9318             }
9319             final String[] feature_allow =
9320                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED };
9321             final String[] feature_disallow =
9322                     { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED };
9323
9324             // Even if we find incompatible accounts along the way, we still check all accounts
9325             // for logging.
9326             boolean compatible = true;
9327             for (Account account : accounts) {
9328                 if (hasAccountFeatures(am, account, feature_disallow)) {
9329                     Log.e(LOG_TAG, account + " has " + feature_disallow[0]);
9330                     compatible = false;
9331                 }
9332                 if (!hasAccountFeatures(am, account, feature_allow)) {
9333                     Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]);
9334                     compatible = false;
9335                 }
9336             }
9337             if (compatible) {
9338                 Log.w(LOG_TAG, "All accounts are compatible");
9339             } else {
9340                 Log.e(LOG_TAG, "Found incompatible accounts");
9341             }
9342
9343             // Then check if the owner is test-only.
9344             String log;
9345             if (owner == null) {
9346                 // Owner is unknown.  Suppose it's not test-only
9347                 compatible = false;
9348                 log = "Only test-only device/profile owner can be installed with accounts";
9349             } else if (isAdminTestOnlyLocked(owner, userId)) {
9350                 if (compatible) {
9351                     log = "Installing test-only owner " + owner;
9352                 } else {
9353                     log = "Can't install test-only owner " + owner + " with incompatible accounts";
9354                 }
9355             } else {
9356                 compatible = false;
9357                 log = "Can't install non test-only owner " + owner + " with accounts";
9358             }
9359             if (compatible) {
9360                 Log.w(LOG_TAG, log);
9361             } else {
9362                 Log.e(LOG_TAG, log);
9363             }
9364             return !compatible;
9365         } finally {
9366             mInjector.binderRestoreCallingIdentity(token);
9367         }
9368     }
9369
9370     private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) {
9371         try {
9372             return am.hasFeatures(account, features, null, null).getResult();
9373         } catch (Exception e) {
9374             Log.w(LOG_TAG, "Failed to get account feature", e);
9375             return false;
9376         }
9377     }
9378
9379     @Override
9380     public void setBackupServiceEnabled(ComponentName admin, boolean enabled) {
9381         Preconditions.checkNotNull(admin);
9382         if (!mHasFeature) {
9383             return;
9384         }
9385         ensureDeviceOwnerManagingSingleUser(admin);
9386         setBackupServiceEnabledInternal(enabled);
9387     }
9388
9389     private synchronized void setBackupServiceEnabledInternal(boolean enabled) {
9390         long ident = mInjector.binderClearCallingIdentity();
9391         try {
9392             IBackupManager ibm = mInjector.getIBackupManager();
9393             if (ibm != null) {
9394                 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled);
9395             }
9396         } catch (RemoteException e) {
9397             throw new IllegalStateException(
9398                 "Failed " + (enabled ? "" : "de") + "activating backup service.", e);
9399         } finally {
9400             mInjector.binderRestoreCallingIdentity(ident);
9401         }
9402     }
9403
9404     @Override
9405     public boolean isBackupServiceEnabled(ComponentName admin) {
9406         Preconditions.checkNotNull(admin);
9407         if (!mHasFeature) {
9408             return true;
9409         }
9410         synchronized (this) {
9411             getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
9412             try {
9413                 IBackupManager ibm = mInjector.getIBackupManager();
9414                 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM);
9415             } catch (RemoteException e) {
9416                 throw new IllegalStateException("Failed requesting backup service state.", e);
9417             }
9418         }
9419     }
9420 }