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