OSDN Git Service

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