OSDN Git Service

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