OSDN Git Service

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