OSDN Git Service

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