OSDN Git Service

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