OSDN Git Service

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