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