OSDN Git Service

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