DevicePolicyManagerService.java revision 424dd39e256b880b0a18d8570daf399885a7567b
1f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross/* 2f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Copyright (C) 2010 The Android Open Source Project 3f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * 4f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Licensed under the Apache License, Version 2.0 (the "License"); 5f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * you may not use this file except in compliance with the License. 6f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * You may obtain a copy of the License at 7f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * 8f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * http://www.apache.org/licenses/LICENSE-2.0 9f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * 10f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * Unless required by applicable law or agreed to in writing, software 11f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * distributed under the License is distributed on an "AS IS" BASIS, 12f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * See the License for the specific language governing permissions and 14f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross * limitations under the License. 15f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross */ 16f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme 176c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzynpackage com.android.server.devicepolicy; 18f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross 192db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport static android.Manifest.permission.BIND_DEVICE_ADMIN; 20f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.Manifest.permission.MANAGE_CA_CERTIFICATES; 21f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_ACCOUNTS_NOT_EMPTY; 22ad5f6c475934ac6a658a203069a9f055540946e7Felipe Lemeimport static android.app.admin.DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED; 23f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE; 246e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Lemeimport static android.app.admin.DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED; 25ad5f6c475934ac6a658a203069a9f055540946e7Felipe Lemeimport static android.app.admin.DevicePolicyManager.CODE_HAS_DEVICE_OWNER; 26635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport static android.app.admin.DevicePolicyManager.CODE_HAS_PAIRED; 278f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzynimport static android.app.admin.DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED; 28f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_NONSYSTEM_USER_EXISTS; 29f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER; 306e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Lemeimport static android.app.admin.DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT; 31f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_OK; 327dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport static android.app.admin.DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 33f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_SYSTEM_USER; 34f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_USER_HAS_PROFILE_OWNER; 35f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_USER_NOT_RUNNING; 36f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.CODE_USER_SETUP_COMPLETED; 37f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS; 38f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.DELEGATION_BLOCK_UNINSTALL; 3996c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Lemeimport static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL; 4096c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Lemeimport static android.app.admin.DevicePolicyManager.DELEGATION_ENABLE_SYSTEM_APP; 419dc117c415d0df0a3acd900709d05deabe975704Elliott Hughesimport static android.app.admin.DevicePolicyManager.DELEGATION_KEEP_UNINSTALLED_PACKAGES; 42058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kallaimport static android.app.admin.DevicePolicyManager.DELEGATION_PACKAGE_ACCESS; 43aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampeimport static android.app.admin.DevicePolicyManager.DELEGATION_PERMISSION_GRANT; 446f674aefab201fbf9141aabbb603bbfc84771927Felipe Lemeimport static android.app.admin.DevicePolicyManager.PASSWORD_QUALITY_COMPLEX; 456f674aefab201fbf9141aabbb603bbfc84771927Felipe Lemeimport static android.app.admin.DevicePolicyManager.PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 46f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static android.app.admin.DevicePolicyManager.WIPE_EXTERNAL_STORAGE; 4775876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Lemeimport static android.app.admin.DevicePolicyManager.WIPE_RESET_PROTECTION_DATA; 486c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzynimport static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 496c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn 50f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static com.android.internal.logging.nano.MetricsProto.MetricsEvent.PROVISIONING_ENTRY_POINT_ADB; 51f029297f673ae06d219bd727a318a48b885db6fdFelipe Lemeimport static com.android.internal.widget.LockPatternUtils.StrongAuthTracker.STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW; 5275876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Lemeimport static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 53f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport static org.xmlpull.v1.XmlPullParser.END_TAG; 546e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Lemeimport static org.xmlpull.v1.XmlPullParser.TEXT; 55cb7ef82aef52e766c45f65f446d02fd9356afea4Steven Moreland 56cb7ef82aef52e766c45f65f446d02fd9356afea4Steven Morelandimport android.Manifest.permission; 5747e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.accessibilityservice.AccessibilityServiceInfo; 5847e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.accounts.Account; 5947e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.accounts.AccountManager; 6047e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.annotation.NonNull; 6147e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.annotation.Nullable; 6247e9be2d71c5eca9002e289c98e8bbc20dffc073Felipe Lemeimport android.annotation.UserIdInt; 63f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport android.app.Activity; 64f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport android.app.ActivityManager; 65f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport android.app.ActivityManagerInternal; 66f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Crossimport android.app.AlarmManager; 671d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemeimport android.app.AppGlobals; 681d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemeimport android.app.IActivityManager; 69635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.app.IApplicationThread; 70635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.app.IServiceConnection; 7178f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Lemeimport android.app.Notification; 722a83daa8a3e1eab292dc1464bbe78f025f4bc0e9Todd Poynorimport android.app.NotificationManager; 737d0a762ecaf9f4d005f0f6db913034c2e084d362Mark Salyzynimport android.app.PendingIntent; 742a83daa8a3e1eab292dc1464bbe78f025f4bc0e9Todd Poynorimport android.app.StatusBarManager; 75341938b446576ebf60865d8b6e5e6175f47766d0Wei Liuimport android.app.admin.DeviceAdminInfo; 76e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Lemeimport android.app.admin.DeviceAdminReceiver; 77d6ab01105bbd80dfa2fc2debc8e31d6422c378eeMark Salyzynimport android.app.admin.DevicePolicyManager; 784d42dea08915ccbb61ca05903af5330d02d66755Mark Salyzynimport android.app.admin.DevicePolicyManagerInternal; 79d2991962b7120319a4fa63f1a93b100adaad5dbeDavid Brazdilimport android.app.admin.IDevicePolicyManager; 80d2991962b7120319a4fa63f1a93b100adaad5dbeDavid Brazdilimport android.app.admin.NetworkEvent; 817dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.admin.PasswordMetrics; 827dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.admin.SystemUpdateInfo; 837dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.admin.SecurityLog; 847dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.admin.SecurityLog.SecurityEvent; 857dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.admin.SystemUpdatePolicy; 860816520c5cd60519d8e221ed92497aa5464e3039Erik Klineimport android.app.backup.IBackupManager; 877dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.app.trust.TrustManager; 887dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.BroadcastReceiver; 897dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.ComponentName; 907dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.Context; 917dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.Intent; 927dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.IntentFilter; 937dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.pm.ActivityInfo; 947dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.content.pm.ApplicationInfo; 95e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemeimport android.content.pm.IPackageManager; 96e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemeimport android.content.pm.PackageInfo; 97678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.PackageManager; 98678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.PackageManager.NameNotFoundException; 99678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.PackageManagerInternal; 100678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.ParceledListSlice; 101678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.ResolveInfo; 102bda15a00929b836a53bf03473b1ec36285e5944bFelipe Lemeimport android.content.pm.ServiceInfo; 103678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.StringParceledListSlice; 104678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.pm.UserInfo; 105678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.content.res.Resources; 106678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.database.ContentObserver; 107678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.graphics.Bitmap; 108678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport android.graphics.Color; 109e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Lemeimport android.media.AudioManager; 110e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemeimport android.media.IAudioService; 111e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemeimport android.net.ConnectivityManager; 112e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Lemeimport android.net.IIpConnectivityMetrics; 1137440ddb786b7732478173fe142512dba4e2a8dfdSteven Morelandimport android.net.ProxyInfo; 1147440ddb786b7732478173fe142512dba4e2a8dfdSteven Morelandimport android.net.Uri; 11569ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huberimport android.net.metrics.IpConnectivityLog; 1167440ddb786b7732478173fe142512dba4e2a8dfdSteven Morelandimport android.net.wifi.WifiInfo; 1179ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Lemeimport android.net.wifi.WifiManager; 11896c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Lemeimport android.os.Binder; 119d071c6802a03031b26de7b92a76d03849681149bFelipe Lemeimport android.os.Build; 120b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kallaimport android.os.Bundle; 121b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kallaimport android.os.Environment; 1229ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Lemeimport android.os.FileUtils; 123f029297f673ae06d219bd727a318a48b885db6fdFelipe Lemeimport android.os.Handler; 124f029297f673ae06d219bd727a318a48b885db6fdFelipe Lemeimport android.os.IBinder; 1253d305a18f771f293b6196f95eeb41c098e7e051fFelipe Lemeimport android.os.Looper; 1263d305a18f771f293b6196f95eeb41c098e7e051fFelipe Lemeimport android.os.ParcelFileDescriptor; 1277dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.PersistableBundle; 128bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Lemeimport android.os.PowerManager; 1297dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.PowerManagerInternal; 1307dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.Process; 13154bcc5ffd5a79f4f194089c58d3de571532bf39bChristopher Ferrisimport android.os.RecoverySystem; 13254bcc5ffd5a79f4f194089c58d3de571532bf39bChristopher Ferrisimport android.os.RemoteCallback; 1337dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.RemoteException; 1343d305a18f771f293b6196f95eeb41c098e7e051fFelipe Lemeimport android.os.ServiceManager; 1351d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemeimport android.os.SystemClock; 1363d305a18f771f293b6196f95eeb41c098e7e051fFelipe Lemeimport android.os.SystemProperties; 1377dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.UserHandle; 1383d305a18f771f293b6196f95eeb41c098e7e051fFelipe Lemeimport android.os.UserManager; 1397dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.UserManagerInternal; 1407dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.os.storage.StorageManager; 1417dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.provider.ContactsContract.QuickContact; 1427dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.provider.ContactsInternal; 1437dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferrisimport android.provider.Settings; 144635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.security.IKeyChainAliasCallback; 1454c2d66379753e2b7680811726424026b9e54b18aFelipe Lemeimport android.security.IKeyChainService; 146635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.security.KeyChain; 147635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.security.KeyChain.KeyChainConnection; 148635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.service.persistentdata.PersistentDataBlockManager; 149635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.telephony.TelephonyManager; 150f0922cc1786c0c2fbf44c10b0005243ecbb4227dNick Kralevichimport android.text.TextUtils; 151635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.ArrayMap; 152635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.ArraySet; 153635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.Log; 154cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Lemeimport android.util.Pair; 155635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.Slog; 156635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.SparseArray; 157635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.util.Xml; 158635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.view.IWindowManager; 159635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.view.accessibility.AccessibilityManager; 160635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport android.view.accessibility.IAccessibilityManager; 161f0922cc1786c0c2fbf44c10b0005243ecbb4227dNick Kralevichimport android.view.inputmethod.InputMethodInfo; 1621d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemeimport android.view.inputmethod.InputMethodManager; 163635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Leme 164635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.R; 165cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Lemeimport com.android.internal.annotations.GuardedBy; 166635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.annotations.VisibleForTesting; 167635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.logging.MetricsLogger; 168635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.messages.nano.SystemMessageProto.SystemMessage; 169635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.notification.SystemNotificationChannels; 170635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.os.BackgroundThread; 1711d486fe3847c831b9d57843cda209ed86853ee21Felipe Lemeimport com.android.internal.statusbar.IStatusBarService; 172678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport com.android.internal.util.DumpUtils; 173635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.util.FastXmlSerializer; 17446b85da716a32f285fe1222e9978beacc8697d09Felipe Lemeimport com.android.internal.util.JournaledFile; 175678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport com.android.internal.util.Preconditions; 176678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Lemeimport com.android.internal.util.XmlUtils; 177635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.internal.widget.LockPatternUtils; 178635ca31754ae734b0c540ac5600d58ae55cd4237Felipe Lemeimport com.android.server.LocalServices; 1792db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport com.android.server.SystemService; 1802db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport com.android.server.devicepolicy.DevicePolicyManagerService.ActiveAdmin.TrustAgentInfo; 1812db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport com.android.server.pm.UserRestrictionsUtils; 1822db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport com.google.android.collect.Sets; 1832db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg 1842db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport org.xmlpull.v1.XmlPullParser; 1852db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport org.xmlpull.v1.XmlPullParserException; 1862db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport org.xmlpull.v1.XmlSerializer; 1872db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg 1882db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.File; 1892db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.FileDescriptor; 1902db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.FileInputStream; 1912db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.FileNotFoundException; 1922db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.FileOutputStream; 1932db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.IOException; 1942db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.io.PrintWriter; 195b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Lemeimport java.nio.charset.StandardCharsets; 1962db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.text.DateFormat; 1972db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.util.ArrayList; 1982db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.util.Arrays; 1992db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.util.Collection; 2002db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevågimport java.util.Collections; 201068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.Date; 202068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.List; 203068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.Map.Entry; 204068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.Set; 205068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.concurrent.TimeUnit; 206068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianimport java.util.concurrent.atomic.AtomicBoolean; 207068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 208068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian/** 209068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian * Implementation of the device policy APIs. 210068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian */ 211068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qianpublic class DevicePolicyManagerService extends IDevicePolicyManager.Stub { 212068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 213afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian protected static final String LOG_TAG = "DevicePolicyManager"; 214afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 215068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final boolean VERBOSE_LOG = false; // DO NOT SUBMIT WITH TRUE 216068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 217068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String DEVICE_POLICIES_XML = "device_policies.xml"; 2181d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 2191d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final String TAG_ACCEPTED_CA_CERTIFICATES = "accepted-ca-certificate"; 220068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 221068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_LOCK_TASK_COMPONENTS = "lock-task-component"; 222068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 223068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_STATUS_BAR = "statusbar"; 22461ffcf73d50dbed5b52265e79bb73abf1849324dEcco Park 225068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_DISABLED = "disabled"; 226068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 227afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String ATTR_NAME = "name"; 228afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 229afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML = 230afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian "do-not-ask-credentials-on-boot"; 231afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 232afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String TAG_AFFILIATION_ID = "affiliation-id"; 233afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 234068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_LAST_SECURITY_LOG_RETRIEVAL = "last-security-log-retrieval"; 235068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 236b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme private static final String TAG_LAST_BUG_REPORT_REQUEST = "last-bug-report-request"; 23730dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme 238068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_LAST_NETWORK_LOG_RETRIEVAL = "last-network-log-retrieval"; 239068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 240068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_ADMIN_BROADCAST_PENDING = "admin-broadcast-pending"; 241068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 242afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String TAG_CURRENT_INPUT_METHOD_SET = "current-ime-set"; 243afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 244afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String TAG_OWNER_INSTALLED_CA_CERT = "owner-installed-ca-cert"; 245afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 246afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String ATTR_ID = "id"; 247afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 248afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String ATTR_VALUE = "value"; 249afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 250afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian private static final String ATTR_ALIAS = "alias"; 251afc38fe263c0997385529d72d9211189b3d6d075Zhengyin Qian 252068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_INITIALIZATION_BUNDLE = "initialization-bundle"; 253068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 254068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String TAG_PASSWORD_TOKEN_HANDLE = "password-token"; 255068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 256068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final int REQUEST_EXPIRE_PASSWORD = 5571; 257068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 258068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final long MS_PER_DAY = TimeUnit.DAYS.toMillis(1); 259068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 260068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final long EXPIRATION_GRACE_PERIOD_MS = 5 * MS_PER_DAY; // 5 days, in ms 261068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 262068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ACTION_EXPIRED_PASSWORD_NOTIFICATION 263068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian = "com.android.server.ACTION_EXPIRED_PASSWORD_NOTIFICATION"; 264068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 265068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_PERMISSION_PROVIDER = "permission-provider"; 266068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_SETUP_COMPLETE = "setup-complete"; 267068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_PROVISIONING_STATE = "provisioning-state"; 268068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_PERMISSION_POLICY = "permission-policy"; 269068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED = 270068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian "device-provisioning-config-applied"; 271068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_DEVICE_PAIRED = "device-paired"; 272068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_DELEGATED_CERT_INSTALLER = "delegated-cert-installer"; 273068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String ATTR_APPLICATION_RESTRICTIONS_MANAGER 274068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian = "application-restrictions-manager"; 275068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 276068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian // Comprehensive list of delegations. 277068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String DELEGATIONS[] = { 278068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_CERT_INSTALL, 279068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_APP_RESTRICTIONS, 280068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_BLOCK_UNINSTALL, 281068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_ENABLE_SYSTEM_APP, 282068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_KEEP_UNINSTALLED_PACKAGES, 283068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_PACKAGE_ACCESS, 284068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian DELEGATION_PERMISSION_GRANT 285068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian }; 286068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 287068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian /** 288068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian * System property whose value is either "true" or "false", indicating whether 289068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian * device owner is present. 2901d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme */ 291068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final String PROPERTY_DEVICE_OWNER_PRESENT = "ro.device_owner"; 292068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 293068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final int STATUS_BAR_DISABLE_MASK = 294068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian StatusBarManager.DISABLE_EXPAND | 295068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian StatusBarManager.DISABLE_NOTIFICATION_ICONS | 296068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian StatusBarManager.DISABLE_NOTIFICATION_ALERTS | 297068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian StatusBarManager.DISABLE_SEARCH; 298068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 299068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final int STATUS_BAR_DISABLE2_MASK = 300068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian StatusBarManager.DISABLE2_QUICK_SETTINGS; 301068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian 302068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final Set<String> SECURE_SETTINGS_WHITELIST; 303068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final Set<String> SECURE_SETTINGS_DEVICEOWNER_WHITELIST; 304068ecc731ec96f1fd1a0819dfed642c510ea69bcZhengyin Qian private static final Set<String> GLOBAL_SETTINGS_WHITELIST; 305efd7e27569b69ed854ed75fca40fc638e3c0268bFelipe Leme private static final Set<String> GLOBAL_SETTINGS_DEPRECATED; 3061d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme static { 3071d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme SECURE_SETTINGS_WHITELIST = new ArraySet<>(); 30871a74ac75c8687195d27642fa0db31a796102c59Felipe Leme SECURE_SETTINGS_WHITELIST.add(Settings.Secure.DEFAULT_INPUT_METHOD); 30971a74ac75c8687195d27642fa0db31a796102c59Felipe Leme SECURE_SETTINGS_WHITELIST.add(Settings.Secure.SKIP_FIRST_USE_HINTS); 310bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme SECURE_SETTINGS_WHITELIST.add(Settings.Secure.INSTALL_NON_MARKET_APPS); 31114e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme 31214e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme SECURE_SETTINGS_DEVICEOWNER_WHITELIST = new ArraySet<>(); 31314e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme SECURE_SETTINGS_DEVICEOWNER_WHITELIST.addAll(SECURE_SETTINGS_WHITELIST); 31414e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme SECURE_SETTINGS_DEVICEOWNER_WHITELIST.add(Settings.Secure.LOCATION_MODE); 31571a74ac75c8687195d27642fa0db31a796102c59Felipe Leme 31671a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST = new ArraySet<>(); 31771a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.ADB_ENABLED); 31871a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME); 31971a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.AUTO_TIME_ZONE); 32071a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.DATA_ROAMING); 32171a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.USB_MASS_STORAGE_ENABLED); 32271a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_SLEEP_POLICY); 32371a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.STAY_ON_WHILE_PLUGGED_IN); 32471a74ac75c8687195d27642fa0db31a796102c59Felipe Leme GLOBAL_SETTINGS_WHITELIST.add(Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN); 32514e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme 32614e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme GLOBAL_SETTINGS_DEPRECATED = new ArraySet<>(); 327b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.BLUETOOTH_ON); 32830dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.DEVELOPMENT_SETTINGS_ENABLED); 32914e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.MODE_RINGER); 330c7fe8fe5b525a1a071af92f3ebbeef2f6d4b06afFelipe Leme GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.NETWORK_PREFERENCE); 33130dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme GLOBAL_SETTINGS_DEPRECATED.add(Settings.Global.WIFI_ON); 33230dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme } 333b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme 33430dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme /** 33530dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme * Keyguard features that when set on a profile affect the profile content or challenge only. 33614e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme * These cannot be set on the managed profile's parent DPM instance 3371d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme */ 33814e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme private static final int PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY = 33971a74ac75c8687195d27642fa0db31a796102c59Felipe Leme DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS; 34014e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme 34114e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme /** Keyguard features that are allowed to be set on a managed profile */ 34214e034a02ec34b2c76afb06975bdfc943a9b5607Felipe Leme private static final int PROFILE_KEYGUARD_FEATURES = 34371a74ac75c8687195d27642fa0db31a796102c59Felipe Leme PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER | PROFILE_KEYGUARD_FEATURES_PROFILE_ONLY; 34471a74ac75c8687195d27642fa0db31a796102c59Felipe Leme 34571a74ac75c8687195d27642fa0db31a796102c59Felipe Leme private static final int DEVICE_ADMIN_DEACTIVATE_TIMEOUT = 10000; 346efd7e27569b69ed854ed75fca40fc638e3c0268bFelipe Leme 347f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme /** 348341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu * Minimum timeout in milliseconds after which unlocking with weak auth times out, 349341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu * i.e. the user has to use a strong authentication method like password, PIN or pattern. 350341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu */ 3511d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1); 3521d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 3531d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme /** 354341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu * Strings logged with {@link 355341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu * com.android.internal.logging.nano.MetricsProto.MetricsEvent#PROVISIONING_ENTRY_POINT_ADB}. 356f0e78d4391fd5cea487af116106a7887720b950eWei Liu */ 357f0e78d4391fd5cea487af116106a7887720b950eWei Liu private static final String LOG_TAG_PROFILE_OWNER = "profile-owner"; 358f0e78d4391fd5cea487af116106a7887720b950eWei Liu private static final String LOG_TAG_DEVICE_OWNER = "device-owner"; 359f0e78d4391fd5cea487af116106a7887720b950eWei Liu 360f0e78d4391fd5cea487af116106a7887720b950eWei Liu final Context mContext; 361f0e78d4391fd5cea487af116106a7887720b950eWei Liu final Injector mInjector; 362f0e78d4391fd5cea487af116106a7887720b950eWei Liu final IPackageManager mIPackageManager; 36330dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme final UserManager mUserManager; 3641d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme final UserManagerInternal mUserManagerInternal; 3651d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme final TelephonyManager mTelephonyManager; 366b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme private final LockPatternUtils mLockPatternUtils; 367341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu private final DeviceAdminServiceController mDeviceAdminServiceController; 368341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu 369341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu /** 3701d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme * Contains (package-user) pairs to remove. An entry (p, u) implies that removal of package p 3711d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme * is requested for user u. 3721d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme */ 373341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu private final Set<Pair<String, Integer>> mPackagesToRemove = 3741d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme new ArraySet<Pair<String, Integer>>(); 3751d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 376341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu final LocalService mLocalService; 377341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu 378341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu // Stores and loads state on device and profile owners. 379341938b446576ebf60865d8b6e5e6175f47766d0Wei Liu @VisibleForTesting 380058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla final Owners mOwners; 381058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 382058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final Binder mToken = new Binder(); 383058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 384058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla /** 385058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla * Whether or not device admin feature is supported. If it isn't return defaults for all 386058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla * public methods. 387058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla */ 388058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla boolean mHasFeature; 389058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 390058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla /** 391058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla * Whether or not this device is a watch. 392058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla */ 393058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla boolean mIsWatch; 394058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 395058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final CertificateMonitor mCertificateMonitor; 396058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final SecurityLogMonitor mSecurityLogMonitor; 397058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private NetworkLogger mNetworkLogger; 398058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 399058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final AtomicBoolean mRemoteBugreportServiceIsActive = new AtomicBoolean(); 400058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final AtomicBoolean mRemoteBugreportSharingAccepted = new AtomicBoolean(); 401058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 402058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private SetupContentObserver mSetupContentObserver; 403058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 404058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final Runnable mRemoteBugreportTimeoutRunnable = new Runnable() { 405058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 406058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public void run() { 407058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla if(mRemoteBugreportServiceIsActive.get()) { 408058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla onBugreportFailed(); 409058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 410058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 411058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla }; 412058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 413058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla /** Listens only if mHasFeature == true. */ 414058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final BroadcastReceiver mRemoteBugreportFinishedReceiver = new BroadcastReceiver() { 415058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 416058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 417058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public void onReceive(Context context, Intent intent) { 418f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme if (DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH.equals(intent.getAction()) 419058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla && mRemoteBugreportServiceIsActive.get()) { 420058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla onBugreportFinished(intent); 421058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 422058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 423058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla }; 424058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 425058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla /** Listens only if mHasFeature == true. */ 426058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla private final BroadcastReceiver mRemoteBugreportConsentReceiver = new BroadcastReceiver() { 427058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 428058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 429058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public void onReceive(Context context, Intent intent) { 430058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla String action = intent.getAction(); 431058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla mInjector.getNotificationManager().cancel(LOG_TAG, 432058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla RemoteBugreportUtils.NOTIFICATION_ID); 433058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED.equals(action)) { 4346ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park onBugreportSharingAccepted(); 4356ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park } else if (DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED.equals(action)) { 4366ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park onBugreportSharingDeclined(); 4376ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park } 4386ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 4396ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park } 440058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla }; 4416ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park 442058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public static final class Lifecycle extends SystemService { 4436ca7d0879ce405634f79607fba2bb8c69dee0e82Ecco Park private DevicePolicyManagerService mService; 444058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 445058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public Lifecycle(Context context) { 446058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla super(context); 447058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla mService = new DevicePolicyManagerService(context); 448058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 449058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 450058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 451058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public void onStart() { 452058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla publishBinderService(Context.DEVICE_POLICY_SERVICE, mService); 453058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } 454058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 455058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 456b77df78ad67299d2478f0d4515a167891ab55784Naveen Kalla public void onBootPhase(int phase) { 457b77df78ad67299d2478f0d4515a167891ab55784Naveen Kalla mService.systemReady(phase); 458b77df78ad67299d2478f0d4515a167891ab55784Naveen Kalla } 459058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla 460058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla @Override 461058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla public void onStartUser(int userHandle) { 462326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn mService.handleStartUser(userHandle); 463326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 464326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn 465326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn @Override 466326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn public void onUnlockUser(int userHandle) { 467326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn mService.handleUnlockUser(userHandle); 468326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 469326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn 470326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn @Override 4714c2d66379753e2b7680811726424026b9e54b18aFelipe Leme public void onStopUser(int userHandle) { 472e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme mService.handleStopUser(userHandle); 473e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme } 474e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme } 475326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn 4768f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn public static class DevicePolicyData { 477326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn @NonNull PasswordMetrics mActivePasswordMetrics = new PasswordMetrics(); 47801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn int mFailedPasswordAttempts = 0; 47901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 48001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn int mUserHandle; 48101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn int mPasswordOwner = -1; 48201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn long mLastMaximumTimeToLock = -1; 48301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mUserSetupComplete = false; 48401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mPaired = false; 48501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn int mUserProvisioningState; 48601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn int mPermissionPolicy; 48701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 48801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mDeviceProvisioningConfigApplied = false; 48901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 49001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final ArrayMap<ComponentName, ActiveAdmin> mAdminMap = new ArrayMap<>(); 49101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final ArrayList<ActiveAdmin> mAdminList = new ArrayList<>(); 49201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final ArrayList<ComponentName> mRemovingAdmins = new ArrayList<>(); 49301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 49401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 49501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final ArraySet<String> mAcceptedCaCertificates = new ArraySet<>(); 49601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 49701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // This is the list of component allowed to start lock task mode. 49801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn List<String> mLockTaskPackages = new ArrayList<>(); 49901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 50001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mStatusBarDisabled = false; 50101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 50201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn ComponentName mRestrictionsProvider; 50301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 50401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // Map of delegate package to delegation scopes 50501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final ArrayMap<String, List<String>> mDelegationMap = new ArrayMap<>(); 50601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 50701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean doNotAskCredentialsOnBoot = false; 50801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 50901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn Set<String> mAffiliationIds = new ArraySet<>(); 51001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 51101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn long mLastSecurityLogRetrievalTime = -1; 51201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 51301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn long mLastBugReportRequestTime = -1; 51401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 51501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn long mLastNetworkLogsRetrievalTime = -1; 51601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 51701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mCurrentInputMethodSet = false; 51801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 51901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // TODO(b/35385311): Keep track of metadata in TrustedCertificateStore instead. 52001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn Set<String> mOwnerInstalledCaCerts = new ArraySet<>(); 52101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 52201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // Used for initialization of users created by createAndManageUsers. 52301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean mAdminBroadcastPending = false; 52401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn PersistableBundle mInitBundle = null; 52501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 52601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn long mPasswordTokenHandle = 0; 52701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 52801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn public DevicePolicyData(int userHandle) { 52901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn mUserHandle = userHandle; 53001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 53101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 53201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 53301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final SparseArray<DevicePolicyData> mUserData = new SparseArray<>(); 53401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 53501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final Handler mHandler; 53601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final Handler mBackgroundHandler; 53701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 53801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn /** Listens only if mHasFeature == true. */ 53901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final BroadcastReceiver mReceiver = new BroadcastReceiver() { 54001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn @Override 54101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn public void onReceive(Context context, Intent intent) { 54201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final String action = intent.getAction(); 54301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 54401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn getSendingUserId()); 54501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 54601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn /* 54701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn * Network logging would ideally be started in setDeviceOwnerSystemPropertyLocked(), 54801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn * however it's too early in the boot process to register with IIpConnectivityMetrics 54901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn * to listen for events. 55001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn */ 55101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn if (Intent.ACTION_USER_STARTED.equals(action) 55201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn && userHandle == mOwners.getDeviceOwnerUserId()) { 55301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn synchronized (DevicePolicyManagerService.this) { 55401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn if (isNetworkLoggingEnabledInternalLocked()) { 55501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn setNetworkLoggingActiveInternal(true); 55601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 55701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 558326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 55901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn if (Intent.ACTION_BOOT_COMPLETED.equals(action) 560326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn && userHandle == mOwners.getDeviceOwnerUserId() 561326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn && getDeviceOwnerRemoteBugreportUri() != null) { 562326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn IntentFilter filterConsent = new IntentFilter(); 563326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 564326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 565326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 566326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 567326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn RemoteBugreportUtils.NOTIFICATION_ID, 568326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn RemoteBugreportUtils.buildNotification(mContext, 569326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 570326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn UserHandle.ALL); 571326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 572326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn if (Intent.ACTION_BOOT_COMPLETED.equals(action) 573326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) { 574326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn if (VERBOSE_LOG) { 575326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn Slog.v(LOG_TAG, "Sending password expiration notifications for action " 576326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn + action + " for user " + userHandle); 577326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 578326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn mHandler.post(new Runnable() { 57901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn @Override 580326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn public void run() { 581326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn handlePasswordExpirationNotification(userHandle); 582326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 583326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn }); 584326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 585326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn 586326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn if (Intent.ACTION_USER_ADDED.equals(action)) { 587326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_ADDED, userHandle); 588326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn synchronized (DevicePolicyManagerService.this) { 589326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn // It might take a while for the user to become affiliated. Make security 590326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn // and network logging unavailable in the meantime. 591326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn maybePauseDeviceWideLoggingLocked(); 592326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 593d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (Intent.ACTION_USER_REMOVED.equals(action)) { 594326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn sendUserAddedOrRemovedCommand(DeviceAdminReceiver.ACTION_USER_REMOVED, userHandle); 595326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn synchronized (DevicePolicyManagerService.this) { 59601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // Check whether the user is affiliated, *before* removing its data. 59701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn boolean isRemovedUserAffiliated = isUserAffiliatedWithDeviceLocked(userHandle); 59801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn removeUserData(userHandle); 59901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn if (!isRemovedUserAffiliated) { 60001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // We discard the logs when unaffiliated users are deleted (so that the 60101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // device owner cannot retrieve data about that user after it's gone). 60201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn discardDeviceWideLogsLocked(); 60301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // Resume logging if all remaining users are affiliated. 60401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn maybeResumeDeviceWideLoggingLocked(); 60501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 60601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 60701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } else if (Intent.ACTION_USER_STARTED.equals(action)) { 60801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn synchronized (DevicePolicyManagerService.this) { 60901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn // Reset the policy data 61001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn mUserData.remove(userHandle); 61101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn sendAdminEnabledBroadcastLocked(userHandle); 61201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 61301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn handlePackagesChanged(null /* check all admins */, userHandle); 61401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { 61501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn handlePackagesChanged(null /* check all admins */, userHandle); 61601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } else if (Intent.ACTION_PACKAGE_CHANGED.equals(action) 61701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn || (Intent.ACTION_PACKAGE_ADDED.equals(action) 61801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false))) { 61901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 62001d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action) 62101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn && !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) { 62201d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn handlePackagesChanged(intent.getData().getSchemeSpecificPart(), userHandle); 62301d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)) { 62401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn clearWipeProfileNotification(); 62501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 62601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 62701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 62801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn private void sendUserAddedOrRemovedCommand(String action, int userHandle) { 62901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn synchronized (DevicePolicyManagerService.this) { 630d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 63101d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn if (deviceOwner != null) { 632d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme Bundle extras = new Bundle(); 633d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 63401d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn sendAdminCommandLocked(deviceOwner, action, extras, null); 63501d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 63601d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 63701d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn } 63801d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn }; 63901d6c3935ace93f208fa3d93802b286e7484cfaeMark Salyzyn 6408f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn static class ActiveAdmin { 641326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn private static final String TAG_DISABLE_KEYGUARD_FEATURES = "disable-keyguard-features"; 642326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn private static final String TAG_TEST_ONLY_ADMIN = "test-only-admin"; 643326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn private static final String TAG_DISABLE_CAMERA = "disable-camera"; 6448f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn private static final String TAG_DISABLE_CALLER_ID = "disable-caller-id"; 6458620bb4118a68721d10c29529dc6978847d08d00Felipe Leme private static final String TAG_DISABLE_CONTACTS_SEARCH = "disable-contacts-search"; 6466c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn private static final String TAG_DISABLE_BLUETOOTH_CONTACT_SHARING 6476c3d90f89a4313eb449c770db6f05b2819cdd8bbMark Salyzyn = "disable-bt-contacts-sharing"; 6488f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn private static final String TAG_DISABLE_SCREEN_CAPTURE = "disable-screen-capture"; 6498f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn private static final String TAG_DISABLE_ACCOUNT_MANAGEMENT = "disable-account-management"; 6508f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn private static final String TAG_REQUIRE_AUTO_TIME = "require_auto_time"; 6518f37aa5011bf5d8c0a67126b92e3b435ffd4dca0Mark Salyzyn private static final String TAG_FORCE_EPHEMERAL_USERS = "force_ephemeral_users"; 6522b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme private static final String TAG_IS_NETWORK_LOGGING_ENABLED = "is_network_logging_enabled"; 65396c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_ACCOUNT_TYPE = "account-type"; 65496c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_PERMITTED_ACCESSIBILITY_SERVICES 65596c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme = "permitted-accessiblity-services"; 65696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_ENCRYPTION_REQUESTED = "encryption-requested"; 65796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_MANAGE_TRUST_AGENT_FEATURES = "manage-trust-agent-features"; 65896c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_TRUST_AGENT_COMPONENT_OPTIONS = "trust-agent-component-options"; 65996c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_TRUST_AGENT_COMPONENT = "component"; 66096c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_PASSWORD_EXPIRATION_DATE = "password-expiration-date"; 661bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme private static final String TAG_PASSWORD_EXPIRATION_TIMEOUT = "password-expiration-timeout"; 662f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross private static final String TAG_GLOBAL_PROXY_EXCLUSION_LIST = "global-proxy-exclusion-list"; 663d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_GLOBAL_PROXY_SPEC = "global-proxy-spec"; 664d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_SPECIFIES_GLOBAL_PROXY = "specifies-global-proxy"; 665d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_PERMITTED_IMES = "permitted-imes"; 666f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross private static final String TAG_MAX_FAILED_PASSWORD_WIPE = "max-failed-password-wipe"; 667d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_MAX_TIME_TO_UNLOCK = "max-time-to-unlock"; 668d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_STRONG_AUTH_UNLOCK_TIMEOUT = "strong-auth-unlock-timeout"; 66996c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme private static final String TAG_MIN_PASSWORD_NONLETTER = "min-password-nonletter"; 670d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_MIN_PASSWORD_SYMBOLS = "min-password-symbols"; 671d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_MIN_PASSWORD_NUMERIC = "min-password-numeric"; 672d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_MIN_PASSWORD_LETTERS = "min-password-letters"; 673d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_MIN_PASSWORD_LOWERCASE = "min-password-lowercase"; 674f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross private static final String TAG_MIN_PASSWORD_UPPERCASE = "min-password-uppercase"; 675d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_PASSWORD_HISTORY_LENGTH = "password-history-length"; 676f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme private static final String TAG_MIN_PASSWORD_LENGTH = "min-password-length"; 677d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String ATTR_VALUE = "value"; 678d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_PASSWORD_QUALITY = "password-quality"; 679d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_POLICIES = "policies"; 680d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme private static final String TAG_CROSS_PROFILE_WIDGET_PROVIDERS = 681d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme "cross-profile-widget-providers"; 68278f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Leme private static final String TAG_PROVIDER = "provider"; 68378f2c86235d5882a8dc84c85a1c1864062e5f3afFelipe Leme private static final String TAG_PACKAGE_LIST_ITEM = "item"; 68424b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_KEEP_UNINSTALLED_PACKAGES = "keep-uninstalled-packages"; 68524b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_USER_RESTRICTIONS = "user-restrictions"; 68624b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_DEFAULT_ENABLED_USER_RESTRICTIONS = 68724b66eed1acd08a975546b57198940f4de9250ebFelipe Leme "default-enabled-user-restrictions"; 68824b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_RESTRICTION = "restriction"; 68924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_SHORT_SUPPORT_MESSAGE = "short-support-message"; 69024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_LONG_SUPPORT_MESSAGE = "long-support-message"; 69124b66eed1acd08a975546b57198940f4de9250ebFelipe Leme private static final String TAG_PARENT_ADMIN = "parent-admin"; 6921d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final String TAG_ORGANIZATION_COLOR = "organization-color"; 6931d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final String TAG_ORGANIZATION_NAME = "organization-name"; 6941d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final String ATTR_LAST_NETWORK_LOGGING_NOTIFICATION = "last-notification"; 6951d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme private static final String ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS = "num-notifications"; 696111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme 697111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme final DeviceAdminInfo info; 69824b66eed1acd08a975546b57198940f4de9250ebFelipe Leme 69924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme 70024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_PASSWORD_HISTORY_LENGTH = 0; 70124b66eed1acd08a975546b57198940f4de9250ebFelipe Leme int passwordHistoryLength = DEF_PASSWORD_HISTORY_LENGTH; 70224b66eed1acd08a975546b57198940f4de9250ebFelipe Leme 70324b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_LENGTH = 0; 70424b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_LETTERS = 1; 70524b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_UPPER_CASE = 0; 70624b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_LOWER_CASE = 0; 70724b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_NUMERIC = 1; 70824b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_SYMBOLS = 1; 70924b66eed1acd08a975546b57198940f4de9250ebFelipe Leme static final int DEF_MINIMUM_PASSWORD_NON_LETTER = 0; 71024b66eed1acd08a975546b57198940f4de9250ebFelipe Leme @NonNull 7116fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme PasswordMetrics minimumPasswordMetrics = new PasswordMetrics( 7126fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, DEF_MINIMUM_PASSWORD_LENGTH, 713c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme DEF_MINIMUM_PASSWORD_LETTERS, DEF_MINIMUM_PASSWORD_UPPER_CASE, 714c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme DEF_MINIMUM_PASSWORD_LOWER_CASE, DEF_MINIMUM_PASSWORD_NUMERIC, 7151d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme DEF_MINIMUM_PASSWORD_SYMBOLS, DEF_MINIMUM_PASSWORD_NON_LETTER); 716c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 7171d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme static final long DEF_MAXIMUM_TIME_TO_UNLOCK = 0; 718e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme long maximumTimeToUnlock = DEF_MAXIMUM_TIME_TO_UNLOCK; 719e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 720e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme long strongAuthUnlockTimeout = 0; // admin doesn't participate by default 721770410dcf2f72cf4e806442263e63719a0be0f5aFelipe Leme 722e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme static final int DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE = 0; 72322200401c000c556ff7ed6d100d4f57e18ebb24fZach Riggle int maximumFailedPasswordsForWipe = DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE; 724e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 725e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme static final long DEF_PASSWORD_EXPIRATION_TIMEOUT = 0; 726e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme long passwordExpirationTimeout = DEF_PASSWORD_EXPIRATION_TIMEOUT; 727cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme 728e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme static final long DEF_PASSWORD_EXPIRATION_DATE = 0; 729e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme long passwordExpirationDate = DEF_PASSWORD_EXPIRATION_DATE; 730c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 731e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme static final int DEF_KEYGUARD_FEATURES_DISABLED = 0; // none 732c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 733e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme int disabledKeyguardFeatures = DEF_KEYGUARD_FEATURES_DISABLED; 734e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 735e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean encryptionRequested = false; 736e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean testOnlyAdmin = false; 737c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme boolean disableCamera = false; 7381d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme boolean disableCallerId = false; 739c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme boolean disableContactsSearch = false; 740e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean disableBluetoothContactSharing = true; 741e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean disableScreenCapture = false; // Can only be set by a device/profile owner. 742e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean requireAutoTime = false; // Can only be set by a device owner. 743e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean forceEphemeralUsers = false; // Can only be set by a device owner. 744e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme boolean isNetworkLoggingEnabled = false; // Can only be set by a device owner. 745e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 7461d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // one notification after enabling + one more after reboots 7471d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme static final int DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN = 2; 7481d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme int numNetworkLoggingNotifications = 0; 749aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampe long lastNetworkLoggingNotificationTimeMs = 0; // Time in milliseconds since epoch 750cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme 751e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme ActiveAdmin parentAdmin; 752e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme final boolean isParent; 753e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 7541d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme static class TrustAgentInfo { 755e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme public PersistableBundle options; 756e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme TrustAgentInfo(PersistableBundle bundle) { 757e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme options = bundle; 7584c2d66379753e2b7680811726424026b9e54b18aFelipe Leme } 7591d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme } 760e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme 761e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme final Set<String> accountTypesWithManagementDisabled = new ArraySet<>(); 7621d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 7631d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // The list of permitted accessibility services package namesas set by a profile 7641d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // or device owner. Null means all accessibility services are allowed, empty means 765111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme // none except system services are allowed. 766111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme List<String> permittedAccessiblityServices; 767678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme 76846b85da716a32f285fe1222e9978beacc8697d09Felipe Leme // The list of permitted input methods package names as set by a profile or device owner. 769678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme // Null means all input methods are allowed, empty means none except system imes are 770e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme // allowed. 771e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme List<String> permittedInputMethods; 7721d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 7731d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // List of package names to keep cached. 7741d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme List<String> keepUninstalledPackages; 7751d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 776111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme // TODO: review implementation decisions with frameworks team 777111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme boolean specifiesGlobalProxy = false; 778cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme String globalProxySpec = null; 779c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme String globalProxyExclusionList = null; 7801d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 781c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme ArrayMap<String, TrustAgentInfo> trustAgentInfos = new ArrayMap<>(); 7821d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme 783809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme List<String> crossProfileWidgetProviders; 784809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme 785809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme Bundle userRestrictions; 786c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 7871d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // User restrictions that have already been enabled by default for this admin (either when 788c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme // setting the device or profile owner, or during a system update if one of those "enabled 7891d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // by default" restrictions is newly added). 790809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme final Set<String> defaultEnabledRestrictionsAlreadySet = new ArraySet<>(); 791809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme 792809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme // Support text provided by the admin to display to the user. 793c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme CharSequence shortSupportMessage = null; 7941d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme CharSequence longSupportMessage = null; 795c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 796809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme // Background color of confirm credentials screen. Default: teal. 797809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme static final int DEF_ORGANIZATION_COLOR = Color.parseColor("#00796B"); 798809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme int organizationColor = DEF_ORGANIZATION_COLOR; 799809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme 800809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme // Default title of confirm credentials screen 801809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme String organizationName = null; 8026ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8036ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme ActiveAdmin(DeviceAdminInfo _info, boolean parent) { 8046ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme info = _info; 8056ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme isParent = parent; 8066ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 8076ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8086ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme ActiveAdmin getParentActiveAdmin() { 8096ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme Preconditions.checkState(!isParent); 8106ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8116ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme if (parentAdmin == null) { 8126ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme parentAdmin = new ActiveAdmin(info, /* parent */ true); 8136ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 8146ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return parentAdmin; 8156ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 8166ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8176ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme boolean hasParentActiveAdmin() { 8186ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return parentAdmin != null; 8196ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 8206ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8216ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme int getUid() { return info.getActivityInfo().applicationInfo.uid; } 8226ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 823ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak public UserHandle getUserHandle() { 824ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak return UserHandle.of(UserHandle.getUserId(info.getActivityInfo().applicationInfo.uid)); 825ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak } 8266ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 8276ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme void writeToXml(XmlSerializer out) 8286ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme throws IllegalArgumentException, IllegalStateException, IOException { 8296ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.startTag(null, TAG_POLICIES); 8306ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme info.writePoliciesToXml(out); 8316ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.endTag(null, TAG_POLICIES); 832ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak if (minimumPasswordMetrics.quality 833ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 8346ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.startTag(null, TAG_PASSWORD_QUALITY); 8356ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.attribute(null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.quality)); 8366ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.endTag(null, TAG_PASSWORD_QUALITY); 8376ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme if (minimumPasswordMetrics.length != DEF_MINIMUM_PASSWORD_LENGTH) { 8386ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.startTag(null, TAG_MIN_PASSWORD_LENGTH); 8396ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.attribute( 840ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.length)); 841ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak out.endTag(null, TAG_MIN_PASSWORD_LENGTH); 8426ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 8436ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme if(passwordHistoryLength != DEF_PASSWORD_HISTORY_LENGTH) { 8446ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.startTag(null, TAG_PASSWORD_HISTORY_LENGTH); 8456ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.attribute(null, ATTR_VALUE, Integer.toString(passwordHistoryLength)); 8466ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.endTag(null, TAG_PASSWORD_HISTORY_LENGTH); 8476ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 848ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak if (minimumPasswordMetrics.upperCase != DEF_MINIMUM_PASSWORD_UPPER_CASE) { 849ae7376516dd9f57137408f11e5fdcc53a15d4d8bTony Mak out.startTag(null, TAG_MIN_PASSWORD_UPPERCASE); 8506ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.attribute( 8516ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.upperCase)); 8526ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.endTag(null, TAG_MIN_PASSWORD_UPPERCASE); 853b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 854b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (minimumPasswordMetrics.lowerCase != DEF_MINIMUM_PASSWORD_LOWER_CASE) { 85532af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline out.startTag(null, TAG_MIN_PASSWORD_LOWERCASE); 856c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme out.attribute( 85732af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.lowerCase)); 85832af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline out.endTag(null, TAG_MIN_PASSWORD_LOWERCASE); 85932af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline } 86032af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline if (minimumPasswordMetrics.letters != DEF_MINIMUM_PASSWORD_LETTERS) { 861c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme out.startTag(null, TAG_MIN_PASSWORD_LETTERS); 862c0808155fd10d2d5c49bb4c8d4cafed8da28c182Felipe Leme out.attribute( 863e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.letters)); 864e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MIN_PASSWORD_LETTERS); 865e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 866e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (minimumPasswordMetrics.numeric != DEF_MINIMUM_PASSWORD_NUMERIC) { 867e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_MIN_PASSWORD_NUMERIC); 868e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute( 869e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.numeric)); 870e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MIN_PASSWORD_NUMERIC); 871e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 872e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (minimumPasswordMetrics.symbols != DEF_MINIMUM_PASSWORD_SYMBOLS) { 873e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_MIN_PASSWORD_SYMBOLS); 874e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute( 875e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.symbols)); 876e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MIN_PASSWORD_SYMBOLS); 877e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 878e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (minimumPasswordMetrics.nonLetter > DEF_MINIMUM_PASSWORD_NON_LETTER) { 879e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_MIN_PASSWORD_NONLETTER); 880e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute( 881e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme null, ATTR_VALUE, Integer.toString(minimumPasswordMetrics.nonLetter)); 882e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MIN_PASSWORD_NONLETTER); 883e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 884e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 885e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (maximumTimeToUnlock != DEF_MAXIMUM_TIME_TO_UNLOCK) { 886e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_MAX_TIME_TO_UNLOCK); 887e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Long.toString(maximumTimeToUnlock)); 888e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MAX_TIME_TO_UNLOCK); 889e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 890e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (strongAuthUnlockTimeout != DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 891e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 892e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Long.toString(strongAuthUnlockTimeout)); 893e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_STRONG_AUTH_UNLOCK_TIMEOUT); 894e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 895d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme if (maximumFailedPasswordsForWipe != DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 896e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 897e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Integer.toString(maximumFailedPasswordsForWipe)); 898e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_MAX_FAILED_PASSWORD_WIPE); 899e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 900d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme if (specifiesGlobalProxy) { 901d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme out.startTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 902e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(specifiesGlobalProxy)); 903e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_SPECIFIES_GLOBAL_PROXY); 904e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (globalProxySpec != null) { 905e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_GLOBAL_PROXY_SPEC); 906e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, globalProxySpec); 907e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_GLOBAL_PROXY_SPEC); 908e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 909e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (globalProxyExclusionList != null) { 910e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 911e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, globalProxyExclusionList); 912e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_GLOBAL_PROXY_EXCLUSION_LIST); 913e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 914e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 915e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (passwordExpirationTimeout != DEF_PASSWORD_EXPIRATION_TIMEOUT) { 916e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 917e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationTimeout)); 918e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_PASSWORD_EXPIRATION_TIMEOUT); 919e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 920e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (passwordExpirationDate != DEF_PASSWORD_EXPIRATION_DATE) { 921e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_PASSWORD_EXPIRATION_DATE); 922e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Long.toString(passwordExpirationDate)); 923e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_PASSWORD_EXPIRATION_DATE); 924e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 925e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (encryptionRequested) { 926e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_ENCRYPTION_REQUESTED); 927e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(encryptionRequested)); 928e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_ENCRYPTION_REQUESTED); 929e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 930e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (testOnlyAdmin) { 931e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_TEST_ONLY_ADMIN); 932e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(testOnlyAdmin)); 933e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_TEST_ONLY_ADMIN); 934e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 935e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (disableCamera) { 936e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_DISABLE_CAMERA); 937e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(disableCamera)); 938e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_DISABLE_CAMERA); 939e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 940e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme if (disableCallerId) { 941e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.startTag(null, TAG_DISABLE_CALLER_ID); 942e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(disableCallerId)); 943e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme out.endTag(null, TAG_DISABLE_CALLER_ID); 944bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme } 9459a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme if (disableContactsSearch) { 946f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross out.startTag(null, TAG_DISABLE_CONTACTS_SEARCH); 9472db0f5f31c015b5a89b619f8c95a9bf95c09c75bArve Hjønnevåg out.attribute(null, ATTR_VALUE, Boolean.toString(disableContactsSearch)); 948b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.endTag(null, TAG_DISABLE_CONTACTS_SEARCH); 949326842fca4883f1256aa9ed019bb3206ee76fca7Mark Salyzyn } 9508c8130eb68c89987a94db084608a4229bad06c18Mark Salyzyn if (!disableBluetoothContactSharing) { 951b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 952b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.attribute(null, ATTR_VALUE, 95330dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme Boolean.toString(disableBluetoothContactSharing)); 954f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme out.endTag(null, TAG_DISABLE_BLUETOOTH_CONTACT_SHARING); 955b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 956b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (disableScreenCapture) { 957b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_DISABLE_SCREEN_CAPTURE); 958b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(disableScreenCapture)); 959b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.endTag(null, TAG_DISABLE_SCREEN_CAPTURE); 960b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 961b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (requireAutoTime) { 962b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_REQUIRE_AUTO_TIME); 963b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(requireAutoTime)); 964b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.endTag(null, TAG_REQUIRE_AUTO_TIME); 965b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 966b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (forceEphemeralUsers) { 967b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_FORCE_EPHEMERAL_USERS); 96830dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme out.attribute(null, ATTR_VALUE, Boolean.toString(forceEphemeralUsers)); 969f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme out.endTag(null, TAG_FORCE_EPHEMERAL_USERS); 970f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 97169ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber if (isNetworkLoggingEnabled) { 97269ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.startTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 97369ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.attribute(null, ATTR_VALUE, Boolean.toString(isNetworkLoggingEnabled)); 97469ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.attribute(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS, 97569ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber Integer.toString(numNetworkLoggingNotifications)); 97669ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.attribute(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION, 97769ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber Long.toString(lastNetworkLoggingNotificationTimeMs)); 97869ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.endTag(null, TAG_IS_NETWORK_LOGGING_ENABLED); 97969ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber } 98069ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber if (disabledKeyguardFeatures != DEF_KEYGUARD_FEATURES_DISABLED) { 98169ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.startTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 98269ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.attribute(null, ATTR_VALUE, Integer.toString(disabledKeyguardFeatures)); 98369ec3ac3e761042f0c5e1e708c161d2df3c6db2bAndreas Huber out.endTag(null, TAG_DISABLE_KEYGUARD_FEATURES); 98481b429eba542f95877459bf6b860c55f35fea222Steven Moreland } 985b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (!accountTypesWithManagementDisabled.isEmpty()) { 98621b7c8d618777d6bf684e52b082c23f7e04b0688Elliott Hughes out.startTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 987e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme writeAttributeValuesToXml( 988e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme out, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 989e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme out.endTag(null, TAG_DISABLE_ACCOUNT_MANAGEMENT); 990e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme } 991b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (!trustAgentInfos.isEmpty()) { 992e4eca58fe7daa5e2dce7fa2b615c541aef00bc67Felipe Leme Set<Entry<String, TrustAgentInfo>> set = trustAgentInfos.entrySet(); 9934db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski out.startTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 994f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross for (Entry<String, TrustAgentInfo> entry : set) { 995f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross TrustAgentInfo trustAgentInfo = entry.getValue(); 996f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme out.startTag(null, TAG_TRUST_AGENT_COMPONENT); 9971dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown out.attribute(null, ATTR_VALUE, entry.getKey()); 9981dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown if (trustAgentInfo.options != null) { 999a297c3258f6f7ea52cc2dcc42d62f85fda12a163Mark Salyzyn out.startTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 1000f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross try { 10013ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme trustAgentInfo.options.saveToXml(out); 10023ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme } catch (XmlPullParserException e) { 10033ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme Log.e(LOG_TAG, "Failed to save TrustAgent options", e); 10043ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme } 10053ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme out.endTag(null, TAG_TRUST_AGENT_COMPONENT_OPTIONS); 10063ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme } 10073ae337c4a12f3fa32a87663e6d8b736bcc136692Felipe Leme out.endTag(null, TAG_TRUST_AGENT_COMPONENT); 1008d886ec496952a19bee202bc3d6f670009c3a0689Ajay Panicker } 10099a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme out.endTag(null, TAG_MANAGE_TRUST_AGENT_FEATURES); 1010cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme } 1011bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme if (crossProfileWidgetProviders != null && !crossProfileWidgetProviders.isEmpty()) { 10125a93003d3f0d1808b6dcd9928041ec62ea7f67adJeff Sharkey out.startTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 10135a93003d3f0d1808b6dcd9928041ec62ea7f67adJeff Sharkey writeAttributeValuesToXml(out, TAG_PROVIDER, crossProfileWidgetProviders); 10146ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme out.endTag(null, TAG_CROSS_PROFILE_WIDGET_PROVIDERS); 1015ecc0763e6c96c418ea4ee6c993d58d16a58407b3Mark Salyzyn } 1016e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme writePackageListToXml(out, TAG_PERMITTED_ACCESSIBILITY_SERVICES, 1017f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross permittedAccessiblityServices); 10187dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris writePackageListToXml(out, TAG_PERMITTED_IMES, permittedInputMethods); 10197dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris writePackageListToXml(out, TAG_KEEP_UNINSTALLED_PACKAGES, keepUninstalledPackages); 10207dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris if (hasUserRestrictions()) { 1021e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme UserRestrictionsUtils.writeRestrictions( 1022e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme out, userRestrictions, TAG_USER_RESTRICTIONS); 10237dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris } 10241d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme if (!defaultEnabledRestrictionsAlreadySet.isEmpty()) { 10251d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme out.startTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1026cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme writeAttributeValuesToXml( 1027e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme out, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 1028e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme out.endTag(null, TAG_DEFAULT_ENABLED_USER_RESTRICTIONS); 1029e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme } 1030e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme if (!TextUtils.isEmpty(shortSupportMessage)) { 1031e82a27d0c1e3f2cef6f13a1a9efff55638601752Felipe Leme out.startTag(null, TAG_SHORT_SUPPORT_MESSAGE); 10327dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris out.text(shortSupportMessage.toString()); 10337dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris out.endTag(null, TAG_SHORT_SUPPORT_MESSAGE); 10347dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris } 10357dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris if (!TextUtils.isEmpty(longSupportMessage)) { 1036d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme out.startTag(null, TAG_LONG_SUPPORT_MESSAGE); 10377dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris out.text(longSupportMessage.toString()); 10387dc7f3221f26b771c266a26ec785eb74287922f1Christopher Ferris out.endTag(null, TAG_LONG_SUPPORT_MESSAGE); 1039b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 1040b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (parentAdmin != null) { 1041b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_PARENT_ADMIN); 1042b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parentAdmin.writeToXml(out); 1043b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.endTag(null, TAG_PARENT_ADMIN); 1044f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 10456ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme if (organizationColor != DEF_ORGANIZATION_COLOR) { 10462262c16372570f57d3107d574abe2c80825d286eMark Salyzyn out.startTag(null, TAG_ORGANIZATION_COLOR); 1047f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross out.attribute(null, ATTR_VALUE, Integer.toString(organizationColor)); 1048a59828a5d2740433164872e9a0b44363e2ba0cd4Elliott Hughes out.endTag(null, TAG_ORGANIZATION_COLOR); 1049b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 1050d4c3d38957870fa27423dbc55d99d68772fbd490Lorenzo Colitti if (organizationName != null) { 1051b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.startTag(null, TAG_ORGANIZATION_NAME); 1052b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.text(organizationName); 1053d4c3d38957870fa27423dbc55d99d68772fbd490Lorenzo Colitti out.endTag(null, TAG_ORGANIZATION_NAME); 1054b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 1055b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 10562b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran 10572b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran void writePackageListToXml(XmlSerializer out, String outerTag, 10582b3bba34aec65b612be8d1f52cd124d9c30955f9Sreeram Ramachandran List<String> packageList) 1059b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme throws IllegalArgumentException, IllegalStateException, IOException { 1060b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme if (packageList == null) { 1061b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme return; 1062b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 106330dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme 1064f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross out.startTag(null, outerTag); 1065b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme writeAttributeValuesToXml(out, TAG_PACKAGE_LIST_ITEM, packageList); 10660b2c9268265e9a165551eaa66cb461d3fab8b564Dmitry Shmidt out.endTag(null, outerTag); 1067b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 106830dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme 10696afc38c45af45eb8f64793bca2903b3f4c55579bLorenzo Colitti void writeAttributeValuesToXml(XmlSerializer out, String tag, 1070b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme @NonNull Collection<String> values) throws IOException { 1071f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross for (String value : values) { 107223ccc625fd60891d20977abc5f2c35cbe46142acElliott Hughes out.startTag(null, tag); 1073f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross out.attribute(null, ATTR_VALUE, value); 1074b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme out.endTag(null, tag); 1075b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } 1076f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 10772435442bcac12703a5c44790aacc91ede94a3e9aJin Qian 1078f649a6ef3ca6358f605aea100c77a3f20f4af937ynwang void readFromXml(XmlPullParser parser) 1079b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme throws XmlPullParserException, IOException { 1080f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross int outerDepth = parser.getDepth(); 1081b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme int type; 1082f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross while ((type=parser.next()) != END_DOCUMENT 1083d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme && (type != END_TAG || parser.getDepth() > outerDepth)) { 1084d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme if (type == END_TAG || type == TEXT) { 1085678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme continue; 1086d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } 1087678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme String tag = parser.getName(); 1088d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme if (TAG_POLICIES.equals(tag)) { 1089678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme info.readPoliciesFromXml(parser); 1090d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_PASSWORD_QUALITY.equals(tag)) { 1091678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme minimumPasswordMetrics.quality = Integer.parseInt( 1092d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1093678727af1ae44fe40a6d70fb175f8acfdb5d83d9Felipe Leme } else if (TAG_MIN_PASSWORD_LENGTH.equals(tag)) { 1094d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme minimumPasswordMetrics.length = Integer.parseInt( 1095f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 1096f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } else if (TAG_PASSWORD_HISTORY_LENGTH.equals(tag)) { 1097b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme passwordHistoryLength = Integer.parseInt( 1098b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1099b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } else if (TAG_MIN_PASSWORD_UPPERCASE.equals(tag)) { 1100b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme minimumPasswordMetrics.upperCase = Integer.parseInt( 1101b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1102f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } else if (TAG_MIN_PASSWORD_LOWERCASE.equals(tag)) { 11036f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme minimumPasswordMetrics.lowerCase = Integer.parseInt( 1104f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 11057440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland } else if (TAG_MIN_PASSWORD_LETTERS.equals(tag)) { 110696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme minimumPasswordMetrics.letters = Integer.parseInt( 110796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 110830dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme } else if (TAG_MIN_PASSWORD_NUMERIC.equals(tag)) { 110930dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme minimumPasswordMetrics.numeric = Integer.parseInt( 111030dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 111130dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme } else if (TAG_MIN_PASSWORD_SYMBOLS.equals(tag)) { 111296c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme minimumPasswordMetrics.symbols = Integer.parseInt( 1113f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 111430dbfa1c5fac2d8cbd5bc2e41616be9353c81733Felipe Leme } else if (TAG_MIN_PASSWORD_NONLETTER.equals(tag)) { 1115f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross minimumPasswordMetrics.nonLetter = Integer.parseInt( 1116b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1117f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } else if (TAG_MAX_TIME_TO_UNLOCK.equals(tag)) { 1118f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross maximumTimeToUnlock = Long.parseLong( 1119d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1120d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_STRONG_AUTH_UNLOCK_TIMEOUT.equals(tag)) { 1121d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme strongAuthUnlockTimeout = Long.parseLong( 1122f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 11235bcce574840ffc58916f6fa9beb39739b51508e6Felipe Leme } else if (TAG_MAX_FAILED_PASSWORD_WIPE.equals(tag)) { 11245bcce574840ffc58916f6fa9beb39739b51508e6Felipe Leme maximumFailedPasswordsForWipe = Integer.parseInt( 1125f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 1126d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_SPECIFIES_GLOBAL_PROXY.equals(tag)) { 1127d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme specifiesGlobalProxy = Boolean.parseBoolean( 1128d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 112902bea9786d2ecc4c04f35fd7d9b73d4dd2b73735Dianne Hackborn } else if (TAG_GLOBAL_PROXY_SPEC.equals(tag)) { 1130b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme globalProxySpec = 1131b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parser.getAttributeValue(null, ATTR_VALUE); 1132b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } else if (TAG_GLOBAL_PROXY_EXCLUSION_LIST.equals(tag)) { 1133b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme globalProxyExclusionList = 1134b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme parser.getAttributeValue(null, ATTR_VALUE); 1135b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } else if (TAG_PASSWORD_EXPIRATION_TIMEOUT.equals(tag)) { 113602bea9786d2ecc4c04f35fd7d9b73d4dd2b73735Dianne Hackborn passwordExpirationTimeout = Long.parseLong( 1137d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1138d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_PASSWORD_EXPIRATION_DATE.equals(tag)) { 1139d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme passwordExpirationDate = Long.parseLong( 1140f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 11411434a5ccf5fa91f20f8f145ecdc4303a03cf3a17Winson Chung } else if (TAG_ENCRYPTION_REQUESTED.equals(tag)) { 1142f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross encryptionRequested = Boolean.parseBoolean( 1143d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1144d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_TEST_ONLY_ADMIN.equals(tag)) { 1145d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme testOnlyAdmin = Boolean.parseBoolean( 1146f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 1147b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } else if (TAG_DISABLE_CAMERA.equals(tag)) { 1148f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross disableCamera = Boolean.parseBoolean( 1149d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1150d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_DISABLE_CALLER_ID.equals(tag)) { 1151d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme disableCallerId = Boolean.parseBoolean( 1152f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 1153b0f669de54ffe3ef59f3597faf2b4885793853cfFelipe Leme } else if (TAG_DISABLE_CONTACTS_SEARCH.equals(tag)) { 1154f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross disableContactsSearch = Boolean.parseBoolean( 1155058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla parser.getAttributeValue(null, ATTR_VALUE)); 1156058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } else if (TAG_DISABLE_BLUETOOTH_CONTACT_SHARING.equals(tag)) { 1157058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla disableBluetoothContactSharing = Boolean.parseBoolean(parser 1158058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla .getAttributeValue(null, ATTR_VALUE)); 1159058e1e8ce51327e00636d3b0008671dc09c20259Naveen Kalla } else if (TAG_DISABLE_SCREEN_CAPTURE.equals(tag)) { 1160d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme disableScreenCapture = Boolean.parseBoolean( 1161d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1162d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_REQUIRE_AUTO_TIME.equals(tag)) { 1163d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme requireAutoTime = Boolean.parseBoolean( 1164d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1165d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } else if (TAG_FORCE_EPHEMERAL_USERS.equals(tag)) { 1166f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross forceEphemeralUsers = Boolean.parseBoolean( 1167f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross parser.getAttributeValue(null, ATTR_VALUE)); 11686f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_IS_NETWORK_LOGGING_ENABLED.equals(tag)) { 11696f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme isNetworkLoggingEnabled = Boolean.parseBoolean( 1170d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 1171d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme lastNetworkLoggingNotificationTimeMs = Long.parseLong( 1172d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme parser.getAttributeValue(null, ATTR_LAST_NETWORK_LOGGING_NOTIFICATION)); 11736f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme numNetworkLoggingNotifications = Integer.parseInt( 117469d9221e3f2c3db256d8216f8f0d6316f7213c88Chris Phoenix parser.getAttributeValue(null, ATTR_NUM_NETWORK_LOGGING_NOTIFICATIONS)); 11756f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_DISABLE_KEYGUARD_FEATURES.equals(tag)) { 11767440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland disabledKeyguardFeatures = Integer.parseInt( 11776f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 11786f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_DISABLE_ACCOUNT_MANAGEMENT.equals(tag)) { 11796f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme readAttributeValues( 11806f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parser, TAG_ACCOUNT_TYPE, accountTypesWithManagementDisabled); 11817440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland } else if (TAG_MANAGE_TRUST_AGENT_FEATURES.equals(tag)) { 11826f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme trustAgentInfos = getAllTrustAgentInfos(parser, tag); 11836f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_CROSS_PROFILE_WIDGET_PROVIDERS.equals(tag)) { 11846f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme crossProfileWidgetProviders = new ArrayList<>(); 11857440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland readAttributeValues(parser, TAG_PROVIDER, crossProfileWidgetProviders); 11866f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_PERMITTED_ACCESSIBILITY_SERVICES.equals(tag)) { 11876f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme permittedAccessiblityServices = readPackageList(parser, tag); 11886f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_PERMITTED_IMES.equals(tag)) { 11896f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme permittedInputMethods = readPackageList(parser, tag); 11906f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_KEEP_UNINSTALLED_PACKAGES.equals(tag)) { 11916f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme keepUninstalledPackages = readPackageList(parser, tag); 11926f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_USER_RESTRICTIONS.equals(tag)) { 11936f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme userRestrictions = UserRestrictionsUtils.readRestrictions(parser); 11946f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_DEFAULT_ENABLED_USER_RESTRICTIONS.equals(tag)) { 11956f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme readAttributeValues( 11966f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parser, TAG_RESTRICTION, defaultEnabledRestrictionsAlreadySet); 11976f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_SHORT_SUPPORT_MESSAGE.equals(tag)) { 11986f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme type = parser.next(); 11996f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme if (type == XmlPullParser.TEXT) { 12006f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme shortSupportMessage = parser.getText(); 12016f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else { 12026f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme Log.w(LOG_TAG, "Missing text when loading short support message"); 1203f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme } 12047440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland } else if (TAG_LONG_SUPPORT_MESSAGE.equals(tag)) { 12057440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland type = parser.next(); 12067440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland if (type == XmlPullParser.TEXT) { 12077440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland longSupportMessage = parser.getText(); 12087440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland } else { 12097440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland Log.w(LOG_TAG, "Missing text when loading long support message"); 12107440ddb786b7732478173fe142512dba4e2a8dfdSteven Moreland } 12116f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_PARENT_ADMIN.equals(tag)) { 12126f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme Preconditions.checkState(!isParent); 1213d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme 12146f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parentAdmin = new ActiveAdmin(info, /* parent */ true); 12156f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parentAdmin.readFromXml(parser); 12166f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_ORGANIZATION_COLOR.equals(tag)) { 12176f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme organizationColor = Integer.parseInt( 12186f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme parser.getAttributeValue(null, ATTR_VALUE)); 12196f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme } else if (TAG_ORGANIZATION_NAME.equals(tag)) { 12206f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme type = parser.next(); 12216f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme if (type == XmlPullParser.TEXT) { 12226f674aefab201fbf9141aabbb603bbfc84771927Felipe Leme organizationName = parser.getText(); 12234a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } else { 12244a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme Log.w(LOG_TAG, "Missing text when loading organization name"); 1225bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme } 12264a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } else { 12274a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme Slog.w(LOG_TAG, "Unknown admin tag: " + tag); 12284a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme XmlUtils.skipCurrentTag(parser); 12294a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } 12304a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } 12314a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } 12324a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme 12334a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme private List<String> readPackageList(XmlPullParser parser, 12344a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme String tag) throws XmlPullParserException, IOException { 12354a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme List<String> result = new ArrayList<String>(); 12364a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme int outerDepth = parser.getDepth(); 12374a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme int outerType; 12384a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme while ((outerType=parser.next()) != XmlPullParser.END_DOCUMENT 12394a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme && (outerType != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 12404a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme if (outerType == XmlPullParser.END_TAG || outerType == XmlPullParser.TEXT) { 12414a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme continue; 1242d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } 12434a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme String outerTag = parser.getName(); 12444a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme if (TAG_PACKAGE_LIST_ITEM.equals(outerTag)) { 12454a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme String packageName = parser.getAttributeValue(null, ATTR_VALUE); 12464a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme if (packageName != null) { 12474a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme result.add(packageName); 12484a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } else { 1249f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross Slog.w(LOG_TAG, "Package name missing under " + outerTag); 1250f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 12516ae5c4f52b55943a7a84fb3cb47710effe788e11Felipe Leme } else { 12522e671bbdb741c2926b6df7b240fdc31c7361f330Andres Morales Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + outerTag); 1253885f888c55587e9366542b5155a06c321cde175aJohn Michelau } 1254885f888c55587e9366542b5155a06c321cde175aJohn Michelau } 1255f87959e00732d7d737527f1248a71adea99ae29dWei Liu return result; 1256f87959e00732d7d737527f1248a71adea99ae29dWei Liu } 1257f87959e00732d7d737527f1248a71adea99ae29dWei Liu 1258f87959e00732d7d737527f1248a71adea99ae29dWei Liu private void readAttributeValues( 1259f87959e00732d7d737527f1248a71adea99ae29dWei Liu XmlPullParser parser, String tag, Collection<String> result) 1260f87959e00732d7d737527f1248a71adea99ae29dWei Liu throws XmlPullParserException, IOException { 1261f87959e00732d7d737527f1248a71adea99ae29dWei Liu result.clear(); 1262f87959e00732d7d737527f1248a71adea99ae29dWei Liu int outerDepthDAM = parser.getDepth(); 1263f87959e00732d7d737527f1248a71adea99ae29dWei Liu int typeDAM; 1264f87959e00732d7d737527f1248a71adea99ae29dWei Liu while ((typeDAM=parser.next()) != END_DOCUMENT 1265f87959e00732d7d737527f1248a71adea99ae29dWei Liu && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1266f87959e00732d7d737527f1248a71adea99ae29dWei Liu if (typeDAM == END_TAG || typeDAM == TEXT) { 12671d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme continue; 12689a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 12691d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme String tagDAM = parser.getName(); 12709a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme if (tag.equals(tagDAM)) { 12715b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme result.add(parser.getAttributeValue(null, ATTR_VALUE)); 12725b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme } else { 12735b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme Slog.e(LOG_TAG, "Expected tag " + tag + " but found " + tagDAM); 12745b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme } 12757447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme } 1276bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme } 12775b9d3bf16bab50c8067bdc932dca1e7d952a035eFelipe Leme 12789a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme private ArrayMap<String, TrustAgentInfo> getAllTrustAgentInfos( 1279cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme XmlPullParser parser, String tag) throws XmlPullParserException, IOException { 12806e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme int outerDepthDAM = parser.getDepth(); 12816e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme int typeDAM; 12821d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme final ArrayMap<String, TrustAgentInfo> result = new ArrayMap<>(); 1283cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme while ((typeDAM=parser.next()) != END_DOCUMENT 1284111b9d06cc0fc72438782c9234f28675e5077ef4Felipe Leme && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1285809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme if (typeDAM == END_TAG || typeDAM == TEXT) { 12866e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme continue; 12870f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme } 12880f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme String tagDAM = parser.getName(); 12899a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme if (TAG_TRUST_AGENT_COMPONENT.equals(tagDAM)) { 12900f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme final String component = parser.getAttributeValue(null, ATTR_VALUE); 12910f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme final TrustAgentInfo trustAgentInfo = getTrustAgentInfo(parser, tag); 12920f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme result.put(component, trustAgentInfo); 12930f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme } else { 12949a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 12950f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme } 12960f3fb20cff288f2874c46c9f4102c6c9f273a0a3Felipe Leme } 1297c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme return result; 12981d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme } 1299c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme 13006e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme private TrustAgentInfo getTrustAgentInfo(XmlPullParser parser, String tag) 13016e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme throws XmlPullParserException, IOException { 13026e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme int outerDepthDAM = parser.getDepth(); 13031d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme int typeDAM; 13041d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme TrustAgentInfo result = new TrustAgentInfo(null); 13051d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme while ((typeDAM=parser.next()) != END_DOCUMENT 1306e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme && (typeDAM != END_TAG || parser.getDepth() > outerDepthDAM)) { 1307e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme if (typeDAM == END_TAG || typeDAM == TEXT) { 1308e9d2c5414c86949f6de12c4291a2d8c34b2d0b34Felipe Leme continue; 1309c4eee56dab06a7de1db18327f8d4831f89d1d640Felipe Leme } 1310c4eee56dab06a7de1db18327f8d4831f89d1d640Felipe Leme String tagDAM = parser.getName(); 13116e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme if (TAG_TRUST_AGENT_COMPONENT_OPTIONS.equals(tagDAM)) { 13126e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme result.options = PersistableBundle.restoreFromXml(parser); 13136e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme } else { 13144db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski Slog.w(LOG_TAG, "Unknown tag under " + tag + ": " + tagDAM); 131527cd7b256eb08bf9dec7e4e8af8375711ab10225Andreas Gampe } 131627cd7b256eb08bf9dec7e4e8af8375711ab10225Andreas Gampe } 1317aff684300a3b7d6984d3b3c1efddb810cd0205e7Andreas Gampe return result; 1318cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme } 13194db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski 13204db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski boolean hasUserRestrictions() { 13214db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski return userRestrictions != null && userRestrictions.size() > 0; 13224db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski } 1323c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes 13244db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski Bundle ensureUserRestrictions() { 13254db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski if (userRestrictions == null) { 13264db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski userRestrictions = new Bundle(); 13274db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski } 13284db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski return userRestrictions; 13294db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski } 13304db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski 1331cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme void dump(String prefix, PrintWriter pw) { 13324db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.print(prefix); pw.print("uid="); pw.println(getUid()); 13334db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.print(prefix); pw.print("testOnlyAdmin="); 13344db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.println(testOnlyAdmin); 1335c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes pw.print(prefix); pw.println("policies:"); 13364db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski ArrayList<DeviceAdminInfo.PolicyInfo> pols = info.getUsedPolicies(); 13374db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski if (pols != null) { 1338c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes for (int i=0; i<pols.size(); i++) { 1339c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes pw.print(prefix); pw.print(" "); pw.println(pols.get(i).tag); 1340c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes } 1341c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes } 1342c4dc141d1442794170421b9ee78ae00ce6b28307Elliott Hughes pw.print(prefix); pw.print("passwordQuality=0x"); 1343cbbdf73608bace91270622034e4813a2355b7bf1Michal Karpinski pw.println(Integer.toHexString(minimumPasswordMetrics.quality)); 13444db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.print(prefix); pw.print("minimumPasswordLength="); 13454db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.println(minimumPasswordMetrics.length); 13464db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.print(prefix); pw.print("passwordHistoryLength="); 13474db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.println(passwordHistoryLength); 13484db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.print(prefix); pw.print("minimumPasswordUpperCase="); 1349a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme pw.println(minimumPasswordMetrics.upperCase); 1350a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme pw.print(prefix); pw.print("minimumPasswordLowerCase="); 1351a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme pw.println(minimumPasswordMetrics.lowerCase); 1352a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme pw.print(prefix); pw.print("minimumPasswordLetters="); 1353a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme pw.println(minimumPasswordMetrics.letters); 13548d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("minimumPasswordNumeric="); 13558d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(minimumPasswordMetrics.numeric); 13568d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("minimumPasswordSymbols="); 13578d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(minimumPasswordMetrics.symbols); 13588d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("minimumPasswordNonLetter="); 13598d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(minimumPasswordMetrics.nonLetter); 13608d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("maximumTimeToUnlock="); 13618d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(maximumTimeToUnlock); 13628d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("strongAuthUnlockTimeout="); 13638d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(strongAuthUnlockTimeout); 13648d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.print(prefix); pw.print("maximumFailedPasswordsForWipe="); 13658d2410eb937fdc27255b1129ed961463d64f847fFelipe Leme pw.println(maximumFailedPasswordsForWipe); 136635b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.print(prefix); pw.print("specifiesGlobalProxy="); 136735b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.println(specifiesGlobalProxy); 136835b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.print(prefix); pw.print("passwordExpirationTimeout="); 136935b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.println(passwordExpirationTimeout); 137035b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.print(prefix); pw.print("passwordExpirationDate="); 137135b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.println(passwordExpirationDate); 137235b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme if (globalProxySpec != null) { 137335b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.print(prefix); pw.print("globalProxySpec="); 137435b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme pw.println(globalProxySpec); 137535b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme } 1376f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross if (globalProxyExclusionList != null) { 1377f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("globalProxyEclusionList="); 13786e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme pw.println(globalProxyExclusionList); 13791f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau } 1380f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("encryptionRequested="); 1381f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.println(encryptionRequested); 13822628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme pw.print(prefix); pw.print("disableCamera="); 1383f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.println(disableCamera); 138427f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey pw.print(prefix); pw.print("disableCallerId="); 13854db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski pw.println(disableCallerId); 1386d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.print("disableContactsSearch="); 138775876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme pw.println(disableContactsSearch); 13886ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme pw.print(prefix); pw.print("disableBluetoothContactSharing="); 13898fecfdda012928bc2fe6d0e66fd4a4c912946254Felipe Leme pw.println(disableBluetoothContactSharing); 1390f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("disableScreenCapture="); 1391f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.println(disableScreenCapture); 13929c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.print(prefix); pw.print("requireAutoTime="); 1393d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.println(requireAutoTime); 1394f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("forceEphemeralUsers="); 13959c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.println(forceEphemeralUsers); 1396f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("isNetworkLoggingEnabled="); 13979c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.println(isNetworkLoggingEnabled); 13989c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.print(prefix); pw.print("disabledKeyguardFeatures="); 13999c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.println(disabledKeyguardFeatures); 14009c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.print(prefix); pw.print("crossProfileWidgetProviders="); 14019c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.println(crossProfileWidgetProviders); 14029c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang if (permittedAccessiblityServices != null) { 14039c1f9bb7205e59d4bdc6f9e9601bc4b3ef210b3bWei Wang pw.print(prefix); pw.print("permittedAccessibilityServices="); 1404f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.println(permittedAccessiblityServices); 1405f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 14061dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown if (permittedInputMethods != null) { 1407f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross pw.print(prefix); pw.print("permittedInputMethods="); 14082628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme pw.println(permittedInputMethods); 1409f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 1410e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme if (keepUninstalledPackages != null) { 1411d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.print("keepUninstalledPackages="); 1412d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.println(keepUninstalledPackages); 1413d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } 1414d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.print("organizationColor="); 1415d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.println(organizationColor); 1416d071c6802a03031b26de7b92a76d03849681149bFelipe Leme if (organizationName != null) { 1417d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.print("organizationName="); 1418d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.println(organizationName); 14199a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 1420d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.println("userRestrictions:"); 1421d071c6802a03031b26de7b92a76d03849681149bFelipe Leme UserRestrictionsUtils.dumpRestrictions(pw, prefix + " ", userRestrictions); 1422d071c6802a03031b26de7b92a76d03849681149bFelipe Leme pw.print(prefix); pw.print("defaultEnabledRestrictionsAlreadySet="); 14234a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme pw.println(defaultEnabledRestrictionsAlreadySet); 14244a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme pw.print(prefix); pw.print("isParent="); 14254a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme pw.println(isParent); 14264a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme if (parentAdmin != null) { 14274a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme pw.print(prefix); pw.println("parentAdmin:"); 14284a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme parentAdmin.dump(prefix + " ", pw); 1429e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme } 1430f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 1431f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 1432f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross 1433d071c6802a03031b26de7b92a76d03849681149bFelipe Leme private void handlePackagesChanged(@Nullable String packageName, int userHandle) { 1434d071c6802a03031b26de7b92a76d03849681149bFelipe Leme boolean removedAdmin = false; 1435d071c6802a03031b26de7b92a76d03849681149bFelipe Leme if (VERBOSE_LOG) Slog.d(LOG_TAG, "Handling package changes for user " + userHandle); 1436d071c6802a03031b26de7b92a76d03849681149bFelipe Leme DevicePolicyData policy = getUserData(userHandle); 1437d071c6802a03031b26de7b92a76d03849681149bFelipe Leme synchronized (this) { 1438d071c6802a03031b26de7b92a76d03849681149bFelipe Leme for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1439d071c6802a03031b26de7b92a76d03849681149bFelipe Leme ActiveAdmin aa = policy.mAdminList.get(i); 1440d071c6802a03031b26de7b92a76d03849681149bFelipe Leme try { 1441d071c6802a03031b26de7b92a76d03849681149bFelipe Leme // If we're checking all packages or if the specific one we're checking matches, 14429a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme // then check if the package and receiver still exist. 14439ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme final String adminPackage = aa.info.getPackageName(); 14449ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme if (packageName == null || packageName.equals(adminPackage)) { 14459a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme if (mIPackageManager.getPackageInfo(adminPackage, 0, userHandle) == null 144675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme || mIPackageManager.getReceiverInfo(aa.info.getComponent(), 144775876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme PackageManager.MATCH_DIRECT_BOOT_AWARE 14489a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 14499ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme userHandle) == null) { 14509a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme removedAdmin = true; 14519ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme policy.mAdminList.remove(i); 14529ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme policy.mAdminMap.remove(aa.info.getComponent()); 14539ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme } 14549a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 14559a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } catch (RemoteException re) { 14566ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme // Shouldn't happen. 14576ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 14589ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme } 14599a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme if (removedAdmin) { 14609ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme validatePasswordOwnerLocked(policy); 14619ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme } 146296c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme 14639ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme boolean removedDelegate = false; 14649ce6aa4d22f6afee2c682cf2e40bf50575f3cc61Felipe Leme 1465b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla // Check if a delegate was removed. 1466b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla for (int i = policy.mDelegationMap.size() - 1; i >= 0; i--) { 1467b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla final String delegatePackage = policy.mDelegationMap.keyAt(i); 1468b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla if (isRemovedPackage(packageName, delegatePackage, userHandle)) { 1469b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla policy.mDelegationMap.removeAt(i); 1470b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla removedDelegate = true; 1471b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla } 1472b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla } 1473b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla 1474b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla // If it's an owner package, we may need to refresh the bound connection. 1475b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla final ComponentName owner = getOwnerComponent(userHandle); 1476b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla if ((packageName != null) && (owner != null) 1477b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla && (owner.getPackageName().equals(packageName))) { 1478b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla startOwnerService(userHandle, "package-broadcast"); 14799a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 14804a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme 14816e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme // Persist updates if the removed package was an admin or delegate. 14826e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme if (removedAdmin || removedDelegate) { 14832628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme saveSettingsLocked(policy.mUserHandle); 14844a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme } 14852628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme } 14862628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme if (removedAdmin) { 14879a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme // The removed admin might have disabled camera, so update user restrictions. 14884a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme pushUserRestrictions(userHandle); 148971bbfc57974331dce79242ce806d92035fce06baFelipe Leme } 14906e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme } 14919a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 14924a0db9fee04a5402b94cd31f0196334e110ebd05Felipe Leme private boolean isRemovedPackage(String changedPackage, String targetPackage, int userHandle) { 14934db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski try { 14944db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski return targetPackage != null 1495d071c6802a03031b26de7b92a76d03849681149bFelipe Leme && (changedPackage == null || changedPackage.equals(targetPackage)) 1496d071c6802a03031b26de7b92a76d03849681149bFelipe Leme && mIPackageManager.getPackageInfo(targetPackage, 0, userHandle) == null; 1497d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } catch (RemoteException e) { 1498d071c6802a03031b26de7b92a76d03849681149bFelipe Leme // Shouldn't happen 1499e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 1500e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme 1501e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme return false; 1502e184f6610284ca80692d7e6789483375a7ca2f39Felipe Leme } 1503d071c6802a03031b26de7b92a76d03849681149bFelipe Leme 1504809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme /** 1505809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme * Unit test will subclass it to inject mocks. 1506d071c6802a03031b26de7b92a76d03849681149bFelipe Leme */ 1507d071c6802a03031b26de7b92a76d03849681149bFelipe Leme @VisibleForTesting 1508d071c6802a03031b26de7b92a76d03849681149bFelipe Leme static class Injector { 1509809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme 1510809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme public final Context mContext; 15117447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme 15127447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme Injector(Context context) { 15137447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme mContext = context; 15147447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme } 15157447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme 15167447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme Context createContextAsUser(UserHandle user) throws PackageManager.NameNotFoundException { 15177447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme final String packageName = mContext.getPackageName(); 15187447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme return mContext.createPackageContextAsUser(packageName, 0, user); 15197447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme } 1520d071c6802a03031b26de7b92a76d03849681149bFelipe Leme 15217447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme Resources getResources() { 1522d071c6802a03031b26de7b92a76d03849681149bFelipe Leme return mContext.getResources(); 1523d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } 1524d071c6802a03031b26de7b92a76d03849681149bFelipe Leme 1525d071c6802a03031b26de7b92a76d03849681149bFelipe Leme Owners newOwners() { 1526d071c6802a03031b26de7b92a76d03849681149bFelipe Leme return new Owners(getUserManager(), getUserManagerInternal(), 15276ae5c4f52b55943a7a84fb3cb47710effe788e11Felipe Leme getPackageManagerInternal()); 1528d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } 152975876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme 153075876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme UserManager getUserManager() { 153175876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme return UserManager.get(mContext); 153275876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme } 153375876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme 153475876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme UserManagerInternal getUserManagerInternal() { 153575876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme return LocalServices.getService(UserManagerInternal.class); 153675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme } 1537f029297f673ae06d219bd727a318a48b885db6fdFelipe Leme 1538d071c6802a03031b26de7b92a76d03849681149bFelipe Leme PackageManagerInternal getPackageManagerInternal() { 1539d071c6802a03031b26de7b92a76d03849681149bFelipe Leme return LocalServices.getService(PackageManagerInternal.class); 1540d071c6802a03031b26de7b92a76d03849681149bFelipe Leme } 15417447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme 1542d071c6802a03031b26de7b92a76d03849681149bFelipe Leme NotificationManager getNotificationManager() { 1543d071c6802a03031b26de7b92a76d03849681149bFelipe Leme return mContext.getSystemService(NotificationManager.class); 1544bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme } 1545809d74e92c16cf694c929b8ca2b54515af13e9feFelipe Leme 15469a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme IIpConnectivityMetrics getIIpConnectivityMetrics() { 1547e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme return (IIpConnectivityMetrics) IIpConnectivityMetrics.Stub.asInterface( 1548ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris ServiceManager.getService(IpConnectivityLog.SERVICE_NAME)); 1549ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris } 1550ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris 1551ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris PackageManager getPackageManager() { 1552ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris return mContext.getPackageManager(); 1553ed9354fc846895dc53397fbb5323bef00b3a3834Christopher Ferris } 15542628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme 15552628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme PowerManagerInternal getPowerManagerInternal() { 15569a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return LocalServices.getService(PowerManagerInternal.class); 15579a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 15582628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme 15592628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme TelephonyManager getTelephonyManager() { 156071bbfc57974331dce79242ce806d92035fce06baFelipe Leme return TelephonyManager.from(mContext); 15619a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 1562f8124bd485e29fa013313426463dfe1647e69765Felipe Leme 1563570e6ec1230c9e3458e0de57ebfe2aa2be043293Ian Pedowitz TrustManager getTrustManager() { 1564f8124bd485e29fa013313426463dfe1647e69765Felipe Leme return (TrustManager) mContext.getSystemService(Context.TRUST_SERVICE); 1565f8124bd485e29fa013313426463dfe1647e69765Felipe Leme } 156671bbfc57974331dce79242ce806d92035fce06baFelipe Leme 156771bbfc57974331dce79242ce806d92035fce06baFelipe Leme AlarmManager getAlarmManager() { 1568bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme return (AlarmManager) mContext.getSystemService(AlarmManager.class); 15692b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme } 1570ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 15712b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme IWindowManager getIWindowManager() { 157271bbfc57974331dce79242ce806d92035fce06baFelipe Leme return IWindowManager.Stub 15736ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme .asInterface(ServiceManager.getService(Context.WINDOW_SERVICE)); 15746ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 15756ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 15766ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme IActivityManager getIActivityManager() { 15776ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return ActivityManager.getService(); 157871bbfc57974331dce79242ce806d92035fce06baFelipe Leme } 15799a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 158071bbfc57974331dce79242ce806d92035fce06baFelipe Leme IPackageManager getIPackageManager() { 15819a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return AppGlobals.getPackageManager(); 158275876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme } 1583e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme 1584e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme IBackupManager getIBackupManager() { 1585e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme return IBackupManager.Stub.asInterface( 1586e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme ServiceManager.getService(Context.BACKUP_SERVICE)); 1587e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme } 1588e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme 1589e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme IAudioService getIAudioService() { 1590e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme return IAudioService.Stub.asInterface(ServiceManager.getService(Context.AUDIO_SERVICE)); 15919a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 15929a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 159371bbfc57974331dce79242ce806d92035fce06baFelipe Leme boolean isBuildDebuggable() { 15941e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme return Build.IS_DEBUGGABLE; 15959a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 15969a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 15979a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme LockPatternUtils newLockPatternUtils() { 15989a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return new LockPatternUtils(mContext); 15991d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme } 16009a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 16011e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme boolean storageManagerIsFileBasedEncryptionEnabled() { 16021e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme return StorageManager.isFileEncryptedNativeOnly(); 1603c6bc8bc4f05ad7d20e931944fb5042b578bc2e53Felipe Leme } 16041e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme 16051d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme boolean storageManagerIsNonDefaultBlockEncrypted() { 16061e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme long identity = Binder.clearCallingIdentity(); 16071e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme try { 16089a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return StorageManager.isNonDefaultBlockEncrypted(); 1609dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme } finally { 1610dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme Binder.restoreCallingIdentity(identity); 1611cfaa07ad3207cc2b64586f388ecad95d60082c88Christopher Tate } 1612dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme } 1613a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme 16142b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme boolean storageManagerIsEncrypted() { 1615e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme return StorageManager.isEncrypted(); 161675876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme } 16177447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme 1618dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme boolean storageManagerIsEncryptable() { 1619dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme return StorageManager.isEncryptable(); 1620a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme } 1621dcd1f0da541304421648c77db287ebe56339a6beFelipe Leme 1622aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme Looper getMyLooper() { 16239a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return Looper.myLooper(); 1624aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme } 162571bbfc57974331dce79242ce806d92035fce06baFelipe Leme 162671bbfc57974331dce79242ce806d92035fce06baFelipe Leme WifiManager getWifiManager() { 162771bbfc57974331dce79242ce806d92035fce06baFelipe Leme return mContext.getSystemService(WifiManager.class); 1628f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich } 1629f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich 1630f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich long binderClearCallingIdentity() { 1631f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich return Binder.clearCallingIdentity(); 1632f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich } 1633f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich 1634f3599b35c5f7f86cced0f3386a6c80e0b552f358Nick Kralevich void binderRestoreCallingIdentity(long token) { 16351f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau Binder.restoreCallingIdentity(token); 163635b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme } 16371f794c442cc63f7962c21e8e712adeca338af63eJohn Michelau 1638f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross int binderGetCallingUid() { 16399a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return Binder.getCallingUid(); 16409a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 16413634a1e3459cb609da709646107e246cafbc01f9Felipe Leme 1642cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme int binderGetCallingPid() { 16433634a1e3459cb609da709646107e246cafbc01f9Felipe Leme return Binder.getCallingPid(); 1644cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme } 1645bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme 1646e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme UserHandle binderGetCallingUserHandle() { 1647e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme return Binder.getCallingUserHandle(); 1648e338bf60701e5b955ab0a097f2631f2190218894Felipe Leme } 16491e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme 16509a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme boolean binderIsCallingUidMyUid() { 16519a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return getCallingUid() == Process.myUid(); 16521d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme } 16531e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme 16541e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme final int userHandleGetCallingUserId() { 16551e9edc619c6b1ca3998a26eaa4882b55ce801f12Felipe Leme return UserHandle.getUserId(binderGetCallingUid()); 165671bbfc57974331dce79242ce806d92035fce06baFelipe Leme } 16579a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 16589a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme File environmentGetUserSystemDirectory(int userId) { 16599a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return Environment.getUserSystemDirectory(userId); 16609a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 16616fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme 16626e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme void powerManagerGoToSleep(long time, int reason, int flags) { 16636e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme mContext.getSystemService(PowerManager.class).goToSleep(time, reason, flags); 16646e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme } 16659a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 16669a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme void powerManagerReboot(String reason) { 16676fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme mContext.getSystemService(PowerManager.class).reboot(reason); 16689a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 16696fe9db67f6c92d5fbf87d371da5cca412f672630Felipe Leme 1670f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross void recoverySystemRebootWipeUserData(boolean shutdown, String reason, boolean force) 1671d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme throws IOException { 1672d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme RecoverySystem.rebootWipeUserData(mContext, shutdown, reason, force); 1673d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme } 1674d8b94e5e61ca744962400ebefa33c15c459571c4Felipe Leme 1675608385dd151e36a93f3e3f4a7514b1e720d20ae9Felipe Leme boolean systemPropertiesGetBoolean(String key, boolean def) { 1676608385dd151e36a93f3e3f4a7514b1e720d20ae9Felipe Leme return SystemProperties.getBoolean(key, def); 1677cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme } 1678bbaf3c11c4723be0f6b56ef603e11b0baaa92429Felipe Leme 1679f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross long systemPropertiesGetLong(String key, long def) { 16806ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return SystemProperties.getLong(key, def); 16816ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 16826ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 16836ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme String systemPropertiesGet(String key, String def) { 16846ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return SystemProperties.get(key, def); 16856ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 16866ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 16876ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme String systemPropertiesGet(String key) { 16886ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return SystemProperties.get(key); 16896ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 16906ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 16916ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme void systemPropertiesSet(String key, String value) { 16926ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme SystemProperties.set(key, value); 16936ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 16946ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 16956ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme boolean userManagerIsSplitSystemUser() { 16966ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return UserManager.isSplitSystemUser(); 169771a74ac75c8687195d27642fa0db31a796102c59Felipe Leme } 16986ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 16996ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme String getDevicePolicyFilePathForSystemUser() { 17006ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return "/data/system/"; 17016ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 17026ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 17036ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme PendingIntent pendingIntentGetActivityAsUser(Context context, int requestCode, 1704fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan @NonNull Intent intent, int flags, Bundle options, UserHandle user) { 17056ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return PendingIntent.getActivityAsUser( 17066ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme context, requestCode, intent, flags, options, user); 1707e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme } 17086ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 17096ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme void registerContentObserver(Uri uri, boolean notifyForDescendents, 1710fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan ContentObserver observer, int userHandle) { 17116ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme mContext.getContentResolver().registerContentObserver(uri, notifyForDescendents, 17126ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme observer, userHandle); 17136ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 17146ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 17156ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme int settingsSecureGetIntForUser(String name, int def, int userHandle) { 17166ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return Settings.Secure.getIntForUser(mContext.getContentResolver(), 17176ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme name, def, userHandle); 17186ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 17196ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 17206ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme String settingsSecureGetStringForUser(String name, int userHandle) { 17216ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme return Settings.Secure.getStringForUser(mContext.getContentResolver(), name, 1722fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan userHandle); 17236ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 17246ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 17256ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme void settingsSecurePutIntForUser(String name, int value, int userHandle) { 172632af8c2aefd9a31e851c8f17168f19afcb5efb18Erik Kline Settings.Secure.putIntForUser(mContext.getContentResolver(), 17276ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme name, value, userHandle); 17286ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 17296ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme 1730d3b809baff20a2ff7e41f4add801f71cce0665f7Lorenzo Colitti void settingsSecurePutStringForUser(String name, String value, int userHandle) { 17316ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme Settings.Secure.putStringForUser(mContext.getContentResolver(), 17326ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme name, value, userHandle); 17336ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme } 1734fdf52d3697aa0396bd9d8883892937b99a6772a0Srinath Sridharan 17356ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme void settingsGlobalPutStringForUser(String name, String value, int userHandle) { 17366ec6ac46c457fb54752c7044647e77b4008ed2cfFelipe Leme Settings.Global.putStringForUser(mContext.getContentResolver(), 1737f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross name, value, userHandle); 173855b42a67f69767976ff16ab443b3e7142db693e1Felipe Leme } 173971bbfc57974331dce79242ce806d92035fce06baFelipe Leme 1740f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross void settingsSecurePutInt(String name, int value) { 1741f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross Settings.Secure.putInt(mContext.getContentResolver(), name, value); 1742f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross } 17436e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme 17446e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme int settingsGlobalGetInt(String name, int def) { 1745ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme return Settings.Global.getInt(mContext.getContentResolver(), name, def); 1746ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme } 174796c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme 174875876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme void settingsGlobalPutInt(String name, int value) { 1749ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme Settings.Global.putInt(mContext.getContentResolver(), name, value); 175096c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme } 1751ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 1752ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme void settingsSecurePutString(String name, String value) { 175396c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme Settings.Secure.putString(mContext.getContentResolver(), name, value); 1754ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme } 1755ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 175696c2bbbf1ab3477f061f2b1b05482f5aec8c5dfaFelipe Leme void settingsGlobalPutString(String name, String value) { 1757ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme Settings.Global.putString(mContext.getContentResolver(), name, value); 1758ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme } 1759ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 17602b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme void securityLogSetLoggingEnabledProperty(boolean enabled) { 17612b9b06ca7c54a6d7b6b2188dbd884b445b052d34Felipe Leme SecurityLog.setLoggingEnabledProperty(enabled); 17629a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 17639a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 17649a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme boolean securityLogGetLoggingEnabledProperty() { 17659a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme return SecurityLog.getLoggingEnabledProperty(); 17669a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 1767ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 17689a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme boolean securityLogIsLoggingEnabled() { 1769ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme return SecurityLog.isLoggingEnabled(); 1770ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme } 1771ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme 1772ad5f6c475934ac6a658a203069a9f055540946e7Felipe Leme KeyChainConnection keyChainBindAsUser(UserHandle user) throws InterruptedException { 17736e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme return KeyChain.bindAsUser(mContext, user); 17746e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme } 17751d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme } 1776cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme 17776e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme /** 17786e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme * Instantiates the service. 17796e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme */ 17809127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme public DevicePolicyManagerService(Context context) { 17819a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme this(new Injector(context)); 17829a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 17839a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 17849a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme @VisibleForTesting 17859a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme DevicePolicyManagerService(Injector injector) { 17861d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme mInjector = injector; 17879127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme mContext = Preconditions.checkNotNull(injector.mContext); 17889a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mHandler = new Handler(Preconditions.checkNotNull(injector.getMyLooper())); 17899127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme mOwners = Preconditions.checkNotNull(injector.newOwners()); 17909127435ffbb081fe91a30169f394a57fd31fd05eFelipe Leme 17916e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme mUserManager = Preconditions.checkNotNull(injector.getUserManager()); 17926e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme mUserManagerInternal = Preconditions.checkNotNull(injector.getUserManagerInternal()); 17936e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme mIPackageManager = Preconditions.checkNotNull(injector.getIPackageManager()); 17949a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mTelephonyManager = Preconditions.checkNotNull(injector.getTelephonyManager()); 17959a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 17969a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mLocalService = new LocalService(); 17979a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mLockPatternUtils = injector.newLockPatternUtils(); 17989a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 17991d486fe3847c831b9d57843cda209ed86853ee21Felipe Leme // TODO: why does SecurityLogMonitor need to be created even when mHasFeature == false? 18009a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mSecurityLogMonitor = new SecurityLogMonitor(this); 18016e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme 18026e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme mHasFeature = mInjector.getPackageManager() 18032628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme .hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN); 18042628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme mIsWatch = mInjector.getPackageManager() 18059a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme .hasSystemFeature(PackageManager.FEATURE_WATCH); 1806e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme mBackgroundHandler = BackgroundThread.getHandler(); 1807e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme 18089a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme // Needed when mHasFeature == false, because it controls the certificate warning text. 18092628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme mCertificateMonitor = new CertificateMonitor(this, mInjector, mBackgroundHandler); 18109a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme 18112628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme mDeviceAdminServiceController = new DeviceAdminServiceController(this); 18122628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme 1813f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross if (!mHasFeature) { 1814f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross // Skip the rest of the initialization 1815cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme return; 181635b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme } 181735b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme 181835b8cf1902bba437eb9c3f14cb69cf403695ebe8Felipe Leme IntentFilter filter = new IntentFilter(); 1819cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme filter.addAction(Intent.ACTION_BOOT_COMPLETED); 1820cc2a2fa64e22378d980ae0ae95c8865ebea05f69Felipe Leme filter.addAction(ACTION_EXPIRED_PASSWORD_NOTIFICATION); 18211dc94e315680b47fe430ef90f46c50a25c92fb6dJeff Brown filter.addAction(Intent.ACTION_USER_ADDED); 182271bbfc57974331dce79242ce806d92035fce06baFelipe Leme filter.addAction(Intent.ACTION_USER_REMOVED); 18239a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme filter.addAction(Intent.ACTION_USER_STARTED); 18249a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY); 1825aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 1826cfaa07ad3207cc2b64586f388ecad95d60082c88Christopher Tate filter = new IntentFilter(); 182736b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme filter.addAction(Intent.ACTION_PACKAGE_CHANGED); 1828a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 1829e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 183075876a2c0649b8cde36329ca0a1dc6e349af6493Felipe Leme filter.addAction(Intent.ACTION_PACKAGE_ADDED); 18317447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme filter.addDataScheme("package"); 18329a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 18339a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme filter = new IntentFilter(); 183436b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED); 1835aabfcae816485b39b244ba372c5b2678d2af03beFelipe Leme mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler); 183636b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme 183736b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme LocalServices.addService(DevicePolicyManagerInternal.class, mLocalService); 183836b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme 18399a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme mSetupContentObserver = new SetupContentObserver(mHandler); 184036b3f6ff17e456dea81501006e33d5fdd1d3b480Felipe Leme } 1841b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla 1842b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla /** 1843b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla * Creates and loads the policy data from xml. 1844b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla * @param userHandle the user for whom to load the policy data 1845b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla * @return 1846b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla */ 1847b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla @NonNull 1848b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla DevicePolicyData getUserData(int userHandle) { 1849b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla synchronized (this) { 1850b53a1c9b4df27a7a66c9448778eace166a0ce14cNaveen Kalla DevicePolicyData policy = mUserData.get(userHandle); 18514db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski if (policy == null) { 18524db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski policy = new DevicePolicyData(userHandle); 18534db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski mUserData.append(userHandle, policy); 18549a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme loadSettingsLocked(policy, userHandle); 1855a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme } 1856a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme return policy; 18574db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski } 1858a4ef1f050ce4f4a9976057f1efa34a4ff5ec0ac8Felipe Leme } 18594db754fd7c13993d81d98157f10e8015422d1e3aMichal Karpinski 18606e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme /** 1861cbce55d4fdbdd2e5a5515054c48d2116c5db2712Felipe Leme * Creates and loads the policy data from xml for data that is shared between 18626e01fa6f95fb20a2faab33561056d2e74cc097cbFelipe Leme * various profiles of a user. In contrast to {@link #getUserData(int)} 186327f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey * it allows access to data of users other than the calling user. 186427f9e6d849fce956c9b8f1ad5c3d9a954501a76bJeff Sharkey * 18657447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme * This function should only be used for shared data, e.g. everything regarding 18667447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme * passwords and should be removed once multiple screen locks are present. 18677447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme * @param userHandle the user for whom to load the policy data 18687447d7c3d74b28f1a071b1d3503212cc8ad08d68Felipe Leme * @return 1869f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross */ 1870107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme DevicePolicyData getUserDataUnchecked(int userHandle) { 1871107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme long ident = mInjector.binderClearCallingIdentity(); 1872107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme try { 1873107a05f72e711c92545d0be648ab79c4f858f372Felipe Leme return getUserData(userHandle); 18749a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } finally { 1875e844a9d60a54c7dd6dbf0a8f44167b484324d08dFelipe Leme mInjector.binderRestoreCallingIdentity(ident); 18769a523aed06ef962f67385ac88191b08dc91059f4Felipe Leme } 18772628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme } 18782628e9e939fda323fa44c5cb743f4a77b12a312aFelipe Leme 1879f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross void removeUserData(int userHandle) { 1880f45fa6b2853cc32385375a0b63ee39ad6a968869Colin Cross synchronized (this) { 1881 if (userHandle == UserHandle.USER_SYSTEM) { 1882 Slog.w(LOG_TAG, "Tried to remove device policy file for user 0! Ignoring."); 1883 return; 1884 } 1885 mOwners.removeProfileOwner(userHandle); 1886 mOwners.writeProfileOwner(userHandle); 1887 1888 DevicePolicyData policy = mUserData.get(userHandle); 1889 if (policy != null) { 1890 mUserData.remove(userHandle); 1891 } 1892 File policyFile = new File(mInjector.environmentGetUserSystemDirectory(userHandle), 1893 DEVICE_POLICIES_XML); 1894 policyFile.delete(); 1895 Slog.i(LOG_TAG, "Removed device policy file " + policyFile.getAbsolutePath()); 1896 } 1897 updateScreenCaptureDisabledInWindowManager(userHandle, false /* default value */); 1898 } 1899 1900 void loadOwners() { 1901 synchronized (this) { 1902 mOwners.load(); 1903 setDeviceOwnerSystemPropertyLocked(); 1904 findOwnerComponentIfNecessaryLocked(); 1905 migrateUserRestrictionsIfNecessaryLocked(); 1906 setDefaultEnabledUserRestrictionsIfNecessaryLocked(); 1907 1908 // TODO PO may not have a class name either due to b/17652534. Address that too. 1909 1910 updateDeviceOwnerLocked(); 1911 } 1912 } 1913 1914 private void setDefaultEnabledUserRestrictionsIfNecessaryLocked() { 1915 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 1916 if (deviceOwner != null 1917 && !UserRestrictionsUtils.getDefaultEnabledForDeviceOwner().equals( 1918 deviceOwner.defaultEnabledRestrictionsAlreadySet)) { 1919 Slog.i(LOG_TAG,"New user restrictions need to be set by default for the device owner"); 1920 1921 if (VERBOSE_LOG) { 1922 Slog.d(LOG_TAG,"Default enabled restrictions for DO: " 1923 + UserRestrictionsUtils.getDefaultEnabledForDeviceOwner() 1924 + ". Restrictions already enabled: " 1925 + deviceOwner.defaultEnabledRestrictionsAlreadySet); 1926 } 1927 1928 Set<String> restrictionsToSet = new ArraySet<>( 1929 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner()); 1930 restrictionsToSet.removeAll(deviceOwner.defaultEnabledRestrictionsAlreadySet); 1931 if (!restrictionsToSet.isEmpty()) { 1932 for (String restriction : restrictionsToSet) { 1933 deviceOwner.ensureUserRestrictions().putBoolean(restriction, true); 1934 } 1935 deviceOwner.defaultEnabledRestrictionsAlreadySet.addAll(restrictionsToSet); 1936 Slog.i(LOG_TAG, 1937 "Enabled the following restrictions by default: " + restrictionsToSet); 1938 1939 saveUserRestrictionsLocked(mOwners.getDeviceOwnerUserId()); 1940 } 1941 } 1942 } 1943 1944 private void setDeviceOwnerSystemPropertyLocked() { 1945 final boolean deviceProvisioned = 1946 mInjector.settingsGlobalGetInt(Settings.Global.DEVICE_PROVISIONED, 0) != 0; 1947 // If the device is not provisioned and there is currently no device owner, do not set the 1948 // read-only system property yet, since Device owner may still be provisioned. For Wear 1949 // devices, if there is already a device owner then it's OK to set the property to true now, 1950 // regardless the provision state. 1951 final boolean isWatchWithDeviceOwner = mIsWatch && mOwners.hasDeviceOwner(); 1952 if (!isWatchWithDeviceOwner && !deviceProvisioned) { 1953 return; 1954 } 1955 // Still at the first stage of CryptKeeper double bounce, mOwners.hasDeviceOwner is 1956 // always false at this point. 1957 if (StorageManager.inCryptKeeperBounce()) { 1958 return; 1959 } 1960 1961 if (!TextUtils.isEmpty(mInjector.systemPropertiesGet(PROPERTY_DEVICE_OWNER_PRESENT))) { 1962 Slog.w(LOG_TAG, "Trying to set ro.device_owner, but it has already been set?"); 1963 } else { 1964 if (mOwners.hasDeviceOwner()) { 1965 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "true"); 1966 Slog.i(LOG_TAG, "Set ro.device_owner property to true"); 1967 1968 if (mInjector.securityLogGetLoggingEnabledProperty()) { 1969 mSecurityLogMonitor.start(); 1970 maybePauseDeviceWideLoggingLocked(); 1971 } 1972 } else { 1973 mInjector.systemPropertiesSet(PROPERTY_DEVICE_OWNER_PRESENT, "false"); 1974 Slog.i(LOG_TAG, "Set ro.device_owner property to false"); 1975 } 1976 } 1977 } 1978 1979 private void findOwnerComponentIfNecessaryLocked() { 1980 if (!mOwners.hasDeviceOwner()) { 1981 return; 1982 } 1983 final ComponentName doComponentName = mOwners.getDeviceOwnerComponent(); 1984 1985 if (!TextUtils.isEmpty(doComponentName.getClassName())) { 1986 return; // Already a full component name. 1987 } 1988 1989 final ComponentName doComponent = findAdminComponentWithPackageLocked( 1990 doComponentName.getPackageName(), 1991 mOwners.getDeviceOwnerUserId()); 1992 if (doComponent == null) { 1993 Slog.e(LOG_TAG, "Device-owner isn't registered as device-admin"); 1994 } else { 1995 mOwners.setDeviceOwnerWithRestrictionsMigrated( 1996 doComponent, 1997 mOwners.getDeviceOwnerName(), 1998 mOwners.getDeviceOwnerUserId(), 1999 !mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()); 2000 mOwners.writeDeviceOwner(); 2001 if (VERBOSE_LOG) { 2002 Log.v(LOG_TAG, "Device owner component filled in"); 2003 } 2004 } 2005 } 2006 2007 /** 2008 * We didn't use to persist user restrictions for each owners but only persisted in user 2009 * manager. 2010 */ 2011 private void migrateUserRestrictionsIfNecessaryLocked() { 2012 boolean migrated = false; 2013 // Migrate for the DO. Basically all restrictions should be considered to be set by DO, 2014 // except for the "system controlled" ones. 2015 if (mOwners.getDeviceOwnerUserRestrictionsNeedsMigration()) { 2016 if (VERBOSE_LOG) { 2017 Log.v(LOG_TAG, "Migrating DO user restrictions"); 2018 } 2019 migrated = true; 2020 2021 // Migrate user 0 restrictions to DO. 2022 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 2023 2024 migrateUserRestrictionsForUser(UserHandle.SYSTEM, deviceOwnerAdmin, 2025 /* exceptionList =*/ null, /* isDeviceOwner =*/ true); 2026 2027 // Push DO user restrictions to user manager. 2028 pushUserRestrictions(UserHandle.USER_SYSTEM); 2029 2030 mOwners.setDeviceOwnerUserRestrictionsMigrated(); 2031 } 2032 2033 // Migrate for POs. 2034 2035 // The following restrictions can be set on secondary users by the device owner, so we 2036 // assume they're not from the PO. 2037 final Set<String> secondaryUserExceptionList = Sets.newArraySet( 2038 UserManager.DISALLOW_OUTGOING_CALLS, 2039 UserManager.DISALLOW_SMS); 2040 2041 for (UserInfo ui : mUserManager.getUsers()) { 2042 final int userId = ui.id; 2043 if (mOwners.getProfileOwnerUserRestrictionsNeedsMigration(userId)) { 2044 if (VERBOSE_LOG) { 2045 Log.v(LOG_TAG, "Migrating PO user restrictions for user " + userId); 2046 } 2047 migrated = true; 2048 2049 final ActiveAdmin profileOwnerAdmin = getProfileOwnerAdminLocked(userId); 2050 2051 final Set<String> exceptionList = 2052 (userId == UserHandle.USER_SYSTEM) ? null : secondaryUserExceptionList; 2053 2054 migrateUserRestrictionsForUser(ui.getUserHandle(), profileOwnerAdmin, 2055 exceptionList, /* isDeviceOwner =*/ false); 2056 2057 // Note if a secondary user has no PO but has a DA that disables camera, we 2058 // don't get here and won't push the camera user restriction to UserManager 2059 // here. That's okay because we'll push user restrictions anyway when a user 2060 // starts. But we still do it because we want to let user manager persist 2061 // upon migration. 2062 pushUserRestrictions(userId); 2063 2064 mOwners.setProfileOwnerUserRestrictionsMigrated(userId); 2065 } 2066 } 2067 if (VERBOSE_LOG && migrated) { 2068 Log.v(LOG_TAG, "User restrictions migrated."); 2069 } 2070 } 2071 2072 private void migrateUserRestrictionsForUser(UserHandle user, ActiveAdmin admin, 2073 Set<String> exceptionList, boolean isDeviceOwner) { 2074 final Bundle origRestrictions = mUserManagerInternal.getBaseUserRestrictions( 2075 user.getIdentifier()); 2076 2077 final Bundle newBaseRestrictions = new Bundle(); 2078 final Bundle newOwnerRestrictions = new Bundle(); 2079 2080 for (String key : origRestrictions.keySet()) { 2081 if (!origRestrictions.getBoolean(key)) { 2082 continue; 2083 } 2084 final boolean canOwnerChange = isDeviceOwner 2085 ? UserRestrictionsUtils.canDeviceOwnerChange(key) 2086 : UserRestrictionsUtils.canProfileOwnerChange(key, user.getIdentifier()); 2087 2088 if (!canOwnerChange || (exceptionList!= null && exceptionList.contains(key))) { 2089 newBaseRestrictions.putBoolean(key, true); 2090 } else { 2091 newOwnerRestrictions.putBoolean(key, true); 2092 } 2093 } 2094 2095 if (VERBOSE_LOG) { 2096 Log.v(LOG_TAG, "origRestrictions=" + origRestrictions); 2097 Log.v(LOG_TAG, "newBaseRestrictions=" + newBaseRestrictions); 2098 Log.v(LOG_TAG, "newOwnerRestrictions=" + newOwnerRestrictions); 2099 } 2100 mUserManagerInternal.setBaseUserRestrictionsByDpmsForMigration(user.getIdentifier(), 2101 newBaseRestrictions); 2102 2103 if (admin != null) { 2104 admin.ensureUserRestrictions().clear(); 2105 admin.ensureUserRestrictions().putAll(newOwnerRestrictions); 2106 } else { 2107 Slog.w(LOG_TAG, "ActiveAdmin for DO/PO not found. user=" + user.getIdentifier()); 2108 } 2109 saveSettingsLocked(user.getIdentifier()); 2110 } 2111 2112 private ComponentName findAdminComponentWithPackageLocked(String packageName, int userId) { 2113 final DevicePolicyData policy = getUserData(userId); 2114 final int n = policy.mAdminList.size(); 2115 ComponentName found = null; 2116 int nFound = 0; 2117 for (int i = 0; i < n; i++) { 2118 final ActiveAdmin admin = policy.mAdminList.get(i); 2119 if (packageName.equals(admin.info.getPackageName())) { 2120 // Found! 2121 if (nFound == 0) { 2122 found = admin.info.getComponent(); 2123 } 2124 nFound++; 2125 } 2126 } 2127 if (nFound > 1) { 2128 Slog.w(LOG_TAG, "Multiple DA found; assume the first one is DO."); 2129 } 2130 return found; 2131 } 2132 2133 /** 2134 * Set an alarm for an upcoming event - expiration warning, expiration, or post-expiration 2135 * reminders. Clears alarm if no expirations are configured. 2136 */ 2137 private void setExpirationAlarmCheckLocked(Context context, int userHandle, boolean parent) { 2138 final long expiration = getPasswordExpirationLocked(null, userHandle, parent); 2139 final long now = System.currentTimeMillis(); 2140 final long timeToExpire = expiration - now; 2141 final long alarmTime; 2142 if (expiration == 0) { 2143 // No expirations are currently configured: Cancel alarm. 2144 alarmTime = 0; 2145 } else if (timeToExpire <= 0) { 2146 // The password has already expired: Repeat every 24 hours. 2147 alarmTime = now + MS_PER_DAY; 2148 } else { 2149 // Selecting the next alarm time: Roll forward to the next 24 hour multiple before 2150 // the expiration time. 2151 long alarmInterval = timeToExpire % MS_PER_DAY; 2152 if (alarmInterval == 0) { 2153 alarmInterval = MS_PER_DAY; 2154 } 2155 alarmTime = now + alarmInterval; 2156 } 2157 2158 long token = mInjector.binderClearCallingIdentity(); 2159 try { 2160 int affectedUserHandle = parent ? getProfileParentId(userHandle) : userHandle; 2161 AlarmManager am = mInjector.getAlarmManager(); 2162 PendingIntent pi = PendingIntent.getBroadcastAsUser(context, REQUEST_EXPIRE_PASSWORD, 2163 new Intent(ACTION_EXPIRED_PASSWORD_NOTIFICATION), 2164 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT, 2165 UserHandle.of(affectedUserHandle)); 2166 am.cancel(pi); 2167 if (alarmTime != 0) { 2168 am.set(AlarmManager.RTC, alarmTime, pi); 2169 } 2170 } finally { 2171 mInjector.binderRestoreCallingIdentity(token); 2172 } 2173 } 2174 2175 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle) { 2176 ActiveAdmin admin = getUserData(userHandle).mAdminMap.get(who); 2177 if (admin != null 2178 && who.getPackageName().equals(admin.info.getActivityInfo().packageName) 2179 && who.getClassName().equals(admin.info.getActivityInfo().name)) { 2180 return admin; 2181 } 2182 return null; 2183 } 2184 2185 ActiveAdmin getActiveAdminUncheckedLocked(ComponentName who, int userHandle, boolean parent) { 2186 if (parent) { 2187 enforceManagedProfile(userHandle, "call APIs on the parent profile"); 2188 } 2189 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2190 if (admin != null && parent) { 2191 admin = admin.getParentActiveAdmin(); 2192 } 2193 return admin; 2194 } 2195 2196 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy) 2197 throws SecurityException { 2198 final int callingUid = mInjector.binderGetCallingUid(); 2199 2200 ActiveAdmin result = getActiveAdminWithPolicyForUidLocked(who, reqPolicy, callingUid); 2201 if (result != null) { 2202 return result; 2203 } 2204 2205 if (who != null) { 2206 final int userId = UserHandle.getUserId(callingUid); 2207 final DevicePolicyData policy = getUserData(userId); 2208 ActiveAdmin admin = policy.mAdminMap.get(who); 2209 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2210 throw new SecurityException("Admin " + admin.info.getComponent() 2211 + " does not own the device"); 2212 } 2213 if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2214 throw new SecurityException("Admin " + admin.info.getComponent() 2215 + " does not own the profile"); 2216 } 2217 throw new SecurityException("Admin " + admin.info.getComponent() 2218 + " did not specify uses-policy for: " 2219 + admin.info.getTagForPolicy(reqPolicy)); 2220 } else { 2221 throw new SecurityException("No active admin owned by uid " 2222 + mInjector.binderGetCallingUid() + " for policy #" + reqPolicy); 2223 } 2224 } 2225 2226 ActiveAdmin getActiveAdminForCallerLocked(ComponentName who, int reqPolicy, boolean parent) 2227 throws SecurityException { 2228 if (parent) { 2229 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), 2230 "call APIs on the parent profile"); 2231 } 2232 ActiveAdmin admin = getActiveAdminForCallerLocked(who, reqPolicy); 2233 return parent ? admin.getParentActiveAdmin() : admin; 2234 } 2235 /** 2236 * Find the admin for the component and userId bit of the uid, then check 2237 * the admin's uid matches the uid. 2238 */ 2239 private ActiveAdmin getActiveAdminForUidLocked(ComponentName who, int uid) { 2240 final int userId = UserHandle.getUserId(uid); 2241 final DevicePolicyData policy = getUserData(userId); 2242 ActiveAdmin admin = policy.mAdminMap.get(who); 2243 if (admin == null) { 2244 throw new SecurityException("No active admin " + who); 2245 } 2246 if (admin.getUid() != uid) { 2247 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2248 } 2249 return admin; 2250 } 2251 2252 private ActiveAdmin getActiveAdminWithPolicyForUidLocked(ComponentName who, int reqPolicy, 2253 int uid) { 2254 // Try to find an admin which can use reqPolicy 2255 final int userId = UserHandle.getUserId(uid); 2256 final DevicePolicyData policy = getUserData(userId); 2257 if (who != null) { 2258 ActiveAdmin admin = policy.mAdminMap.get(who); 2259 if (admin == null) { 2260 throw new SecurityException("No active admin " + who); 2261 } 2262 if (admin.getUid() != uid) { 2263 throw new SecurityException("Admin " + who + " is not owned by uid " + uid); 2264 } 2265 if (isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, userId)) { 2266 return admin; 2267 } 2268 } else { 2269 for (ActiveAdmin admin : policy.mAdminList) { 2270 if (admin.getUid() == uid && isActiveAdminWithPolicyForUserLocked(admin, reqPolicy, 2271 userId)) { 2272 return admin; 2273 } 2274 } 2275 } 2276 2277 return null; 2278 } 2279 2280 @VisibleForTesting 2281 boolean isActiveAdminWithPolicyForUserLocked(ActiveAdmin admin, int reqPolicy, 2282 int userId) { 2283 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userId); 2284 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userId); 2285 2286 if (reqPolicy == DeviceAdminInfo.USES_POLICY_DEVICE_OWNER) { 2287 return ownsDevice; 2288 } else if (reqPolicy == DeviceAdminInfo.USES_POLICY_PROFILE_OWNER) { 2289 // DO always has the PO power. 2290 return ownsDevice || ownsProfile; 2291 } else { 2292 return admin.info.usesPolicy(reqPolicy); 2293 } 2294 } 2295 2296 void sendAdminCommandLocked(ActiveAdmin admin, String action) { 2297 sendAdminCommandLocked(admin, action, null); 2298 } 2299 2300 void sendAdminCommandLocked(ActiveAdmin admin, String action, BroadcastReceiver result) { 2301 sendAdminCommandLocked(admin, action, null, result); 2302 } 2303 2304 /** 2305 * Send an update to one specific admin, get notified when that admin returns a result. 2306 */ 2307 void sendAdminCommandLocked(ActiveAdmin admin, String action, Bundle adminExtras, 2308 BroadcastReceiver result) { 2309 Intent intent = new Intent(action); 2310 intent.setComponent(admin.info.getComponent()); 2311 if (action.equals(DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING)) { 2312 intent.putExtra("expiration", admin.passwordExpirationDate); 2313 } 2314 if (adminExtras != null) { 2315 intent.putExtras(adminExtras); 2316 } 2317 if (result != null) { 2318 mContext.sendOrderedBroadcastAsUser(intent, admin.getUserHandle(), 2319 null, result, mHandler, Activity.RESULT_OK, null, null); 2320 } else { 2321 mContext.sendBroadcastAsUser(intent, admin.getUserHandle()); 2322 } 2323 } 2324 2325 /** 2326 * Send an update to all admins of a user that enforce a specified policy. 2327 */ 2328 void sendAdminCommandLocked(String action, int reqPolicy, int userHandle, Bundle adminExtras) { 2329 final DevicePolicyData policy = getUserData(userHandle); 2330 final int count = policy.mAdminList.size(); 2331 for (int i = 0; i < count; i++) { 2332 final ActiveAdmin admin = policy.mAdminList.get(i); 2333 if (admin.info.usesPolicy(reqPolicy)) { 2334 sendAdminCommandLocked(admin, action, adminExtras, null); 2335 } 2336 } 2337 } 2338 2339 /** 2340 * Send an update intent to all admins of a user and its profiles. Only send to admins that 2341 * enforce a specified policy. 2342 */ 2343 private void sendAdminCommandToSelfAndProfilesLocked(String action, int reqPolicy, 2344 int userHandle, Bundle adminExtras) { 2345 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 2346 for (int profileId : profileIds) { 2347 sendAdminCommandLocked(action, reqPolicy, profileId, adminExtras); 2348 } 2349 } 2350 2351 /** 2352 * Sends a broadcast to each profile that share the password unlock with the given user id. 2353 */ 2354 private void sendAdminCommandForLockscreenPoliciesLocked( 2355 String action, int reqPolicy, int userHandle) { 2356 final Bundle extras = new Bundle(); 2357 extras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 2358 if (isSeparateProfileChallengeEnabled(userHandle)) { 2359 sendAdminCommandLocked(action, reqPolicy, userHandle, extras); 2360 } else { 2361 sendAdminCommandToSelfAndProfilesLocked(action, reqPolicy, userHandle, extras); 2362 } 2363 } 2364 2365 void removeActiveAdminLocked(final ComponentName adminReceiver, final int userHandle) { 2366 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 2367 DevicePolicyData policy = getUserData(userHandle); 2368 if (admin != null && !policy.mRemovingAdmins.contains(adminReceiver)) { 2369 policy.mRemovingAdmins.add(adminReceiver); 2370 sendAdminCommandLocked(admin, 2371 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED, 2372 new BroadcastReceiver() { 2373 @Override 2374 public void onReceive(Context context, Intent intent) { 2375 removeAdminArtifacts(adminReceiver, userHandle); 2376 removePackageIfRequired(adminReceiver.getPackageName(), userHandle); 2377 } 2378 }); 2379 } 2380 } 2381 2382 2383 public DeviceAdminInfo findAdmin(ComponentName adminName, int userHandle, 2384 boolean throwForMissiongPermission) { 2385 if (!mHasFeature) { 2386 return null; 2387 } 2388 enforceFullCrossUsersPermission(userHandle); 2389 ActivityInfo ai = null; 2390 try { 2391 ai = mIPackageManager.getReceiverInfo(adminName, 2392 PackageManager.GET_META_DATA | 2393 PackageManager.MATCH_DISABLED_UNTIL_USED_COMPONENTS | 2394 PackageManager.MATCH_DIRECT_BOOT_AWARE | 2395 PackageManager.MATCH_DIRECT_BOOT_UNAWARE, userHandle); 2396 } catch (RemoteException e) { 2397 // shouldn't happen. 2398 } 2399 if (ai == null) { 2400 throw new IllegalArgumentException("Unknown admin: " + adminName); 2401 } 2402 2403 if (!permission.BIND_DEVICE_ADMIN.equals(ai.permission)) { 2404 final String message = "DeviceAdminReceiver " + adminName + " must be protected with " 2405 + permission.BIND_DEVICE_ADMIN; 2406 Slog.w(LOG_TAG, message); 2407 if (throwForMissiongPermission && 2408 ai.applicationInfo.targetSdkVersion > Build.VERSION_CODES.M) { 2409 throw new IllegalArgumentException(message); 2410 } 2411 } 2412 2413 try { 2414 return new DeviceAdminInfo(mContext, ai); 2415 } catch (XmlPullParserException | IOException e) { 2416 Slog.w(LOG_TAG, "Bad device admin requested for user=" + userHandle + ": " + adminName, 2417 e); 2418 return null; 2419 } 2420 } 2421 2422 private JournaledFile makeJournaledFile(int userHandle) { 2423 final String base = userHandle == UserHandle.USER_SYSTEM 2424 ? mInjector.getDevicePolicyFilePathForSystemUser() + DEVICE_POLICIES_XML 2425 : new File(mInjector.environmentGetUserSystemDirectory(userHandle), 2426 DEVICE_POLICIES_XML).getAbsolutePath(); 2427 if (VERBOSE_LOG) { 2428 Log.v(LOG_TAG, "Opening " + base); 2429 } 2430 return new JournaledFile(new File(base), new File(base + ".tmp")); 2431 } 2432 2433 private void saveSettingsLocked(int userHandle) { 2434 DevicePolicyData policy = getUserData(userHandle); 2435 JournaledFile journal = makeJournaledFile(userHandle); 2436 FileOutputStream stream = null; 2437 try { 2438 stream = new FileOutputStream(journal.chooseForWrite(), false); 2439 XmlSerializer out = new FastXmlSerializer(); 2440 out.setOutput(stream, StandardCharsets.UTF_8.name()); 2441 out.startDocument(null, true); 2442 2443 out.startTag(null, "policies"); 2444 if (policy.mRestrictionsProvider != null) { 2445 out.attribute(null, ATTR_PERMISSION_PROVIDER, 2446 policy.mRestrictionsProvider.flattenToString()); 2447 } 2448 if (policy.mUserSetupComplete) { 2449 out.attribute(null, ATTR_SETUP_COMPLETE, 2450 Boolean.toString(true)); 2451 } 2452 if (policy.mPaired) { 2453 out.attribute(null, ATTR_DEVICE_PAIRED, 2454 Boolean.toString(true)); 2455 } 2456 if (policy.mDeviceProvisioningConfigApplied) { 2457 out.attribute(null, ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED, 2458 Boolean.toString(true)); 2459 } 2460 if (policy.mUserProvisioningState != DevicePolicyManager.STATE_USER_UNMANAGED) { 2461 out.attribute(null, ATTR_PROVISIONING_STATE, 2462 Integer.toString(policy.mUserProvisioningState)); 2463 } 2464 if (policy.mPermissionPolicy != DevicePolicyManager.PERMISSION_POLICY_PROMPT) { 2465 out.attribute(null, ATTR_PERMISSION_POLICY, 2466 Integer.toString(policy.mPermissionPolicy)); 2467 } 2468 2469 // Serialize delegations. 2470 for (int i = 0; i < policy.mDelegationMap.size(); ++i) { 2471 final String delegatePackage = policy.mDelegationMap.keyAt(i); 2472 final List<String> scopes = policy.mDelegationMap.valueAt(i); 2473 2474 // Every "delegation" tag serializes the information of one delegate-scope pair. 2475 for (String scope : scopes) { 2476 out.startTag(null, "delegation"); 2477 out.attribute(null, "delegatePackage", delegatePackage); 2478 out.attribute(null, "scope", scope); 2479 out.endTag(null, "delegation"); 2480 } 2481 } 2482 2483 final int N = policy.mAdminList.size(); 2484 for (int i=0; i<N; i++) { 2485 ActiveAdmin ap = policy.mAdminList.get(i); 2486 if (ap != null) { 2487 out.startTag(null, "admin"); 2488 out.attribute(null, "name", ap.info.getComponent().flattenToString()); 2489 ap.writeToXml(out); 2490 out.endTag(null, "admin"); 2491 } 2492 } 2493 2494 if (policy.mPasswordOwner >= 0) { 2495 out.startTag(null, "password-owner"); 2496 out.attribute(null, "value", Integer.toString(policy.mPasswordOwner)); 2497 out.endTag(null, "password-owner"); 2498 } 2499 2500 if (policy.mFailedPasswordAttempts != 0) { 2501 out.startTag(null, "failed-password-attempts"); 2502 out.attribute(null, "value", Integer.toString(policy.mFailedPasswordAttempts)); 2503 out.endTag(null, "failed-password-attempts"); 2504 } 2505 2506 // Don't save metrics for FBE devices 2507 final PasswordMetrics metrics = policy.mActivePasswordMetrics; 2508 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled() && !metrics.isDefault()) { 2509 out.startTag(null, "active-password"); 2510 out.attribute(null, "quality", Integer.toString(metrics.quality)); 2511 out.attribute(null, "length", Integer.toString(metrics.length)); 2512 out.attribute(null, "uppercase", Integer.toString(metrics.upperCase)); 2513 out.attribute(null, "lowercase", Integer.toString(metrics.lowerCase)); 2514 out.attribute(null, "letters", Integer.toString(metrics.letters)); 2515 out.attribute(null, "numeric", Integer.toString(metrics.numeric)); 2516 out.attribute(null, "symbols", Integer.toString(metrics.symbols)); 2517 out.attribute(null, "nonletter", Integer.toString(metrics.nonLetter)); 2518 out.endTag(null, "active-password"); 2519 } 2520 2521 for (int i = 0; i < policy.mAcceptedCaCertificates.size(); i++) { 2522 out.startTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2523 out.attribute(null, ATTR_NAME, policy.mAcceptedCaCertificates.valueAt(i)); 2524 out.endTag(null, TAG_ACCEPTED_CA_CERTIFICATES); 2525 } 2526 2527 for (int i=0; i<policy.mLockTaskPackages.size(); i++) { 2528 String component = policy.mLockTaskPackages.get(i); 2529 out.startTag(null, TAG_LOCK_TASK_COMPONENTS); 2530 out.attribute(null, "name", component); 2531 out.endTag(null, TAG_LOCK_TASK_COMPONENTS); 2532 } 2533 2534 if (policy.mStatusBarDisabled) { 2535 out.startTag(null, TAG_STATUS_BAR); 2536 out.attribute(null, ATTR_DISABLED, Boolean.toString(policy.mStatusBarDisabled)); 2537 out.endTag(null, TAG_STATUS_BAR); 2538 } 2539 2540 if (policy.doNotAskCredentialsOnBoot) { 2541 out.startTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2542 out.endTag(null, DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML); 2543 } 2544 2545 for (String id : policy.mAffiliationIds) { 2546 out.startTag(null, TAG_AFFILIATION_ID); 2547 out.attribute(null, ATTR_ID, id); 2548 out.endTag(null, TAG_AFFILIATION_ID); 2549 } 2550 2551 if (policy.mLastSecurityLogRetrievalTime >= 0) { 2552 out.startTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2553 out.attribute(null, ATTR_VALUE, 2554 Long.toString(policy.mLastSecurityLogRetrievalTime)); 2555 out.endTag(null, TAG_LAST_SECURITY_LOG_RETRIEVAL); 2556 } 2557 2558 if (policy.mLastBugReportRequestTime >= 0) { 2559 out.startTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2560 out.attribute(null, ATTR_VALUE, 2561 Long.toString(policy.mLastBugReportRequestTime)); 2562 out.endTag(null, TAG_LAST_BUG_REPORT_REQUEST); 2563 } 2564 2565 if (policy.mLastNetworkLogsRetrievalTime >= 0) { 2566 out.startTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2567 out.attribute(null, ATTR_VALUE, 2568 Long.toString(policy.mLastNetworkLogsRetrievalTime)); 2569 out.endTag(null, TAG_LAST_NETWORK_LOG_RETRIEVAL); 2570 } 2571 2572 if (policy.mAdminBroadcastPending) { 2573 out.startTag(null, TAG_ADMIN_BROADCAST_PENDING); 2574 out.attribute(null, ATTR_VALUE, 2575 Boolean.toString(policy.mAdminBroadcastPending)); 2576 out.endTag(null, TAG_ADMIN_BROADCAST_PENDING); 2577 } 2578 2579 if (policy.mInitBundle != null) { 2580 out.startTag(null, TAG_INITIALIZATION_BUNDLE); 2581 policy.mInitBundle.saveToXml(out); 2582 out.endTag(null, TAG_INITIALIZATION_BUNDLE); 2583 } 2584 2585 if (policy.mPasswordTokenHandle != 0) { 2586 out.startTag(null, TAG_PASSWORD_TOKEN_HANDLE); 2587 out.attribute(null, ATTR_VALUE, 2588 Long.toString(policy.mPasswordTokenHandle)); 2589 out.endTag(null, TAG_PASSWORD_TOKEN_HANDLE); 2590 } 2591 2592 if (policy.mCurrentInputMethodSet) { 2593 out.startTag(null, TAG_CURRENT_INPUT_METHOD_SET); 2594 out.endTag(null, TAG_CURRENT_INPUT_METHOD_SET); 2595 } 2596 2597 for (final String cert : policy.mOwnerInstalledCaCerts) { 2598 out.startTag(null, TAG_OWNER_INSTALLED_CA_CERT); 2599 out.attribute(null, ATTR_ALIAS, cert); 2600 out.endTag(null, TAG_OWNER_INSTALLED_CA_CERT); 2601 } 2602 2603 out.endTag(null, "policies"); 2604 2605 out.endDocument(); 2606 stream.flush(); 2607 FileUtils.sync(stream); 2608 stream.close(); 2609 journal.commit(); 2610 sendChangedNotification(userHandle); 2611 } catch (XmlPullParserException | IOException e) { 2612 Slog.w(LOG_TAG, "failed writing file", e); 2613 try { 2614 if (stream != null) { 2615 stream.close(); 2616 } 2617 } catch (IOException ex) { 2618 // Ignore 2619 } 2620 journal.rollback(); 2621 } 2622 } 2623 2624 private void sendChangedNotification(int userHandle) { 2625 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 2626 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 2627 long ident = mInjector.binderClearCallingIdentity(); 2628 try { 2629 mContext.sendBroadcastAsUser(intent, new UserHandle(userHandle)); 2630 } finally { 2631 mInjector.binderRestoreCallingIdentity(ident); 2632 } 2633 } 2634 2635 private void loadSettingsLocked(DevicePolicyData policy, int userHandle) { 2636 JournaledFile journal = makeJournaledFile(userHandle); 2637 FileInputStream stream = null; 2638 File file = journal.chooseForRead(); 2639 boolean needsRewrite = false; 2640 try { 2641 stream = new FileInputStream(file); 2642 XmlPullParser parser = Xml.newPullParser(); 2643 parser.setInput(stream, StandardCharsets.UTF_8.name()); 2644 2645 int type; 2646 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2647 && type != XmlPullParser.START_TAG) { 2648 } 2649 String tag = parser.getName(); 2650 if (!"policies".equals(tag)) { 2651 throw new XmlPullParserException( 2652 "Settings do not start with policies tag: found " + tag); 2653 } 2654 2655 // Extract the permission provider component name if available 2656 String permissionProvider = parser.getAttributeValue(null, ATTR_PERMISSION_PROVIDER); 2657 if (permissionProvider != null) { 2658 policy.mRestrictionsProvider = ComponentName.unflattenFromString(permissionProvider); 2659 } 2660 String userSetupComplete = parser.getAttributeValue(null, ATTR_SETUP_COMPLETE); 2661 if (userSetupComplete != null && Boolean.toString(true).equals(userSetupComplete)) { 2662 policy.mUserSetupComplete = true; 2663 } 2664 String paired = parser.getAttributeValue(null, ATTR_DEVICE_PAIRED); 2665 if (paired != null && Boolean.toString(true).equals(paired)) { 2666 policy.mPaired = true; 2667 } 2668 String deviceProvisioningConfigApplied = parser.getAttributeValue(null, 2669 ATTR_DEVICE_PROVISIONING_CONFIG_APPLIED); 2670 if (deviceProvisioningConfigApplied != null 2671 && Boolean.toString(true).equals(deviceProvisioningConfigApplied)) { 2672 policy.mDeviceProvisioningConfigApplied = true; 2673 } 2674 String provisioningState = parser.getAttributeValue(null, ATTR_PROVISIONING_STATE); 2675 if (!TextUtils.isEmpty(provisioningState)) { 2676 policy.mUserProvisioningState = Integer.parseInt(provisioningState); 2677 } 2678 String permissionPolicy = parser.getAttributeValue(null, ATTR_PERMISSION_POLICY); 2679 if (!TextUtils.isEmpty(permissionPolicy)) { 2680 policy.mPermissionPolicy = Integer.parseInt(permissionPolicy); 2681 } 2682 // Check for delegation compatibility with pre-O. 2683 // TODO(edmanp) remove in P. 2684 { 2685 final String certDelegate = parser.getAttributeValue(null, 2686 ATTR_DELEGATED_CERT_INSTALLER); 2687 if (certDelegate != null) { 2688 List<String> scopes = policy.mDelegationMap.get(certDelegate); 2689 if (scopes == null) { 2690 scopes = new ArrayList<>(); 2691 policy.mDelegationMap.put(certDelegate, scopes); 2692 } 2693 if (!scopes.contains(DELEGATION_CERT_INSTALL)) { 2694 scopes.add(DELEGATION_CERT_INSTALL); 2695 needsRewrite = true; 2696 } 2697 } 2698 final String appRestrictionsDelegate = parser.getAttributeValue(null, 2699 ATTR_APPLICATION_RESTRICTIONS_MANAGER); 2700 if (appRestrictionsDelegate != null) { 2701 List<String> scopes = policy.mDelegationMap.get(appRestrictionsDelegate); 2702 if (scopes == null) { 2703 scopes = new ArrayList<>(); 2704 policy.mDelegationMap.put(appRestrictionsDelegate, scopes); 2705 } 2706 if (!scopes.contains(DELEGATION_APP_RESTRICTIONS)) { 2707 scopes.add(DELEGATION_APP_RESTRICTIONS); 2708 needsRewrite = true; 2709 } 2710 } 2711 } 2712 2713 type = parser.next(); 2714 int outerDepth = parser.getDepth(); 2715 policy.mLockTaskPackages.clear(); 2716 policy.mAdminList.clear(); 2717 policy.mAdminMap.clear(); 2718 policy.mAffiliationIds.clear(); 2719 policy.mOwnerInstalledCaCerts.clear(); 2720 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2721 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2722 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2723 continue; 2724 } 2725 tag = parser.getName(); 2726 if ("admin".equals(tag)) { 2727 String name = parser.getAttributeValue(null, "name"); 2728 try { 2729 DeviceAdminInfo dai = findAdmin( 2730 ComponentName.unflattenFromString(name), userHandle, 2731 /* throwForMissionPermission= */ false); 2732 if (VERBOSE_LOG 2733 && (UserHandle.getUserId(dai.getActivityInfo().applicationInfo.uid) 2734 != userHandle)) { 2735 Slog.w(LOG_TAG, "findAdmin returned an incorrect uid " 2736 + dai.getActivityInfo().applicationInfo.uid + " for user " 2737 + userHandle); 2738 } 2739 if (dai != null) { 2740 ActiveAdmin ap = new ActiveAdmin(dai, /* parent */ false); 2741 ap.readFromXml(parser); 2742 policy.mAdminMap.put(ap.info.getComponent(), ap); 2743 } 2744 } catch (RuntimeException e) { 2745 Slog.w(LOG_TAG, "Failed loading admin " + name, e); 2746 } 2747 } else if ("delegation".equals(tag)) { 2748 // Parse delegation info. 2749 final String delegatePackage = parser.getAttributeValue(null, 2750 "delegatePackage"); 2751 final String scope = parser.getAttributeValue(null, "scope"); 2752 2753 // Get a reference to the scopes list for the delegatePackage. 2754 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 2755 // Or make a new list if none was found. 2756 if (scopes == null) { 2757 scopes = new ArrayList<>(); 2758 policy.mDelegationMap.put(delegatePackage, scopes); 2759 } 2760 // Add the new scope to the list of delegatePackage if it's not already there. 2761 if (!scopes.contains(scope)) { 2762 scopes.add(scope); 2763 } 2764 } else if ("failed-password-attempts".equals(tag)) { 2765 policy.mFailedPasswordAttempts = Integer.parseInt( 2766 parser.getAttributeValue(null, "value")); 2767 } else if ("password-owner".equals(tag)) { 2768 policy.mPasswordOwner = Integer.parseInt( 2769 parser.getAttributeValue(null, "value")); 2770 } else if (TAG_ACCEPTED_CA_CERTIFICATES.equals(tag)) { 2771 policy.mAcceptedCaCertificates.add(parser.getAttributeValue(null, ATTR_NAME)); 2772 } else if (TAG_LOCK_TASK_COMPONENTS.equals(tag)) { 2773 policy.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 2774 } else if (TAG_STATUS_BAR.equals(tag)) { 2775 policy.mStatusBarDisabled = Boolean.parseBoolean( 2776 parser.getAttributeValue(null, ATTR_DISABLED)); 2777 } else if (DO_NOT_ASK_CREDENTIALS_ON_BOOT_XML.equals(tag)) { 2778 policy.doNotAskCredentialsOnBoot = true; 2779 } else if (TAG_AFFILIATION_ID.equals(tag)) { 2780 policy.mAffiliationIds.add(parser.getAttributeValue(null, ATTR_ID)); 2781 } else if (TAG_LAST_SECURITY_LOG_RETRIEVAL.equals(tag)) { 2782 policy.mLastSecurityLogRetrievalTime = Long.parseLong( 2783 parser.getAttributeValue(null, ATTR_VALUE)); 2784 } else if (TAG_LAST_BUG_REPORT_REQUEST.equals(tag)) { 2785 policy.mLastBugReportRequestTime = Long.parseLong( 2786 parser.getAttributeValue(null, ATTR_VALUE)); 2787 } else if (TAG_LAST_NETWORK_LOG_RETRIEVAL.equals(tag)) { 2788 policy.mLastNetworkLogsRetrievalTime = Long.parseLong( 2789 parser.getAttributeValue(null, ATTR_VALUE)); 2790 } else if (TAG_ADMIN_BROADCAST_PENDING.equals(tag)) { 2791 String pending = parser.getAttributeValue(null, ATTR_VALUE); 2792 policy.mAdminBroadcastPending = Boolean.toString(true).equals(pending); 2793 } else if (TAG_INITIALIZATION_BUNDLE.equals(tag)) { 2794 policy.mInitBundle = PersistableBundle.restoreFromXml(parser); 2795 } else if ("active-password".equals(tag)) { 2796 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 2797 // Remove this from FBE devices 2798 needsRewrite = true; 2799 } else { 2800 final PasswordMetrics m = policy.mActivePasswordMetrics; 2801 m.quality = Integer.parseInt(parser.getAttributeValue(null, "quality")); 2802 m.length = Integer.parseInt(parser.getAttributeValue(null, "length")); 2803 m.upperCase = Integer.parseInt(parser.getAttributeValue(null, "uppercase")); 2804 m.lowerCase = Integer.parseInt(parser.getAttributeValue(null, "lowercase")); 2805 m.letters = Integer.parseInt(parser.getAttributeValue(null, "letters")); 2806 m.numeric = Integer.parseInt(parser.getAttributeValue(null, "numeric")); 2807 m.symbols = Integer.parseInt(parser.getAttributeValue(null, "symbols")); 2808 m.nonLetter = Integer.parseInt(parser.getAttributeValue(null, "nonletter")); 2809 } 2810 } else if (TAG_PASSWORD_TOKEN_HANDLE.equals(tag)) { 2811 policy.mPasswordTokenHandle = Long.parseLong( 2812 parser.getAttributeValue(null, ATTR_VALUE)); 2813 } else if (TAG_CURRENT_INPUT_METHOD_SET.equals(tag)) { 2814 policy.mCurrentInputMethodSet = true; 2815 } else if (TAG_OWNER_INSTALLED_CA_CERT.equals(tag)) { 2816 policy.mOwnerInstalledCaCerts.add(parser.getAttributeValue(null, ATTR_ALIAS)); 2817 } else { 2818 Slog.w(LOG_TAG, "Unknown tag: " + tag); 2819 XmlUtils.skipCurrentTag(parser); 2820 } 2821 } 2822 } catch (FileNotFoundException e) { 2823 // Don't be noisy, this is normal if we haven't defined any policies. 2824 } catch (NullPointerException | NumberFormatException | XmlPullParserException | IOException 2825 | IndexOutOfBoundsException e) { 2826 Slog.w(LOG_TAG, "failed parsing " + file, e); 2827 } 2828 try { 2829 if (stream != null) { 2830 stream.close(); 2831 } 2832 } catch (IOException e) { 2833 // Ignore 2834 } 2835 2836 // Generate a list of admins from the admin map 2837 policy.mAdminList.addAll(policy.mAdminMap.values()); 2838 2839 // Might need to upgrade the file by rewriting it 2840 if (needsRewrite) { 2841 saveSettingsLocked(userHandle); 2842 } 2843 2844 validatePasswordOwnerLocked(policy); 2845 updateMaximumTimeToLockLocked(userHandle); 2846 updateLockTaskPackagesLocked(policy.mLockTaskPackages, userHandle); 2847 if (policy.mStatusBarDisabled) { 2848 setStatusBarDisabledInternal(policy.mStatusBarDisabled, userHandle); 2849 } 2850 } 2851 2852 private void updateLockTaskPackagesLocked(List<String> packages, int userId) { 2853 long ident = mInjector.binderClearCallingIdentity(); 2854 try { 2855 mInjector.getIActivityManager() 2856 .updateLockTaskPackages(userId, packages.toArray(new String[packages.size()])); 2857 } catch (RemoteException e) { 2858 // Not gonna happen. 2859 } finally { 2860 mInjector.binderRestoreCallingIdentity(ident); 2861 } 2862 } 2863 2864 private void updateDeviceOwnerLocked() { 2865 long ident = mInjector.binderClearCallingIdentity(); 2866 try { 2867 // TODO This is to prevent DO from getting "clear data"ed, but it should also check the 2868 // user id and also protect all other DAs too. 2869 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 2870 if (deviceOwnerComponent != null) { 2871 mInjector.getIActivityManager() 2872 .updateDeviceOwner(deviceOwnerComponent.getPackageName()); 2873 } 2874 } catch (RemoteException e) { 2875 // Not gonna happen. 2876 } finally { 2877 mInjector.binderRestoreCallingIdentity(ident); 2878 } 2879 } 2880 2881 static void validateQualityConstant(int quality) { 2882 switch (quality) { 2883 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED: 2884 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 2885 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 2886 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 2887 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: 2888 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 2889 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 2890 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 2891 case DevicePolicyManager.PASSWORD_QUALITY_MANAGED: 2892 return; 2893 } 2894 throw new IllegalArgumentException("Invalid quality constant: 0x" 2895 + Integer.toHexString(quality)); 2896 } 2897 2898 void validatePasswordOwnerLocked(DevicePolicyData policy) { 2899 if (policy.mPasswordOwner >= 0) { 2900 boolean haveOwner = false; 2901 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 2902 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 2903 haveOwner = true; 2904 break; 2905 } 2906 } 2907 if (!haveOwner) { 2908 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 2909 + " no longer active; disabling"); 2910 policy.mPasswordOwner = -1; 2911 } 2912 } 2913 } 2914 2915 @VisibleForTesting 2916 void systemReady(int phase) { 2917 if (!mHasFeature) { 2918 return; 2919 } 2920 switch (phase) { 2921 case SystemService.PHASE_LOCK_SETTINGS_READY: 2922 onLockSettingsReady(); 2923 break; 2924 case SystemService.PHASE_BOOT_COMPLETED: 2925 ensureDeviceOwnerUserStarted(); // TODO Consider better place to do this. 2926 break; 2927 } 2928 } 2929 2930 private void ensureUnknownSourcesRestrictionForProfileOwners() { 2931 synchronized (this) { 2932 for (int userId : mOwners.getProfileOwnerKeys()) { 2933 if (!mUserManager.isManagedProfile(userId) || 2934 mInjector.settingsSecureGetIntForUser( 2935 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId) == 0) { 2936 continue; 2937 } 2938 setUserRestrictionOnBehalfOfProfileOwnerLocked( 2939 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId); 2940 mInjector.settingsSecurePutIntForUser( 2941 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userId); 2942 } 2943 } 2944 } 2945 2946 private void setUserRestrictionOnBehalfOfProfileOwnerLocked(String userRestrictionKey, 2947 int userId) { 2948 if (UserRestrictionsUtils.isValidRestriction(userRestrictionKey) && 2949 UserRestrictionsUtils.canProfileOwnerChange(userRestrictionKey, userId)) { 2950 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 2951 if (profileOwner == null) { 2952 return; 2953 } 2954 Bundle restrictions = profileOwner.ensureUserRestrictions(); 2955 restrictions.putBoolean(userRestrictionKey, true); 2956 saveUserRestrictionsLocked(userId); 2957 } 2958 } 2959 2960 private void onLockSettingsReady() { 2961 getUserData(UserHandle.USER_SYSTEM); 2962 loadOwners(); 2963 cleanUpOldUsers(); 2964 ensureUnknownSourcesRestrictionForProfileOwners(); 2965 handleStartUser(UserHandle.USER_SYSTEM); 2966 2967 // Register an observer for watching for user setup complete and settings changes. 2968 mSetupContentObserver.register(); 2969 // Initialize the user setup state, to handle the upgrade case. 2970 updateUserSetupCompleteAndPaired(); 2971 2972 List<String> packageList; 2973 synchronized (this) { 2974 packageList = getKeepUninstalledPackagesLocked(); 2975 } 2976 if (packageList != null) { 2977 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 2978 } 2979 2980 synchronized (this) { 2981 // push the force-ephemeral-users policy to the user manager. 2982 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 2983 if (deviceOwner != null) { 2984 mUserManagerInternal.setForceEphemeralUsers(deviceOwner.forceEphemeralUsers); 2985 } 2986 } 2987 } 2988 2989 private void ensureDeviceOwnerUserStarted() { 2990 final int userId; 2991 synchronized (this) { 2992 if (!mOwners.hasDeviceOwner()) { 2993 return; 2994 } 2995 userId = mOwners.getDeviceOwnerUserId(); 2996 } 2997 if (VERBOSE_LOG) { 2998 Log.v(LOG_TAG, "Starting non-system DO user: " + userId); 2999 } 3000 if (userId != UserHandle.USER_SYSTEM) { 3001 try { 3002 mInjector.getIActivityManager().startUserInBackground(userId); 3003 3004 // STOPSHIP Prevent the DO user from being killed. 3005 3006 } catch (RemoteException e) { 3007 Slog.w(LOG_TAG, "Exception starting user", e); 3008 } 3009 } 3010 } 3011 3012 void handleStartUser(int userId) { 3013 updateScreenCaptureDisabledInWindowManager(userId, 3014 getScreenCaptureDisabled(null, userId)); 3015 pushUserRestrictions(userId); 3016 3017 startOwnerService(userId, "start-user"); 3018 } 3019 3020 void handleUnlockUser(int userId) { 3021 startOwnerService(userId, "unlock-user"); 3022 } 3023 3024 void handleStopUser(int userId) { 3025 stopOwnerService(userId, "stop-user"); 3026 } 3027 3028 private void startOwnerService(int userId, String actionForLog) { 3029 final ComponentName owner = getOwnerComponent(userId); 3030 if (owner != null) { 3031 mDeviceAdminServiceController.startServiceForOwner( 3032 owner.getPackageName(), userId, actionForLog); 3033 } 3034 } 3035 3036 private void stopOwnerService(int userId, String actionForLog) { 3037 mDeviceAdminServiceController.stopServiceForOwner(userId, actionForLog); 3038 } 3039 3040 private void cleanUpOldUsers() { 3041 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 3042 // before reboot 3043 Set<Integer> usersWithProfileOwners; 3044 Set<Integer> usersWithData; 3045 synchronized(this) { 3046 usersWithProfileOwners = mOwners.getProfileOwnerKeys(); 3047 usersWithData = new ArraySet<>(); 3048 for (int i = 0; i < mUserData.size(); i++) { 3049 usersWithData.add(mUserData.keyAt(i)); 3050 } 3051 } 3052 List<UserInfo> allUsers = mUserManager.getUsers(); 3053 3054 Set<Integer> deletedUsers = new ArraySet<>(); 3055 deletedUsers.addAll(usersWithProfileOwners); 3056 deletedUsers.addAll(usersWithData); 3057 for (UserInfo userInfo : allUsers) { 3058 deletedUsers.remove(userInfo.id); 3059 } 3060 for (Integer userId : deletedUsers) { 3061 removeUserData(userId); 3062 } 3063 } 3064 3065 private void handlePasswordExpirationNotification(int userHandle) { 3066 final Bundle adminExtras = new Bundle(); 3067 adminExtras.putParcelable(Intent.EXTRA_USER, UserHandle.of(userHandle)); 3068 3069 synchronized (this) { 3070 final long now = System.currentTimeMillis(); 3071 3072 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 3073 userHandle, /* parent */ false); 3074 final int N = admins.size(); 3075 for (int i = 0; i < N; i++) { 3076 ActiveAdmin admin = admins.get(i); 3077 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 3078 && admin.passwordExpirationTimeout > 0L 3079 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 3080 && admin.passwordExpirationDate > 0L) { 3081 sendAdminCommandLocked(admin, 3082 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING, adminExtras, null); 3083 } 3084 } 3085 setExpirationAlarmCheckLocked(mContext, userHandle, /* parent */ false); 3086 } 3087 } 3088 3089 /** 3090 * Clean up internal state when the set of installed trusted CA certificates changes. 3091 * 3092 * @param userHandle user to check for. This must be a real user and not, for example, 3093 * {@link UserHandle#ALL}. 3094 * @param installedCertificates the full set of certificate authorities currently installed for 3095 * {@param userHandle}. After calling this function, {@code mAcceptedCaCertificates} will 3096 * correspond to some subset of this. 3097 */ 3098 protected void onInstalledCertificatesChanged(final UserHandle userHandle, 3099 final @NonNull Collection<String> installedCertificates) { 3100 if (!mHasFeature) { 3101 return; 3102 } 3103 enforceManageUsers(); 3104 3105 synchronized (this) { 3106 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3107 3108 boolean changed = false; 3109 changed |= policy.mAcceptedCaCertificates.retainAll(installedCertificates); 3110 changed |= policy.mOwnerInstalledCaCerts.retainAll(installedCertificates); 3111 if (changed) { 3112 saveSettingsLocked(userHandle.getIdentifier()); 3113 } 3114 } 3115 } 3116 3117 /** 3118 * Internal method used by {@link CertificateMonitor}. 3119 */ 3120 protected Set<String> getAcceptedCaCertificates(final UserHandle userHandle) { 3121 if (!mHasFeature) { 3122 return Collections.<String> emptySet(); 3123 } 3124 synchronized (this) { 3125 final DevicePolicyData policy = getUserData(userHandle.getIdentifier()); 3126 return policy.mAcceptedCaCertificates; 3127 } 3128 } 3129 3130 /** 3131 * @param adminReceiver The admin to add 3132 * @param refreshing true = update an active admin, no error 3133 */ 3134 @Override 3135 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 3136 if (!mHasFeature) { 3137 return; 3138 } 3139 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 3140 } 3141 3142 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 3143 Bundle onEnableData) { 3144 mContext.enforceCallingOrSelfPermission( 3145 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3146 enforceFullCrossUsersPermission(userHandle); 3147 3148 DevicePolicyData policy = getUserData(userHandle); 3149 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle, 3150 /* throwForMissionPermission= */ true); 3151 if (info == null) { 3152 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 3153 } 3154 if (!info.getActivityInfo().applicationInfo.isInternal()) { 3155 throw new IllegalArgumentException("Only apps in internal storage can be active admin: " 3156 + adminReceiver); 3157 } 3158 if (info.getActivityInfo().applicationInfo.isInstantApp()) { 3159 throw new IllegalArgumentException("Instant apps cannot be device admins: " 3160 + adminReceiver); 3161 } 3162 synchronized (this) { 3163 long ident = mInjector.binderClearCallingIdentity(); 3164 try { 3165 final ActiveAdmin existingAdmin 3166 = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3167 if (!refreshing && existingAdmin != null) { 3168 throw new IllegalArgumentException("Admin is already added"); 3169 } 3170 if (policy.mRemovingAdmins.contains(adminReceiver)) { 3171 throw new IllegalArgumentException( 3172 "Trying to set an admin which is being removed"); 3173 } 3174 ActiveAdmin newAdmin = new ActiveAdmin(info, /* parent */ false); 3175 newAdmin.testOnlyAdmin = 3176 (existingAdmin != null) ? existingAdmin.testOnlyAdmin 3177 : isPackageTestOnly(adminReceiver.getPackageName(), userHandle); 3178 policy.mAdminMap.put(adminReceiver, newAdmin); 3179 int replaceIndex = -1; 3180 final int N = policy.mAdminList.size(); 3181 for (int i=0; i < N; i++) { 3182 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 3183 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 3184 replaceIndex = i; 3185 break; 3186 } 3187 } 3188 if (replaceIndex == -1) { 3189 policy.mAdminList.add(newAdmin); 3190 enableIfNecessary(info.getPackageName(), userHandle); 3191 } else { 3192 policy.mAdminList.set(replaceIndex, newAdmin); 3193 } 3194 saveSettingsLocked(userHandle); 3195 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 3196 onEnableData, null); 3197 } finally { 3198 mInjector.binderRestoreCallingIdentity(ident); 3199 } 3200 } 3201 } 3202 3203 @Override 3204 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 3205 if (!mHasFeature) { 3206 return false; 3207 } 3208 enforceFullCrossUsersPermission(userHandle); 3209 synchronized (this) { 3210 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 3211 } 3212 } 3213 3214 @Override 3215 public boolean isRemovingAdmin(ComponentName adminReceiver, int userHandle) { 3216 if (!mHasFeature) { 3217 return false; 3218 } 3219 enforceFullCrossUsersPermission(userHandle); 3220 synchronized (this) { 3221 DevicePolicyData policyData = getUserData(userHandle); 3222 return policyData.mRemovingAdmins.contains(adminReceiver); 3223 } 3224 } 3225 3226 @Override 3227 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 3228 if (!mHasFeature) { 3229 return false; 3230 } 3231 enforceFullCrossUsersPermission(userHandle); 3232 synchronized (this) { 3233 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3234 if (administrator == null) { 3235 throw new SecurityException("No active admin " + adminReceiver); 3236 } 3237 return administrator.info.usesPolicy(policyId); 3238 } 3239 } 3240 3241 @Override 3242 @SuppressWarnings("unchecked") 3243 public List<ComponentName> getActiveAdmins(int userHandle) { 3244 if (!mHasFeature) { 3245 return Collections.EMPTY_LIST; 3246 } 3247 3248 enforceFullCrossUsersPermission(userHandle); 3249 synchronized (this) { 3250 DevicePolicyData policy = getUserData(userHandle); 3251 final int N = policy.mAdminList.size(); 3252 if (N <= 0) { 3253 return null; 3254 } 3255 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 3256 for (int i=0; i<N; i++) { 3257 res.add(policy.mAdminList.get(i).info.getComponent()); 3258 } 3259 return res; 3260 } 3261 } 3262 3263 @Override 3264 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 3265 if (!mHasFeature) { 3266 return false; 3267 } 3268 enforceFullCrossUsersPermission(userHandle); 3269 synchronized (this) { 3270 DevicePolicyData policy = getUserData(userHandle); 3271 final int N = policy.mAdminList.size(); 3272 for (int i=0; i<N; i++) { 3273 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 3274 return true; 3275 } 3276 } 3277 return false; 3278 } 3279 } 3280 3281 public void forceRemoveActiveAdmin(ComponentName adminReceiver, int userHandle) { 3282 if (!mHasFeature) { 3283 return; 3284 } 3285 Preconditions.checkNotNull(adminReceiver, "ComponentName is null"); 3286 enforceShell("forceRemoveActiveAdmin"); 3287 long ident = mInjector.binderClearCallingIdentity(); 3288 try { 3289 synchronized (this) { 3290 if (!isAdminTestOnlyLocked(adminReceiver, userHandle)) { 3291 throw new SecurityException("Attempt to remove non-test admin " 3292 + adminReceiver + " " + userHandle); 3293 } 3294 3295 // If admin is a device or profile owner tidy that up first. 3296 if (isDeviceOwner(adminReceiver, userHandle)) { 3297 clearDeviceOwnerLocked(getDeviceOwnerAdminLocked(), userHandle); 3298 } 3299 if (isProfileOwner(adminReceiver, userHandle)) { 3300 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, 3301 userHandle, /* parent */ false); 3302 clearProfileOwnerLocked(admin, userHandle); 3303 } 3304 } 3305 // Remove the admin skipping sending the broadcast. 3306 removeAdminArtifacts(adminReceiver, userHandle); 3307 Slog.i(LOG_TAG, "Admin " + adminReceiver + " removed from user " + userHandle); 3308 } finally { 3309 mInjector.binderRestoreCallingIdentity(ident); 3310 } 3311 } 3312 3313 private void clearDeviceOwnerUserRestrictionLocked(UserHandle userHandle) { 3314 // ManagedProvisioning/DPC sets DISALLOW_ADD_USER. Clear to recover to the original state 3315 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_USER, userHandle)) { 3316 mUserManager.setUserRestriction(UserManager.DISALLOW_ADD_USER, false, userHandle); 3317 } 3318 } 3319 3320 /** 3321 * Return if a given package has testOnly="true", in which case we'll relax certain rules 3322 * for CTS. 3323 * 3324 * DO NOT use this method except in {@link #setActiveAdmin}. Use {@link #isAdminTestOnlyLocked} 3325 * to check wehter an active admin is test-only or not. 3326 * 3327 * The system allows this flag to be changed when an app is updated, which is not good 3328 * for us. So we persist the flag in {@link ActiveAdmin} when an admin is first installed, 3329 * and used the persisted version in actual checks. (See b/31382361 and b/28928996) 3330 */ 3331 private boolean isPackageTestOnly(String packageName, int userHandle) { 3332 final ApplicationInfo ai; 3333 try { 3334 ai = mIPackageManager.getApplicationInfo(packageName, 3335 (PackageManager.MATCH_DIRECT_BOOT_AWARE 3336 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE), userHandle); 3337 } catch (RemoteException e) { 3338 throw new IllegalStateException(e); 3339 } 3340 if (ai == null) { 3341 throw new IllegalStateException("Couldn't find package: " 3342 + packageName + " on user " + userHandle); 3343 } 3344 return (ai.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0; 3345 } 3346 3347 /** 3348 * See {@link #isPackageTestOnly}. 3349 */ 3350 private boolean isAdminTestOnlyLocked(ComponentName who, int userHandle) { 3351 final ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3352 return (admin != null) && admin.testOnlyAdmin; 3353 } 3354 3355 private void enforceShell(String method) { 3356 final int callingUid = Binder.getCallingUid(); 3357 if (callingUid != Process.SHELL_UID && callingUid != Process.ROOT_UID) { 3358 throw new SecurityException("Non-shell user attempted to call " + method); 3359 } 3360 } 3361 3362 @Override 3363 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 3364 if (!mHasFeature) { 3365 return; 3366 } 3367 enforceFullCrossUsersPermission(userHandle); 3368 enforceUserUnlocked(userHandle); 3369 synchronized (this) { 3370 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 3371 if (admin == null) { 3372 return; 3373 } 3374 // Active device/profile owners must remain active admins. 3375 if (isDeviceOwner(adminReceiver, userHandle) 3376 || isProfileOwner(adminReceiver, userHandle)) { 3377 Slog.e(LOG_TAG, "Device/profile owner cannot be removed: component=" + 3378 adminReceiver); 3379 return; 3380 } 3381 if (admin.getUid() != mInjector.binderGetCallingUid()) { 3382 mContext.enforceCallingOrSelfPermission( 3383 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 3384 } 3385 long ident = mInjector.binderClearCallingIdentity(); 3386 try { 3387 removeActiveAdminLocked(adminReceiver, userHandle); 3388 } finally { 3389 mInjector.binderRestoreCallingIdentity(ident); 3390 } 3391 } 3392 } 3393 3394 @Override 3395 public boolean isSeparateProfileChallengeAllowed(int userHandle) { 3396 ComponentName profileOwner = getProfileOwner(userHandle); 3397 // Profile challenge is supported on N or newer release. 3398 return profileOwner != null && 3399 getTargetSdk(profileOwner.getPackageName(), userHandle) > Build.VERSION_CODES.M; 3400 } 3401 3402 @Override 3403 public void setPasswordQuality(ComponentName who, int quality, boolean parent) { 3404 if (!mHasFeature) { 3405 return; 3406 } 3407 Preconditions.checkNotNull(who, "ComponentName is null"); 3408 validateQualityConstant(quality); 3409 3410 synchronized (this) { 3411 ActiveAdmin ap = getActiveAdminForCallerLocked( 3412 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3413 if (ap.minimumPasswordMetrics.quality != quality) { 3414 ap.minimumPasswordMetrics.quality = quality; 3415 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3416 } 3417 } 3418 } 3419 3420 @Override 3421 public int getPasswordQuality(ComponentName who, int userHandle, boolean parent) { 3422 if (!mHasFeature) { 3423 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 3424 } 3425 enforceFullCrossUsersPermission(userHandle); 3426 synchronized (this) { 3427 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 3428 3429 if (who != null) { 3430 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3431 return admin != null ? admin.minimumPasswordMetrics.quality : mode; 3432 } 3433 3434 // Return the strictest policy across all participating admins. 3435 List<ActiveAdmin> admins = 3436 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3437 final int N = admins.size(); 3438 for (int i = 0; i < N; i++) { 3439 ActiveAdmin admin = admins.get(i); 3440 if (mode < admin.minimumPasswordMetrics.quality) { 3441 mode = admin.minimumPasswordMetrics.quality; 3442 } 3443 } 3444 return mode; 3445 } 3446 } 3447 3448 private List<ActiveAdmin> getActiveAdminsForLockscreenPoliciesLocked( 3449 int userHandle, boolean parent) { 3450 if (!parent && isSeparateProfileChallengeEnabled(userHandle)) { 3451 // If this user has a separate challenge, only return its restrictions. 3452 return getUserDataUnchecked(userHandle).mAdminList; 3453 } else { 3454 // Return all admins for this user and the profiles that are visible from this 3455 // user that do not use a separate work challenge. 3456 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 3457 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 3458 DevicePolicyData policy = getUserData(userInfo.id); 3459 if (!userInfo.isManagedProfile()) { 3460 admins.addAll(policy.mAdminList); 3461 } else { 3462 // For managed profiles, we always include the policies set on the parent 3463 // profile. Additionally, we include the ones set on the managed profile 3464 // if no separate challenge is in place. 3465 boolean hasSeparateChallenge = isSeparateProfileChallengeEnabled(userInfo.id); 3466 final int N = policy.mAdminList.size(); 3467 for (int i = 0; i < N; i++) { 3468 ActiveAdmin admin = policy.mAdminList.get(i); 3469 if (admin.hasParentActiveAdmin()) { 3470 admins.add(admin.getParentActiveAdmin()); 3471 } 3472 if (!hasSeparateChallenge) { 3473 admins.add(admin); 3474 } 3475 } 3476 } 3477 } 3478 return admins; 3479 } 3480 } 3481 3482 private boolean isSeparateProfileChallengeEnabled(int userHandle) { 3483 long ident = mInjector.binderClearCallingIdentity(); 3484 try { 3485 return mLockPatternUtils.isSeparateProfileChallengeEnabled(userHandle); 3486 } finally { 3487 mInjector.binderRestoreCallingIdentity(ident); 3488 } 3489 } 3490 3491 @Override 3492 public void setPasswordMinimumLength(ComponentName who, int length, boolean parent) { 3493 if (!mHasFeature) { 3494 return; 3495 } 3496 Preconditions.checkNotNull(who, "ComponentName is null"); 3497 synchronized (this) { 3498 ActiveAdmin ap = getActiveAdminForCallerLocked( 3499 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3500 if (ap.minimumPasswordMetrics.length != length) { 3501 ap.minimumPasswordMetrics.length = length; 3502 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3503 } 3504 } 3505 } 3506 3507 @Override 3508 public int getPasswordMinimumLength(ComponentName who, int userHandle, boolean parent) { 3509 if (!mHasFeature) { 3510 return 0; 3511 } 3512 enforceFullCrossUsersPermission(userHandle); 3513 synchronized (this) { 3514 int length = 0; 3515 3516 if (who != null) { 3517 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3518 return admin != null ? admin.minimumPasswordMetrics.length : length; 3519 } 3520 3521 // Return the strictest policy across all participating admins. 3522 List<ActiveAdmin> admins = 3523 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3524 final int N = admins.size(); 3525 for (int i = 0; i < N; i++) { 3526 ActiveAdmin admin = admins.get(i); 3527 if (length < admin.minimumPasswordMetrics.length) { 3528 length = admin.minimumPasswordMetrics.length; 3529 } 3530 } 3531 return length; 3532 } 3533 } 3534 3535 @Override 3536 public void setPasswordHistoryLength(ComponentName who, int length, boolean parent) { 3537 if (!mHasFeature) { 3538 return; 3539 } 3540 Preconditions.checkNotNull(who, "ComponentName is null"); 3541 synchronized (this) { 3542 ActiveAdmin ap = getActiveAdminForCallerLocked( 3543 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3544 if (ap.passwordHistoryLength != length) { 3545 ap.passwordHistoryLength = length; 3546 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3547 } 3548 } 3549 } 3550 3551 @Override 3552 public int getPasswordHistoryLength(ComponentName who, int userHandle, boolean parent) { 3553 if (!mHasFeature) { 3554 return 0; 3555 } 3556 enforceFullCrossUsersPermission(userHandle); 3557 synchronized (this) { 3558 int length = 0; 3559 3560 if (who != null) { 3561 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3562 return admin != null ? admin.passwordHistoryLength : length; 3563 } 3564 3565 // Return the strictest policy across all participating admins. 3566 List<ActiveAdmin> admins = 3567 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3568 final int N = admins.size(); 3569 for (int i = 0; i < N; i++) { 3570 ActiveAdmin admin = admins.get(i); 3571 if (length < admin.passwordHistoryLength) { 3572 length = admin.passwordHistoryLength; 3573 } 3574 } 3575 3576 return length; 3577 } 3578 } 3579 3580 @Override 3581 public void setPasswordExpirationTimeout(ComponentName who, long timeout, boolean parent) { 3582 if (!mHasFeature) { 3583 return; 3584 } 3585 Preconditions.checkNotNull(who, "ComponentName is null"); 3586 Preconditions.checkArgumentNonnegative(timeout, "Timeout must be >= 0 ms"); 3587 final int userHandle = mInjector.userHandleGetCallingUserId(); 3588 synchronized (this) { 3589 ActiveAdmin ap = getActiveAdminForCallerLocked( 3590 who, DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD, parent); 3591 // Calling this API automatically bumps the expiration date 3592 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 3593 ap.passwordExpirationDate = expiration; 3594 ap.passwordExpirationTimeout = timeout; 3595 if (timeout > 0L) { 3596 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 3597 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 3598 .format(new Date(expiration))); 3599 } 3600 saveSettingsLocked(userHandle); 3601 3602 // in case this is the first one, set the alarm on the appropriate user. 3603 setExpirationAlarmCheckLocked(mContext, userHandle, parent); 3604 } 3605 } 3606 3607 /** 3608 * Return a single admin's expiration cycle time, or the min of all cycle times. 3609 * Returns 0 if not configured. 3610 */ 3611 @Override 3612 public long getPasswordExpirationTimeout(ComponentName who, int userHandle, boolean parent) { 3613 if (!mHasFeature) { 3614 return 0L; 3615 } 3616 enforceFullCrossUsersPermission(userHandle); 3617 synchronized (this) { 3618 long timeout = 0L; 3619 3620 if (who != null) { 3621 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3622 return admin != null ? admin.passwordExpirationTimeout : timeout; 3623 } 3624 3625 // Return the strictest policy across all participating admins. 3626 List<ActiveAdmin> admins = 3627 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3628 final int N = admins.size(); 3629 for (int i = 0; i < N; i++) { 3630 ActiveAdmin admin = admins.get(i); 3631 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 3632 && timeout > admin.passwordExpirationTimeout)) { 3633 timeout = admin.passwordExpirationTimeout; 3634 } 3635 } 3636 return timeout; 3637 } 3638 } 3639 3640 @Override 3641 public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { 3642 final int userId = UserHandle.getCallingUserId(); 3643 List<String> changedProviders = null; 3644 3645 synchronized (this) { 3646 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3647 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3648 if (activeAdmin.crossProfileWidgetProviders == null) { 3649 activeAdmin.crossProfileWidgetProviders = new ArrayList<>(); 3650 } 3651 List<String> providers = activeAdmin.crossProfileWidgetProviders; 3652 if (!providers.contains(packageName)) { 3653 providers.add(packageName); 3654 changedProviders = new ArrayList<>(providers); 3655 saveSettingsLocked(userId); 3656 } 3657 } 3658 3659 if (changedProviders != null) { 3660 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 3661 return true; 3662 } 3663 3664 return false; 3665 } 3666 3667 @Override 3668 public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { 3669 final int userId = UserHandle.getCallingUserId(); 3670 List<String> changedProviders = null; 3671 3672 synchronized (this) { 3673 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3674 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3675 if (activeAdmin.crossProfileWidgetProviders == null 3676 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 3677 return false; 3678 } 3679 List<String> providers = activeAdmin.crossProfileWidgetProviders; 3680 if (providers.remove(packageName)) { 3681 changedProviders = new ArrayList<>(providers); 3682 saveSettingsLocked(userId); 3683 } 3684 } 3685 3686 if (changedProviders != null) { 3687 mLocalService.notifyCrossProfileProvidersChanged(userId, changedProviders); 3688 return true; 3689 } 3690 3691 return false; 3692 } 3693 3694 @Override 3695 public List<String> getCrossProfileWidgetProviders(ComponentName admin) { 3696 synchronized (this) { 3697 ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(admin, 3698 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3699 if (activeAdmin.crossProfileWidgetProviders == null 3700 || activeAdmin.crossProfileWidgetProviders.isEmpty()) { 3701 return null; 3702 } 3703 if (mInjector.binderIsCallingUidMyUid()) { 3704 return new ArrayList<>(activeAdmin.crossProfileWidgetProviders); 3705 } else { 3706 return activeAdmin.crossProfileWidgetProviders; 3707 } 3708 } 3709 } 3710 3711 /** 3712 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 3713 * Returns 0 if not configured. 3714 */ 3715 private long getPasswordExpirationLocked(ComponentName who, int userHandle, boolean parent) { 3716 long timeout = 0L; 3717 3718 if (who != null) { 3719 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3720 return admin != null ? admin.passwordExpirationDate : timeout; 3721 } 3722 3723 // Return the strictest policy across all participating admins. 3724 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3725 final int N = admins.size(); 3726 for (int i = 0; i < N; i++) { 3727 ActiveAdmin admin = admins.get(i); 3728 if (timeout == 0L || (admin.passwordExpirationDate != 0 3729 && timeout > admin.passwordExpirationDate)) { 3730 timeout = admin.passwordExpirationDate; 3731 } 3732 } 3733 return timeout; 3734 } 3735 3736 @Override 3737 public long getPasswordExpiration(ComponentName who, int userHandle, boolean parent) { 3738 if (!mHasFeature) { 3739 return 0L; 3740 } 3741 enforceFullCrossUsersPermission(userHandle); 3742 synchronized (this) { 3743 return getPasswordExpirationLocked(who, userHandle, parent); 3744 } 3745 } 3746 3747 @Override 3748 public void setPasswordMinimumUpperCase(ComponentName who, int length, boolean parent) { 3749 if (!mHasFeature) { 3750 return; 3751 } 3752 Preconditions.checkNotNull(who, "ComponentName is null"); 3753 synchronized (this) { 3754 ActiveAdmin ap = getActiveAdminForCallerLocked( 3755 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3756 if (ap.minimumPasswordMetrics.upperCase != length) { 3757 ap.minimumPasswordMetrics.upperCase = length; 3758 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3759 } 3760 } 3761 } 3762 3763 @Override 3764 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle, boolean parent) { 3765 if (!mHasFeature) { 3766 return 0; 3767 } 3768 enforceFullCrossUsersPermission(userHandle); 3769 synchronized (this) { 3770 int length = 0; 3771 3772 if (who != null) { 3773 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3774 return admin != null ? admin.minimumPasswordMetrics.upperCase : length; 3775 } 3776 3777 // Return the strictest policy across all participating admins. 3778 List<ActiveAdmin> admins = 3779 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3780 final int N = admins.size(); 3781 for (int i = 0; i < N; i++) { 3782 ActiveAdmin admin = admins.get(i); 3783 if (length < admin.minimumPasswordMetrics.upperCase) { 3784 length = admin.minimumPasswordMetrics.upperCase; 3785 } 3786 } 3787 return length; 3788 } 3789 } 3790 3791 @Override 3792 public void setPasswordMinimumLowerCase(ComponentName who, int length, boolean parent) { 3793 Preconditions.checkNotNull(who, "ComponentName is null"); 3794 synchronized (this) { 3795 ActiveAdmin ap = getActiveAdminForCallerLocked( 3796 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3797 if (ap.minimumPasswordMetrics.lowerCase != length) { 3798 ap.minimumPasswordMetrics.lowerCase = length; 3799 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3800 } 3801 } 3802 } 3803 3804 @Override 3805 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle, boolean parent) { 3806 if (!mHasFeature) { 3807 return 0; 3808 } 3809 enforceFullCrossUsersPermission(userHandle); 3810 synchronized (this) { 3811 int length = 0; 3812 3813 if (who != null) { 3814 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3815 return admin != null ? admin.minimumPasswordMetrics.lowerCase : length; 3816 } 3817 3818 // Return the strictest policy across all participating admins. 3819 List<ActiveAdmin> admins = 3820 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3821 final int N = admins.size(); 3822 for (int i = 0; i < N; i++) { 3823 ActiveAdmin admin = admins.get(i); 3824 if (length < admin.minimumPasswordMetrics.lowerCase) { 3825 length = admin.minimumPasswordMetrics.lowerCase; 3826 } 3827 } 3828 return length; 3829 } 3830 } 3831 3832 @Override 3833 public void setPasswordMinimumLetters(ComponentName who, int length, boolean parent) { 3834 if (!mHasFeature) { 3835 return; 3836 } 3837 Preconditions.checkNotNull(who, "ComponentName is null"); 3838 synchronized (this) { 3839 ActiveAdmin ap = getActiveAdminForCallerLocked( 3840 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3841 if (ap.minimumPasswordMetrics.letters != length) { 3842 ap.minimumPasswordMetrics.letters = length; 3843 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3844 } 3845 } 3846 } 3847 3848 @Override 3849 public int getPasswordMinimumLetters(ComponentName who, int userHandle, boolean parent) { 3850 if (!mHasFeature) { 3851 return 0; 3852 } 3853 enforceFullCrossUsersPermission(userHandle); 3854 synchronized (this) { 3855 int length = 0; 3856 3857 if (who != null) { 3858 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3859 return admin != null ? admin.minimumPasswordMetrics.letters : length; 3860 } 3861 3862 // Return the strictest policy across all participating admins. 3863 List<ActiveAdmin> admins = 3864 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3865 final int N = admins.size(); 3866 for (int i = 0; i < N; i++) { 3867 ActiveAdmin admin = admins.get(i); 3868 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3869 continue; 3870 } 3871 if (length < admin.minimumPasswordMetrics.letters) { 3872 length = admin.minimumPasswordMetrics.letters; 3873 } 3874 } 3875 return length; 3876 } 3877 } 3878 3879 @Override 3880 public void setPasswordMinimumNumeric(ComponentName who, int length, boolean parent) { 3881 if (!mHasFeature) { 3882 return; 3883 } 3884 Preconditions.checkNotNull(who, "ComponentName is null"); 3885 synchronized (this) { 3886 ActiveAdmin ap = getActiveAdminForCallerLocked( 3887 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3888 if (ap.minimumPasswordMetrics.numeric != length) { 3889 ap.minimumPasswordMetrics.numeric = length; 3890 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3891 } 3892 } 3893 } 3894 3895 @Override 3896 public int getPasswordMinimumNumeric(ComponentName who, int userHandle, boolean parent) { 3897 if (!mHasFeature) { 3898 return 0; 3899 } 3900 enforceFullCrossUsersPermission(userHandle); 3901 synchronized (this) { 3902 int length = 0; 3903 3904 if (who != null) { 3905 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3906 return admin != null ? admin.minimumPasswordMetrics.numeric : length; 3907 } 3908 3909 // Return the strictest policy across all participating admins. 3910 List<ActiveAdmin> admins = 3911 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3912 final int N = admins.size(); 3913 for (int i = 0; i < N; i++) { 3914 ActiveAdmin admin = admins.get(i); 3915 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3916 continue; 3917 } 3918 if (length < admin.minimumPasswordMetrics.numeric) { 3919 length = admin.minimumPasswordMetrics.numeric; 3920 } 3921 } 3922 return length; 3923 } 3924 } 3925 3926 @Override 3927 public void setPasswordMinimumSymbols(ComponentName who, int length, boolean parent) { 3928 if (!mHasFeature) { 3929 return; 3930 } 3931 Preconditions.checkNotNull(who, "ComponentName is null"); 3932 synchronized (this) { 3933 ActiveAdmin ap = getActiveAdminForCallerLocked( 3934 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3935 if (ap.minimumPasswordMetrics.symbols != length) { 3936 ap.minimumPasswordMetrics.symbols = length; 3937 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3938 } 3939 } 3940 } 3941 3942 @Override 3943 public int getPasswordMinimumSymbols(ComponentName who, int userHandle, boolean parent) { 3944 if (!mHasFeature) { 3945 return 0; 3946 } 3947 enforceFullCrossUsersPermission(userHandle); 3948 synchronized (this) { 3949 int length = 0; 3950 3951 if (who != null) { 3952 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 3953 return admin != null ? admin.minimumPasswordMetrics.symbols : length; 3954 } 3955 3956 // Return the strictest policy across all participating admins. 3957 List<ActiveAdmin> admins = 3958 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 3959 final int N = admins.size(); 3960 for (int i = 0; i < N; i++) { 3961 ActiveAdmin admin = admins.get(i); 3962 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 3963 continue; 3964 } 3965 if (length < admin.minimumPasswordMetrics.symbols) { 3966 length = admin.minimumPasswordMetrics.symbols; 3967 } 3968 } 3969 return length; 3970 } 3971 } 3972 3973 @Override 3974 public void setPasswordMinimumNonLetter(ComponentName who, int length, boolean parent) { 3975 if (!mHasFeature) { 3976 return; 3977 } 3978 Preconditions.checkNotNull(who, "ComponentName is null"); 3979 synchronized (this) { 3980 ActiveAdmin ap = getActiveAdminForCallerLocked( 3981 who, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 3982 if (ap.minimumPasswordMetrics.nonLetter != length) { 3983 ap.minimumPasswordMetrics.nonLetter = length; 3984 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 3985 } 3986 } 3987 } 3988 3989 @Override 3990 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle, boolean parent) { 3991 if (!mHasFeature) { 3992 return 0; 3993 } 3994 enforceFullCrossUsersPermission(userHandle); 3995 synchronized (this) { 3996 int length = 0; 3997 3998 if (who != null) { 3999 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4000 return admin != null ? admin.minimumPasswordMetrics.nonLetter : length; 4001 } 4002 4003 // Return the strictest policy across all participating admins. 4004 List<ActiveAdmin> admins = 4005 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4006 final int N = admins.size(); 4007 for (int i = 0; i < N; i++) { 4008 ActiveAdmin admin = admins.get(i); 4009 if (!isLimitPasswordAllowed(admin, PASSWORD_QUALITY_COMPLEX)) { 4010 continue; 4011 } 4012 if (length < admin.minimumPasswordMetrics.nonLetter) { 4013 length = admin.minimumPasswordMetrics.nonLetter; 4014 } 4015 } 4016 return length; 4017 } 4018 } 4019 4020 @Override 4021 public boolean isActivePasswordSufficient(int userHandle, boolean parent) { 4022 if (!mHasFeature) { 4023 return true; 4024 } 4025 enforceFullCrossUsersPermission(userHandle); 4026 4027 synchronized (this) { 4028 // This API can only be called by an active device admin, 4029 // so try to retrieve it to check that the caller is one. 4030 getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, parent); 4031 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4032 return isActivePasswordSufficientForUserLocked(policy, userHandle, parent); 4033 } 4034 } 4035 4036 @Override 4037 public boolean isProfileActivePasswordSufficientForParent(int userHandle) { 4038 if (!mHasFeature) { 4039 return true; 4040 } 4041 enforceFullCrossUsersPermission(userHandle); 4042 enforceManagedProfile(userHandle, "call APIs refering to the parent profile"); 4043 4044 synchronized (this) { 4045 int targetUser = getProfileParentId(userHandle); 4046 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, false)); 4047 return isActivePasswordSufficientForUserLocked(policy, targetUser, false); 4048 } 4049 } 4050 4051 private boolean isActivePasswordSufficientForUserLocked( 4052 DevicePolicyData policy, int userHandle, boolean parent) { 4053 enforceUserUnlocked(userHandle, parent); 4054 4055 final int requiredPasswordQuality = getPasswordQuality(null, userHandle, parent); 4056 if (policy.mActivePasswordMetrics.quality < requiredPasswordQuality) { 4057 return false; 4058 } 4059 if (requiredPasswordQuality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC 4060 && policy.mActivePasswordMetrics.length < getPasswordMinimumLength( 4061 null, userHandle, parent)) { 4062 return false; 4063 } 4064 if (requiredPasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4065 return true; 4066 } 4067 return policy.mActivePasswordMetrics.upperCase >= getPasswordMinimumUpperCase( 4068 null, userHandle, parent) 4069 && policy.mActivePasswordMetrics.lowerCase >= getPasswordMinimumLowerCase( 4070 null, userHandle, parent) 4071 && policy.mActivePasswordMetrics.letters >= getPasswordMinimumLetters( 4072 null, userHandle, parent) 4073 && policy.mActivePasswordMetrics.numeric >= getPasswordMinimumNumeric( 4074 null, userHandle, parent) 4075 && policy.mActivePasswordMetrics.symbols >= getPasswordMinimumSymbols( 4076 null, userHandle, parent) 4077 && policy.mActivePasswordMetrics.nonLetter >= getPasswordMinimumNonLetter( 4078 null, userHandle, parent); 4079 } 4080 4081 @Override 4082 public int getCurrentFailedPasswordAttempts(int userHandle, boolean parent) { 4083 enforceFullCrossUsersPermission(userHandle); 4084 synchronized (this) { 4085 if (!isCallerWithSystemUid()) { 4086 // This API can only be called by an active device admin, 4087 // so try to retrieve it to check that the caller is one. 4088 getActiveAdminForCallerLocked( 4089 null, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4090 } 4091 4092 DevicePolicyData policy = getUserDataUnchecked(getCredentialOwner(userHandle, parent)); 4093 4094 return policy.mFailedPasswordAttempts; 4095 } 4096 } 4097 4098 @Override 4099 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, boolean parent) { 4100 if (!mHasFeature) { 4101 return; 4102 } 4103 Preconditions.checkNotNull(who, "ComponentName is null"); 4104 synchronized (this) { 4105 // This API can only be called by an active device admin, 4106 // so try to retrieve it to check that the caller is one. 4107 getActiveAdminForCallerLocked( 4108 who, DeviceAdminInfo.USES_POLICY_WIPE_DATA, parent); 4109 ActiveAdmin ap = getActiveAdminForCallerLocked( 4110 who, DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, parent); 4111 if (ap.maximumFailedPasswordsForWipe != num) { 4112 ap.maximumFailedPasswordsForWipe = num; 4113 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 4114 } 4115 } 4116 } 4117 4118 @Override 4119 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle, boolean parent) { 4120 if (!mHasFeature) { 4121 return 0; 4122 } 4123 enforceFullCrossUsersPermission(userHandle); 4124 synchronized (this) { 4125 ActiveAdmin admin = (who != null) 4126 ? getActiveAdminUncheckedLocked(who, userHandle, parent) 4127 : getAdminWithMinimumFailedPasswordsForWipeLocked(userHandle, parent); 4128 return admin != null ? admin.maximumFailedPasswordsForWipe : 0; 4129 } 4130 } 4131 4132 @Override 4133 public int getProfileWithMinimumFailedPasswordsForWipe(int userHandle, boolean parent) { 4134 if (!mHasFeature) { 4135 return UserHandle.USER_NULL; 4136 } 4137 enforceFullCrossUsersPermission(userHandle); 4138 synchronized (this) { 4139 ActiveAdmin admin = getAdminWithMinimumFailedPasswordsForWipeLocked( 4140 userHandle, parent); 4141 return admin != null ? admin.getUserHandle().getIdentifier() : UserHandle.USER_NULL; 4142 } 4143 } 4144 4145 /** 4146 * Returns the admin with the strictest policy on maximum failed passwords for: 4147 * <ul> 4148 * <li>this user if it has a separate profile challenge, or 4149 * <li>this user and all profiles that don't have their own challenge otherwise. 4150 * </ul> 4151 * <p>If the policy for the primary and any other profile are equal, it returns the admin for 4152 * the primary profile. 4153 * Returns {@code null} if no participating admin has that policy set. 4154 */ 4155 private ActiveAdmin getAdminWithMinimumFailedPasswordsForWipeLocked( 4156 int userHandle, boolean parent) { 4157 int count = 0; 4158 ActiveAdmin strictestAdmin = null; 4159 4160 // Return the strictest policy across all participating admins. 4161 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 4162 final int N = admins.size(); 4163 for (int i = 0; i < N; i++) { 4164 ActiveAdmin admin = admins.get(i); 4165 if (admin.maximumFailedPasswordsForWipe == 4166 ActiveAdmin.DEF_MAXIMUM_FAILED_PASSWORDS_FOR_WIPE) { 4167 continue; // No max number of failed passwords policy set for this profile. 4168 } 4169 4170 // We always favor the primary profile if several profiles have the same value set. 4171 int userId = admin.getUserHandle().getIdentifier(); 4172 if (count == 0 || 4173 count > admin.maximumFailedPasswordsForWipe || 4174 (count == admin.maximumFailedPasswordsForWipe && 4175 getUserInfo(userId).isPrimary())) { 4176 count = admin.maximumFailedPasswordsForWipe; 4177 strictestAdmin = admin; 4178 } 4179 } 4180 return strictestAdmin; 4181 } 4182 4183 private UserInfo getUserInfo(@UserIdInt int userId) { 4184 final long token = mInjector.binderClearCallingIdentity(); 4185 try { 4186 return mUserManager.getUserInfo(userId); 4187 } finally { 4188 mInjector.binderRestoreCallingIdentity(token); 4189 } 4190 } 4191 @Override 4192 public boolean resetPassword(String passwordOrNull, int flags) throws RemoteException { 4193 final int callingUid = mInjector.binderGetCallingUid(); 4194 final int userHandle = mInjector.userHandleGetCallingUserId(); 4195 4196 String password = passwordOrNull != null ? passwordOrNull : ""; 4197 4198 // Password resetting to empty/null is not allowed for managed profiles. 4199 if (TextUtils.isEmpty(password)) { 4200 enforceNotManagedProfile(userHandle, "clear the active password"); 4201 } 4202 4203 synchronized (this) { 4204 // If caller has PO (or DO) it can change the password, so see if that's the case first. 4205 ActiveAdmin admin = getActiveAdminWithPolicyForUidLocked( 4206 null, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, callingUid); 4207 final boolean preN; 4208 if (admin != null) { 4209 final int targetSdk = getTargetSdk(admin.info.getPackageName(), userHandle); 4210 if (targetSdk >= Build.VERSION_CODES.O) { 4211 throw new SecurityException("resetPassword() is deprecated for DPC targeting O" 4212 + " or later"); 4213 } 4214 preN = targetSdk <= android.os.Build.VERSION_CODES.M; 4215 } else { 4216 // Otherwise, make sure the caller has any active admin with the right policy. 4217 admin = getActiveAdminForCallerLocked(null, 4218 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 4219 preN = getTargetSdk(admin.info.getPackageName(), 4220 userHandle) <= android.os.Build.VERSION_CODES.M; 4221 4222 // As of N, password resetting to empty/null is not allowed anymore. 4223 // TODO Should we allow DO/PO to set an empty password? 4224 if (TextUtils.isEmpty(password)) { 4225 if (!preN) { 4226 throw new SecurityException("Cannot call with null password"); 4227 } else { 4228 Slog.e(LOG_TAG, "Cannot call with null password"); 4229 return false; 4230 } 4231 } 4232 // As of N, password cannot be changed by the admin if it is already set. 4233 if (isLockScreenSecureUnchecked(userHandle)) { 4234 if (!preN) { 4235 throw new SecurityException("Admin cannot change current password"); 4236 } else { 4237 Slog.e(LOG_TAG, "Admin cannot change current password"); 4238 return false; 4239 } 4240 } 4241 } 4242 // Do not allow to reset password when current user has a managed profile 4243 if (!isManagedProfile(userHandle)) { 4244 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4245 if (userInfo.isManagedProfile()) { 4246 if (!preN) { 4247 throw new IllegalStateException( 4248 "Cannot reset password on user has managed profile"); 4249 } else { 4250 Slog.e(LOG_TAG, "Cannot reset password on user has managed profile"); 4251 return false; 4252 } 4253 } 4254 } 4255 } 4256 // Do not allow to reset password when user is locked 4257 if (!mUserManager.isUserUnlocked(userHandle)) { 4258 if (!preN) { 4259 throw new IllegalStateException("Cannot reset password when user is locked"); 4260 } else { 4261 Slog.e(LOG_TAG, "Cannot reset password when user is locked"); 4262 return false; 4263 } 4264 } 4265 } 4266 4267 return resetPasswordInternal(password, 0, null, flags, callingUid, userHandle); 4268 } 4269 4270 private boolean resetPasswordInternal(String password, long tokenHandle, byte[] token, 4271 int flags, int callingUid, int userHandle) { 4272 int quality; 4273 synchronized (this) { 4274 quality = getPasswordQuality(null, userHandle, /* parent */ false); 4275 if (quality == DevicePolicyManager.PASSWORD_QUALITY_MANAGED) { 4276 quality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 4277 } 4278 final PasswordMetrics metrics = PasswordMetrics.computeForPassword(password); 4279 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 4280 final int realQuality = metrics.quality; 4281 if (realQuality < quality 4282 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4283 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 4284 + Integer.toHexString(realQuality) 4285 + " does not meet required quality 0x" 4286 + Integer.toHexString(quality)); 4287 return false; 4288 } 4289 quality = Math.max(realQuality, quality); 4290 } 4291 int length = getPasswordMinimumLength(null, userHandle, /* parent */ false); 4292 if (password.length() < length) { 4293 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 4294 + " does not meet required length " + length); 4295 return false; 4296 } 4297 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 4298 int neededLetters = getPasswordMinimumLetters(null, userHandle, /* parent */ false); 4299 if(metrics.letters < neededLetters) { 4300 Slog.w(LOG_TAG, "resetPassword: number of letters " + metrics.letters 4301 + " does not meet required number of letters " + neededLetters); 4302 return false; 4303 } 4304 int neededNumeric = getPasswordMinimumNumeric(null, userHandle, /* parent */ false); 4305 if (metrics.numeric < neededNumeric) { 4306 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + metrics.numeric 4307 + " does not meet required number of numerical digits " 4308 + neededNumeric); 4309 return false; 4310 } 4311 int neededLowerCase = getPasswordMinimumLowerCase( 4312 null, userHandle, /* parent */ false); 4313 if (metrics.lowerCase < neededLowerCase) { 4314 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " 4315 + metrics.lowerCase 4316 + " does not meet required number of lowercase letters " 4317 + neededLowerCase); 4318 return false; 4319 } 4320 int neededUpperCase = getPasswordMinimumUpperCase( 4321 null, userHandle, /* parent */ false); 4322 if (metrics.upperCase < neededUpperCase) { 4323 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " 4324 + metrics.upperCase 4325 + " does not meet required number of uppercase letters " 4326 + neededUpperCase); 4327 return false; 4328 } 4329 int neededSymbols = getPasswordMinimumSymbols(null, userHandle, /* parent */ false); 4330 if (metrics.symbols < neededSymbols) { 4331 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + metrics.symbols 4332 + " does not meet required number of special symbols " + neededSymbols); 4333 return false; 4334 } 4335 int neededNonLetter = getPasswordMinimumNonLetter( 4336 null, userHandle, /* parent */ false); 4337 if (metrics.nonLetter < neededNonLetter) { 4338 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " 4339 + metrics.nonLetter 4340 + " does not meet required number of non-letter characters " 4341 + neededNonLetter); 4342 return false; 4343 } 4344 } 4345 } 4346 4347 DevicePolicyData policy = getUserData(userHandle); 4348 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 4349 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 4350 return false; 4351 } 4352 4353 boolean callerIsDeviceOwnerAdmin = isCallerDeviceOwner(callingUid); 4354 boolean doNotAskCredentialsOnBoot = 4355 (flags & DevicePolicyManager.RESET_PASSWORD_DO_NOT_ASK_CREDENTIALS_ON_BOOT) != 0; 4356 if (callerIsDeviceOwnerAdmin && doNotAskCredentialsOnBoot) { 4357 setDoNotAskCredentialsOnBoot(); 4358 } 4359 4360 // Don't do this with the lock held, because it is going to call 4361 // back in to the service. 4362 final long ident = mInjector.binderClearCallingIdentity(); 4363 final boolean result; 4364 try { 4365 if (token == null) { 4366 if (!TextUtils.isEmpty(password)) { 4367 mLockPatternUtils.saveLockPassword(password, null, quality, userHandle); 4368 } else { 4369 mLockPatternUtils.clearLock(null, userHandle); 4370 } 4371 result = true; 4372 } else { 4373 result = mLockPatternUtils.setLockCredentialWithToken(password, 4374 TextUtils.isEmpty(password) ? LockPatternUtils.CREDENTIAL_TYPE_NONE 4375 : LockPatternUtils.CREDENTIAL_TYPE_PASSWORD, 4376 tokenHandle, token, userHandle); 4377 } 4378 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 4379 if (requireEntry) { 4380 mLockPatternUtils.requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, 4381 UserHandle.USER_ALL); 4382 } 4383 synchronized (this) { 4384 int newOwner = requireEntry ? callingUid : -1; 4385 if (policy.mPasswordOwner != newOwner) { 4386 policy.mPasswordOwner = newOwner; 4387 saveSettingsLocked(userHandle); 4388 } 4389 } 4390 } finally { 4391 mInjector.binderRestoreCallingIdentity(ident); 4392 } 4393 return result; 4394 } 4395 4396 private boolean isLockScreenSecureUnchecked(int userId) { 4397 long ident = mInjector.binderClearCallingIdentity(); 4398 try { 4399 return mLockPatternUtils.isSecure(userId); 4400 } finally { 4401 mInjector.binderRestoreCallingIdentity(ident); 4402 } 4403 } 4404 4405 private void setDoNotAskCredentialsOnBoot() { 4406 synchronized (this) { 4407 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4408 if (!policyData.doNotAskCredentialsOnBoot) { 4409 policyData.doNotAskCredentialsOnBoot = true; 4410 saveSettingsLocked(UserHandle.USER_SYSTEM); 4411 } 4412 } 4413 } 4414 4415 @Override 4416 public boolean getDoNotAskCredentialsOnBoot() { 4417 mContext.enforceCallingOrSelfPermission( 4418 android.Manifest.permission.QUERY_DO_NOT_ASK_CREDENTIALS_ON_BOOT, null); 4419 synchronized (this) { 4420 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 4421 return policyData.doNotAskCredentialsOnBoot; 4422 } 4423 } 4424 4425 @Override 4426 public void setMaximumTimeToLock(ComponentName who, long timeMs, boolean parent) { 4427 if (!mHasFeature) { 4428 return; 4429 } 4430 Preconditions.checkNotNull(who, "ComponentName is null"); 4431 final int userHandle = mInjector.userHandleGetCallingUserId(); 4432 synchronized (this) { 4433 ActiveAdmin ap = getActiveAdminForCallerLocked( 4434 who, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4435 if (ap.maximumTimeToUnlock != timeMs) { 4436 ap.maximumTimeToUnlock = timeMs; 4437 saveSettingsLocked(userHandle); 4438 updateMaximumTimeToLockLocked(userHandle); 4439 } 4440 } 4441 } 4442 4443 void updateMaximumTimeToLockLocked(int userHandle) { 4444 // Calculate the min timeout for all profiles - including the ones with a separate 4445 // challenge. Ideally if the timeout only affected the profile challenge we'd lock that 4446 // challenge only and keep the screen on. However there is no easy way of doing that at the 4447 // moment so we set the screen off timeout regardless of whether it affects the parent user 4448 // or the profile challenge only. 4449 long timeMs = Long.MAX_VALUE; 4450 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userHandle); 4451 for (int profileId : profileIds) { 4452 DevicePolicyData policy = getUserDataUnchecked(profileId); 4453 final int N = policy.mAdminList.size(); 4454 for (int i = 0; i < N; i++) { 4455 ActiveAdmin admin = policy.mAdminList.get(i); 4456 if (admin.maximumTimeToUnlock > 0 4457 && timeMs > admin.maximumTimeToUnlock) { 4458 timeMs = admin.maximumTimeToUnlock; 4459 } 4460 // If userInfo.id is a managed profile, we also need to look at 4461 // the policies set on the parent. 4462 if (admin.hasParentActiveAdmin()) { 4463 final ActiveAdmin parentAdmin = admin.getParentActiveAdmin(); 4464 if (parentAdmin.maximumTimeToUnlock > 0 4465 && timeMs > parentAdmin.maximumTimeToUnlock) { 4466 timeMs = parentAdmin.maximumTimeToUnlock; 4467 } 4468 } 4469 } 4470 } 4471 4472 // We only store the last maximum time to lock on the parent profile. So if calling from a 4473 // managed profile, retrieve the policy for the parent. 4474 DevicePolicyData policy = getUserDataUnchecked(getProfileParentId(userHandle)); 4475 if (policy.mLastMaximumTimeToLock == timeMs) { 4476 return; 4477 } 4478 policy.mLastMaximumTimeToLock = timeMs; 4479 4480 final long ident = mInjector.binderClearCallingIdentity(); 4481 try { 4482 if (policy.mLastMaximumTimeToLock != Long.MAX_VALUE) { 4483 // Make sure KEEP_SCREEN_ON is disabled, since that 4484 // would allow bypassing of the maximum time to lock. 4485 mInjector.settingsGlobalPutInt(Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 4486 } 4487 4488 mInjector.getPowerManagerInternal().setMaximumScreenOffTimeoutFromDeviceAdmin( 4489 (int) Math.min(policy.mLastMaximumTimeToLock, Integer.MAX_VALUE)); 4490 } finally { 4491 mInjector.binderRestoreCallingIdentity(ident); 4492 } 4493 } 4494 4495 @Override 4496 public long getMaximumTimeToLock(ComponentName who, int userHandle, boolean parent) { 4497 if (!mHasFeature) { 4498 return 0; 4499 } 4500 enforceFullCrossUsersPermission(userHandle); 4501 synchronized (this) { 4502 if (who != null) { 4503 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 4504 return admin != null ? admin.maximumTimeToUnlock : 0; 4505 } 4506 // Return the strictest policy across all participating admins. 4507 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 4508 userHandle, parent); 4509 return getMaximumTimeToLockPolicyFromAdmins(admins); 4510 } 4511 } 4512 4513 @Override 4514 public long getMaximumTimeToLockForUserAndProfiles(int userHandle) { 4515 if (!mHasFeature) { 4516 return 0; 4517 } 4518 enforceFullCrossUsersPermission(userHandle); 4519 synchronized (this) { 4520 // All admins for this user. 4521 ArrayList<ActiveAdmin> admins = new ArrayList<ActiveAdmin>(); 4522 for (UserInfo userInfo : mUserManager.getProfiles(userHandle)) { 4523 DevicePolicyData policy = getUserData(userInfo.id); 4524 admins.addAll(policy.mAdminList); 4525 // If it is a managed profile, it may have parent active admins 4526 if (userInfo.isManagedProfile()) { 4527 for (ActiveAdmin admin : policy.mAdminList) { 4528 if (admin.hasParentActiveAdmin()) { 4529 admins.add(admin.getParentActiveAdmin()); 4530 } 4531 } 4532 } 4533 } 4534 return getMaximumTimeToLockPolicyFromAdmins(admins); 4535 } 4536 } 4537 4538 private long getMaximumTimeToLockPolicyFromAdmins(List<ActiveAdmin> admins) { 4539 long time = 0; 4540 final int N = admins.size(); 4541 for (int i = 0; i < N; i++) { 4542 ActiveAdmin admin = admins.get(i); 4543 if (time == 0) { 4544 time = admin.maximumTimeToUnlock; 4545 } else if (admin.maximumTimeToUnlock != 0 4546 && time > admin.maximumTimeToUnlock) { 4547 time = admin.maximumTimeToUnlock; 4548 } 4549 } 4550 return time; 4551 } 4552 4553 @Override 4554 public void setRequiredStrongAuthTimeout(ComponentName who, long timeoutMs, 4555 boolean parent) { 4556 if (!mHasFeature) { 4557 return; 4558 } 4559 Preconditions.checkNotNull(who, "ComponentName is null"); 4560 Preconditions.checkArgument(timeoutMs >= 0, "Timeout must not be a negative number."); 4561 // timeoutMs with value 0 means that the admin doesn't participate 4562 // timeoutMs is clamped to the interval in case the internal constants change in the future 4563 final long minimumStrongAuthTimeout = getMinimumStrongAuthTimeoutMs(); 4564 if (timeoutMs != 0 && timeoutMs < minimumStrongAuthTimeout) { 4565 timeoutMs = minimumStrongAuthTimeout; 4566 } 4567 if (timeoutMs > DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS) { 4568 timeoutMs = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4569 } 4570 4571 final int userHandle = mInjector.userHandleGetCallingUserId(); 4572 synchronized (this) { 4573 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 4574 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, parent); 4575 if (ap.strongAuthUnlockTimeout != timeoutMs) { 4576 ap.strongAuthUnlockTimeout = timeoutMs; 4577 saveSettingsLocked(userHandle); 4578 } 4579 } 4580 } 4581 4582 /** 4583 * Return a single admin's strong auth unlock timeout or minimum value (strictest) of all 4584 * admins if who is null. 4585 * Returns 0 if not configured for the provided admin. 4586 */ 4587 @Override 4588 public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) { 4589 if (!mHasFeature) { 4590 return DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4591 } 4592 enforceFullCrossUsersPermission(userId); 4593 synchronized (this) { 4594 if (who != null) { 4595 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent); 4596 return admin != null ? admin.strongAuthUnlockTimeout : 0; 4597 } 4598 4599 // Return the strictest policy across all participating admins. 4600 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent); 4601 4602 long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS; 4603 for (int i = 0; i < admins.size(); i++) { 4604 final long timeout = admins.get(i).strongAuthUnlockTimeout; 4605 if (timeout != 0) { // take only participating admins into account 4606 strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout); 4607 } 4608 } 4609 return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs()); 4610 } 4611 } 4612 4613 private long getMinimumStrongAuthTimeoutMs() { 4614 if (!mInjector.isBuildDebuggable()) { 4615 return MINIMUM_STRONG_AUTH_TIMEOUT_MS; 4616 } 4617 // ideally the property was named persist.sys.min_strong_auth_timeout, but system property 4618 // name cannot be longer than 31 characters 4619 return Math.min(mInjector.systemPropertiesGetLong("persist.sys.min_str_auth_timeo", 4620 MINIMUM_STRONG_AUTH_TIMEOUT_MS), 4621 MINIMUM_STRONG_AUTH_TIMEOUT_MS); 4622 } 4623 4624 @Override 4625 public void lockNow(int flags, boolean parent) { 4626 if (!mHasFeature) { 4627 return; 4628 } 4629 4630 final int callingUserId = mInjector.userHandleGetCallingUserId(); 4631 synchronized (this) { 4632 // This API can only be called by an active device admin, 4633 // so try to retrieve it to check that the caller is one. 4634 final ActiveAdmin admin = getActiveAdminForCallerLocked( 4635 null, DeviceAdminInfo.USES_POLICY_FORCE_LOCK, parent); 4636 4637 final long ident = mInjector.binderClearCallingIdentity(); 4638 try { 4639 // Evict key 4640 if ((flags & DevicePolicyManager.FLAG_EVICT_CE_KEY) != 0) { 4641 enforceManagedProfile(callingUserId, "set FLAG_EVICT_CE_KEY"); 4642 if (!isProfileOwner(admin.info.getComponent(), callingUserId)) { 4643 throw new SecurityException( 4644 "Only profile owner admins can set FLAG_EVICT_CE_KEY"); 4645 } 4646 if (parent) { 4647 throw new IllegalArgumentException( 4648 "Cannot set FLAG_EVICT_CE_KEY for the parent"); 4649 } 4650 if (!mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 4651 throw new UnsupportedOperationException( 4652 "FLAG_EVICT_CE_KEY only applies to FBE devices"); 4653 } 4654 mUserManager.evictCredentialEncryptionKey(callingUserId); 4655 } 4656 4657 // Lock all users unless this is a managed profile with a separate challenge 4658 final int userToLock = (parent || !isSeparateProfileChallengeEnabled(callingUserId) 4659 ? UserHandle.USER_ALL : callingUserId); 4660 mLockPatternUtils.requireStrongAuth( 4661 STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW, userToLock); 4662 4663 // Require authentication for the device or profile 4664 if (userToLock == UserHandle.USER_ALL) { 4665 // Power off the display 4666 mInjector.powerManagerGoToSleep(SystemClock.uptimeMillis(), 4667 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 4668 mInjector.getIWindowManager().lockNow(null); 4669 } else { 4670 mInjector.getTrustManager().setDeviceLockedForUser(userToLock, true); 4671 } 4672 } catch (RemoteException e) { 4673 } finally { 4674 mInjector.binderRestoreCallingIdentity(ident); 4675 } 4676 } 4677 } 4678 4679 @Override 4680 public void enforceCanManageCaCerts(ComponentName who, String callerPackage) { 4681 if (who == null) { 4682 if (!isCallerDelegate(callerPackage, DELEGATION_CERT_INSTALL)) { 4683 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 4684 } 4685 } else { 4686 enforceProfileOrDeviceOwner(who); 4687 } 4688 } 4689 4690 private void enforceProfileOrDeviceOwner(ComponentName who) { 4691 synchronized (this) { 4692 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4693 } 4694 } 4695 4696 @Override 4697 public boolean approveCaCert(String alias, int userId, boolean approval) { 4698 enforceManageUsers(); 4699 synchronized (this) { 4700 Set<String> certs = getUserData(userId).mAcceptedCaCertificates; 4701 boolean changed = (approval ? certs.add(alias) : certs.remove(alias)); 4702 if (!changed) { 4703 return false; 4704 } 4705 saveSettingsLocked(userId); 4706 } 4707 mCertificateMonitor.onCertificateApprovalsChanged(userId); 4708 return true; 4709 } 4710 4711 @Override 4712 public boolean isCaCertApproved(String alias, int userId) { 4713 enforceManageUsers(); 4714 synchronized (this) { 4715 return getUserData(userId).mAcceptedCaCertificates.contains(alias); 4716 } 4717 } 4718 4719 private void removeCaApprovalsIfNeeded(int userId) { 4720 for (UserInfo userInfo : mUserManager.getProfiles(userId)) { 4721 boolean isSecure = mLockPatternUtils.isSecure(userInfo.id); 4722 if (userInfo.isManagedProfile()){ 4723 isSecure |= mLockPatternUtils.isSecure(getProfileParentId(userInfo.id)); 4724 } 4725 if (!isSecure) { 4726 synchronized (this) { 4727 getUserData(userInfo.id).mAcceptedCaCertificates.clear(); 4728 saveSettingsLocked(userInfo.id); 4729 } 4730 mCertificateMonitor.onCertificateApprovalsChanged(userId); 4731 } 4732 } 4733 } 4734 4735 @Override 4736 public boolean installCaCert(ComponentName admin, String callerPackage, byte[] certBuffer) 4737 throws RemoteException { 4738 if (!mHasFeature) { 4739 return false; 4740 } 4741 enforceCanManageCaCerts(admin, callerPackage); 4742 4743 final String alias; 4744 4745 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 4746 final long id = mInjector.binderClearCallingIdentity(); 4747 try { 4748 alias = mCertificateMonitor.installCaCert(userHandle, certBuffer); 4749 if (alias == null) { 4750 Log.w(LOG_TAG, "Problem installing cert"); 4751 return false; 4752 } 4753 } finally { 4754 mInjector.binderRestoreCallingIdentity(id); 4755 } 4756 4757 synchronized (this) { 4758 getUserData(userHandle.getIdentifier()).mOwnerInstalledCaCerts.add(alias); 4759 saveSettingsLocked(userHandle.getIdentifier()); 4760 } 4761 return true; 4762 } 4763 4764 @Override 4765 public void uninstallCaCerts(ComponentName admin, String callerPackage, String[] aliases) { 4766 if (!mHasFeature) { 4767 return; 4768 } 4769 enforceCanManageCaCerts(admin, callerPackage); 4770 4771 final int userId = mInjector.userHandleGetCallingUserId(); 4772 final long id = mInjector.binderClearCallingIdentity(); 4773 try { 4774 mCertificateMonitor.uninstallCaCerts(UserHandle.of(userId), aliases); 4775 } finally { 4776 mInjector.binderRestoreCallingIdentity(id); 4777 } 4778 4779 synchronized (this) { 4780 if (getUserData(userId).mOwnerInstalledCaCerts.removeAll(Arrays.asList(aliases))) { 4781 saveSettingsLocked(userId); 4782 } 4783 } 4784 } 4785 4786 @Override 4787 public boolean installKeyPair(ComponentName who, String callerPackage, byte[] privKey, 4788 byte[] cert, byte[] chain, String alias, boolean requestAccess) { 4789 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 4790 DELEGATION_CERT_INSTALL); 4791 4792 4793 final int callingUid = mInjector.binderGetCallingUid(); 4794 final long id = mInjector.binderClearCallingIdentity(); 4795 try { 4796 final KeyChainConnection keyChainConnection = 4797 KeyChain.bindAsUser(mContext, UserHandle.getUserHandleForUid(callingUid)); 4798 try { 4799 IKeyChainService keyChain = keyChainConnection.getService(); 4800 if (!keyChain.installKeyPair(privKey, cert, chain, alias)) { 4801 return false; 4802 } 4803 if (requestAccess) { 4804 keyChain.setGrant(callingUid, alias, true); 4805 } 4806 return true; 4807 } catch (RemoteException e) { 4808 Log.e(LOG_TAG, "Installing certificate", e); 4809 } finally { 4810 keyChainConnection.close(); 4811 } 4812 } catch (InterruptedException e) { 4813 Log.w(LOG_TAG, "Interrupted while installing certificate", e); 4814 Thread.currentThread().interrupt(); 4815 } finally { 4816 mInjector.binderRestoreCallingIdentity(id); 4817 } 4818 return false; 4819 } 4820 4821 @Override 4822 public boolean removeKeyPair(ComponentName who, String callerPackage, String alias) { 4823 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 4824 DELEGATION_CERT_INSTALL); 4825 4826 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 4827 final long id = Binder.clearCallingIdentity(); 4828 try { 4829 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 4830 try { 4831 IKeyChainService keyChain = keyChainConnection.getService(); 4832 return keyChain.removeKeyPair(alias); 4833 } catch (RemoteException e) { 4834 Log.e(LOG_TAG, "Removing keypair", e); 4835 } finally { 4836 keyChainConnection.close(); 4837 } 4838 } catch (InterruptedException e) { 4839 Log.w(LOG_TAG, "Interrupted while removing keypair", e); 4840 Thread.currentThread().interrupt(); 4841 } finally { 4842 Binder.restoreCallingIdentity(id); 4843 } 4844 return false; 4845 } 4846 4847 @Override 4848 public void choosePrivateKeyAlias(final int uid, final Uri uri, final String alias, 4849 final IBinder response) { 4850 // Caller UID needs to be trusted, so we restrict this method to SYSTEM_UID callers. 4851 if (!isCallerWithSystemUid()) { 4852 return; 4853 } 4854 4855 final UserHandle caller = mInjector.binderGetCallingUserHandle(); 4856 // If there is a profile owner, redirect to that; otherwise query the device owner. 4857 ComponentName aliasChooser = getProfileOwner(caller.getIdentifier()); 4858 if (aliasChooser == null && caller.isSystem()) { 4859 ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 4860 if (deviceOwnerAdmin != null) { 4861 aliasChooser = deviceOwnerAdmin.info.getComponent(); 4862 } 4863 } 4864 if (aliasChooser == null) { 4865 sendPrivateKeyAliasResponse(null, response); 4866 return; 4867 } 4868 4869 Intent intent = new Intent(DeviceAdminReceiver.ACTION_CHOOSE_PRIVATE_KEY_ALIAS); 4870 intent.setComponent(aliasChooser); 4871 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_SENDER_UID, uid); 4872 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_URI, uri); 4873 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_ALIAS, alias); 4874 intent.putExtra(DeviceAdminReceiver.EXTRA_CHOOSE_PRIVATE_KEY_RESPONSE, response); 4875 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 4876 4877 final long id = mInjector.binderClearCallingIdentity(); 4878 try { 4879 mContext.sendOrderedBroadcastAsUser(intent, caller, null, new BroadcastReceiver() { 4880 @Override 4881 public void onReceive(Context context, Intent intent) { 4882 final String chosenAlias = getResultData(); 4883 sendPrivateKeyAliasResponse(chosenAlias, response); 4884 } 4885 }, null, Activity.RESULT_OK, null, null); 4886 } finally { 4887 mInjector.binderRestoreCallingIdentity(id); 4888 } 4889 } 4890 4891 private void sendPrivateKeyAliasResponse(final String alias, final IBinder responseBinder) { 4892 final IKeyChainAliasCallback keyChainAliasResponse = 4893 IKeyChainAliasCallback.Stub.asInterface(responseBinder); 4894 // Send the response. It's OK to do this from the main thread because IKeyChainAliasCallback 4895 // is oneway, which means it won't block if the recipient lives in another process. 4896 try { 4897 keyChainAliasResponse.alias(alias); 4898 } catch (Exception e) { 4899 // Caller could throw RuntimeException or RemoteException back across processes. Catch 4900 // everything just to be sure. 4901 Log.e(LOG_TAG, "error while responding to callback", e); 4902 } 4903 } 4904 4905 /** 4906 * Determine whether DPMS should check if a delegate package is already installed before 4907 * granting it new delegations via {@link #setDelegatedScopes}. 4908 */ 4909 private static boolean shouldCheckIfDelegatePackageIsInstalled(String delegatePackage, 4910 int targetSdk, List<String> scopes) { 4911 // 1) Never skip is installed check from N. 4912 if (targetSdk >= Build.VERSION_CODES.N) { 4913 return true; 4914 } 4915 // 2) Skip if DELEGATION_CERT_INSTALL is the only scope being given. 4916 if (scopes.size() == 1 && scopes.get(0).equals(DELEGATION_CERT_INSTALL)) { 4917 return false; 4918 } 4919 // 3) Skip if all previously granted scopes are being cleared. 4920 if (scopes.isEmpty()) { 4921 return false; 4922 } 4923 // Otherwise it should check that delegatePackage is installed. 4924 return true; 4925 } 4926 4927 /** 4928 * Set the scopes of a device owner or profile owner delegate. 4929 * 4930 * @param who the device owner or profile owner. 4931 * @param delegatePackage the name of the delegate package. 4932 * @param scopes the list of delegation scopes to be given to the delegate package. 4933 */ 4934 @Override 4935 public void setDelegatedScopes(ComponentName who, String delegatePackage, 4936 List<String> scopes) throws SecurityException { 4937 Preconditions.checkNotNull(who, "ComponentName is null"); 4938 Preconditions.checkStringNotEmpty(delegatePackage, "Delegate package is null or empty"); 4939 Preconditions.checkCollectionElementsNotNull(scopes, "Scopes"); 4940 // Remove possible duplicates. 4941 scopes = new ArrayList(new ArraySet(scopes)); 4942 // Ensure given scopes are valid. 4943 if (scopes.retainAll(Arrays.asList(DELEGATIONS))) { 4944 throw new IllegalArgumentException("Unexpected delegation scopes"); 4945 } 4946 4947 // Retrieve the user ID of the calling process. 4948 final int userId = mInjector.userHandleGetCallingUserId(); 4949 synchronized (this) { 4950 // Ensure calling process is device/profile owner. 4951 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 4952 // Ensure the delegate is installed (skip this for DELEGATION_CERT_INSTALL in pre-N). 4953 if (shouldCheckIfDelegatePackageIsInstalled(delegatePackage, 4954 getTargetSdk(who.getPackageName(), userId), scopes)) { 4955 // Throw when the delegate package is not installed. 4956 if (!isPackageInstalledForUser(delegatePackage, userId)) { 4957 throw new IllegalArgumentException("Package " + delegatePackage 4958 + " is not installed on the current user"); 4959 } 4960 } 4961 4962 // Set the new delegate in user policies. 4963 final DevicePolicyData policy = getUserData(userId); 4964 if (!scopes.isEmpty()) { 4965 policy.mDelegationMap.put(delegatePackage, new ArrayList<>(scopes)); 4966 } else { 4967 // Remove any delegation info if the given scopes list is empty. 4968 policy.mDelegationMap.remove(delegatePackage); 4969 } 4970 4971 // Notify delegate package of updates. 4972 final Intent intent = new Intent( 4973 DevicePolicyManager.ACTION_APPLICATION_DELEGATION_SCOPES_CHANGED); 4974 // Only call receivers registered with Context#registerReceiver (don’t wake delegate). 4975 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 4976 // Limit components this intent resolves to to the delegate package. 4977 intent.setPackage(delegatePackage); 4978 // Include the list of delegated scopes as an extra. 4979 intent.putStringArrayListExtra(DevicePolicyManager.EXTRA_DELEGATION_SCOPES, 4980 (ArrayList<String>) scopes); 4981 // Send the broadcast. 4982 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 4983 4984 // Persist updates. 4985 saveSettingsLocked(userId); 4986 } 4987 } 4988 4989 /** 4990 * Get the delegation scopes given to a delegate package by a device owner or profile owner. 4991 * 4992 * A DO/PO can get the scopes of any package. A non DO/PO package can get its own scopes by 4993 * passing in {@code null} as the {@code who} parameter and its own name as the 4994 * {@code delegatepackage}. 4995 * 4996 * @param who the device owner or profile owner, or {@code null} if the caller is 4997 * {@code delegatePackage}. 4998 * @param delegatePackage the name of the delegate package whose scopes are to be retrieved. 4999 * @return a list of the delegation scopes currently given to {@code delegatePackage}. 5000 */ 5001 @Override 5002 @NonNull 5003 public List<String> getDelegatedScopes(ComponentName who, 5004 String delegatePackage) throws SecurityException { 5005 Preconditions.checkNotNull(delegatePackage, "Delegate package is null"); 5006 5007 // Retrieve the user ID of the calling process. 5008 final int callingUid = mInjector.binderGetCallingUid(); 5009 final int userId = UserHandle.getUserId(callingUid); 5010 synchronized (this) { 5011 // Ensure calling process is device/profile owner. 5012 if (who != null) { 5013 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5014 // Or ensure calling process is delegatePackage itself. 5015 } else { 5016 int uid = 0; 5017 try { 5018 uid = mInjector.getPackageManager() 5019 .getPackageUidAsUser(delegatePackage, userId); 5020 } catch(NameNotFoundException e) { 5021 } 5022 if (uid != callingUid) { 5023 throw new SecurityException("Caller with uid " + callingUid + " is not " 5024 + delegatePackage); 5025 } 5026 } 5027 final DevicePolicyData policy = getUserData(userId); 5028 // Retrieve the scopes assigned to delegatePackage, or null if no scope was given. 5029 final List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5030 return scopes == null ? Collections.EMPTY_LIST : scopes; 5031 } 5032 } 5033 5034 /** 5035 * Get a list of packages that were given a specific delegation scopes by a device owner or 5036 * profile owner. 5037 * 5038 * @param who the device owner or profile owner. 5039 * @param scope the scope whose delegates are to be retrieved. 5040 * @return a list of the delegate packages currently given the {@code scope} delegation. 5041 */ 5042 @NonNull 5043 public List<String> getDelegatePackages(ComponentName who, String scope) 5044 throws SecurityException { 5045 Preconditions.checkNotNull(who, "ComponentName is null"); 5046 Preconditions.checkNotNull(scope, "Scope is null"); 5047 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5048 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5049 } 5050 5051 // Retrieve the user ID of the calling process. 5052 final int userId = mInjector.userHandleGetCallingUserId(); 5053 synchronized (this) { 5054 // Ensure calling process is device/profile owner. 5055 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5056 final DevicePolicyData policy = getUserData(userId); 5057 5058 // Create a list to hold the resulting delegate packages. 5059 final List<String> delegatePackagesWithScope = new ArrayList<>(); 5060 // Add all delegations containing scope to the result list. 5061 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5062 if (policy.mDelegationMap.valueAt(i).contains(scope)) { 5063 delegatePackagesWithScope.add(policy.mDelegationMap.keyAt(i)); 5064 } 5065 } 5066 return delegatePackagesWithScope; 5067 } 5068 } 5069 5070 /** 5071 * Check whether a caller application has been delegated a given scope via 5072 * {@link #setDelegatedScopes} to access privileged APIs on the behalf of a profile owner or 5073 * device owner. 5074 * <p> 5075 * This is done by checking that {@code callerPackage} was granted {@code scope} delegation and 5076 * then comparing the calling UID with the UID of {@code callerPackage} as reported by 5077 * {@link PackageManager#getPackageUidAsUser}. 5078 * 5079 * @param callerPackage the name of the package that is trying to invoke a function in the DPMS. 5080 * @param scope the delegation scope to be checked. 5081 * @return {@code true} if the calling process is a delegate of {@code scope}. 5082 */ 5083 private boolean isCallerDelegate(String callerPackage, String scope) { 5084 Preconditions.checkNotNull(callerPackage, "callerPackage is null"); 5085 if (!Arrays.asList(DELEGATIONS).contains(scope)) { 5086 throw new IllegalArgumentException("Unexpected delegation scope: " + scope); 5087 } 5088 5089 // Retrieve the UID and user ID of the calling process. 5090 final int callingUid = mInjector.binderGetCallingUid(); 5091 final int userId = UserHandle.getUserId(callingUid); 5092 synchronized (this) { 5093 // Retrieve user policy data. 5094 final DevicePolicyData policy = getUserData(userId); 5095 // Retrieve the list of delegation scopes granted to callerPackage. 5096 final List<String> scopes = policy.mDelegationMap.get(callerPackage); 5097 // Check callingUid only if callerPackage has the required scope delegation. 5098 if (scopes != null && scopes.contains(scope)) { 5099 try { 5100 // Retrieve the expected UID for callerPackage. 5101 final int uid = mInjector.getPackageManager() 5102 .getPackageUidAsUser(callerPackage, userId); 5103 // Return true if the caller is actually callerPackage. 5104 return uid == callingUid; 5105 } catch (NameNotFoundException e) { 5106 // Ignore. 5107 } 5108 } 5109 return false; 5110 } 5111 } 5112 5113 /** 5114 * Throw a security exception if a ComponentName is given and it is not a device/profile owner 5115 * or if the calling process is not a delegate of the given scope. 5116 * 5117 * @param who the device owner of profile owner, or null if {@code callerPackage} is a 5118 * {@code scope} delegate. 5119 * @param callerPackage the name of the calling package. Required if {@code who} is 5120 * {@code null}. 5121 * @param reqPolicy the policy used in the API whose access permission is being checked. 5122 * @param scope the delegation scope corresponding to the API being checked. 5123 * @throws SecurityException if {@code who} is given and is not an owner for {@code reqPolicy}; 5124 * or when {@code who} is {@code null} and {@code callerPackage} is not a delegate 5125 * of {@code scope}. 5126 */ 5127 private void enforceCanManageScope(ComponentName who, String callerPackage, int reqPolicy, 5128 String scope) { 5129 // If a ComponentName is given ensure it is a device or profile owner according to policy. 5130 if (who != null) { 5131 synchronized (this) { 5132 getActiveAdminForCallerLocked(who, reqPolicy); 5133 } 5134 // If no ComponentName is given ensure calling process has scope delegation. 5135 } else if (!isCallerDelegate(callerPackage, scope)) { 5136 throw new SecurityException("Caller with uid " + mInjector.binderGetCallingUid() 5137 + " is not a delegate of scope " + scope + "."); 5138 } 5139 } 5140 5141 /** 5142 * Helper function to preserve delegation behavior pre-O when using the deprecated functions 5143 * {@code #setCertInstallerPackage} and {@code #setApplicationRestrictionsManagingPackage}. 5144 */ 5145 private void setDelegatedScopePreO(ComponentName who, 5146 String delegatePackage, String scope) { 5147 Preconditions.checkNotNull(who, "ComponentName is null"); 5148 5149 final int userId = mInjector.userHandleGetCallingUserId(); 5150 synchronized(this) { 5151 // Ensure calling process is device/profile owner. 5152 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5153 final DevicePolicyData policy = getUserData(userId); 5154 5155 if (delegatePackage != null) { 5156 // Set package as a delegate for scope if it is not already one. 5157 List<String> scopes = policy.mDelegationMap.get(delegatePackage); 5158 if (scopes == null) { 5159 scopes = new ArrayList<>(); 5160 } 5161 if (!scopes.contains(scope)) { 5162 scopes.add(scope); 5163 setDelegatedScopes(who, delegatePackage, scopes); 5164 } 5165 } 5166 5167 // Clear any existing scope delegates. 5168 for (int i = 0; i < policy.mDelegationMap.size(); i++) { 5169 final String currentPackage = policy.mDelegationMap.keyAt(i); 5170 final List<String> currentScopes = policy.mDelegationMap.valueAt(i); 5171 5172 if (!currentPackage.equals(delegatePackage) && currentScopes.contains(scope)) { 5173 final List<String> newScopes = new ArrayList(currentScopes); 5174 newScopes.remove(scope); 5175 setDelegatedScopes(who, currentPackage, newScopes); 5176 } 5177 } 5178 } 5179 } 5180 5181 @Override 5182 public void setCertInstallerPackage(ComponentName who, String installerPackage) 5183 throws SecurityException { 5184 setDelegatedScopePreO(who, installerPackage, DELEGATION_CERT_INSTALL); 5185 } 5186 5187 @Override 5188 public String getCertInstallerPackage(ComponentName who) throws SecurityException { 5189 final List<String> delegatePackages = getDelegatePackages(who, DELEGATION_CERT_INSTALL); 5190 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 5191 } 5192 5193 /** 5194 * @return {@code true} if the package is installed and set as always-on, {@code false} if it is 5195 * not installed and therefore not available. 5196 * 5197 * @throws SecurityException if the caller is not a profile or device owner. 5198 * @throws UnsupportedOperationException if the package does not support being set as always-on. 5199 */ 5200 @Override 5201 public boolean setAlwaysOnVpnPackage(ComponentName admin, String vpnPackage, boolean lockdown) 5202 throws SecurityException { 5203 enforceProfileOrDeviceOwner(admin); 5204 5205 final int userId = mInjector.userHandleGetCallingUserId(); 5206 final long token = mInjector.binderClearCallingIdentity(); 5207 try { 5208 if (vpnPackage != null && !isPackageInstalledForUser(vpnPackage, userId)) { 5209 return false; 5210 } 5211 ConnectivityManager connectivityManager = (ConnectivityManager) 5212 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5213 if (!connectivityManager.setAlwaysOnVpnPackageForUser(userId, vpnPackage, lockdown)) { 5214 throw new UnsupportedOperationException(); 5215 } 5216 } finally { 5217 mInjector.binderRestoreCallingIdentity(token); 5218 } 5219 return true; 5220 } 5221 5222 @Override 5223 public String getAlwaysOnVpnPackage(ComponentName admin) 5224 throws SecurityException { 5225 enforceProfileOrDeviceOwner(admin); 5226 5227 final int userId = mInjector.userHandleGetCallingUserId(); 5228 final long token = mInjector.binderClearCallingIdentity(); 5229 try{ 5230 ConnectivityManager connectivityManager = (ConnectivityManager) 5231 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5232 return connectivityManager.getAlwaysOnVpnPackageForUser(userId); 5233 } finally { 5234 mInjector.binderRestoreCallingIdentity(token); 5235 } 5236 } 5237 5238 private void forceWipeDeviceNoLock(boolean wipeExtRequested, String reason) { 5239 wtfIfInLock(); 5240 5241 if (wipeExtRequested) { 5242 StorageManager sm = (StorageManager) mContext.getSystemService( 5243 Context.STORAGE_SERVICE); 5244 sm.wipeAdoptableDisks(); 5245 } 5246 try { 5247 mInjector.recoverySystemRebootWipeUserData( 5248 /*shutdown=*/ false, reason, /*force=*/ true); 5249 } catch (IOException | SecurityException e) { 5250 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 5251 } 5252 } 5253 5254 private void forceWipeUser(int userId) { 5255 try { 5256 IActivityManager am = mInjector.getIActivityManager(); 5257 if (am.getCurrentUser().id == userId) { 5258 am.switchUser(UserHandle.USER_SYSTEM); 5259 } 5260 5261 boolean userRemoved = mUserManagerInternal.removeUserEvenWhenDisallowed(userId); 5262 if (!userRemoved) { 5263 Slog.w(LOG_TAG, "Couldn't remove user " + userId); 5264 } else if (isManagedProfile(userId)) { 5265 sendWipeProfileNotification(); 5266 } 5267 } catch (RemoteException re) { 5268 // Shouldn't happen 5269 } 5270 } 5271 5272 @Override 5273 public void wipeData(int flags) { 5274 if (!mHasFeature) { 5275 return; 5276 } 5277 enforceFullCrossUsersPermission(mInjector.userHandleGetCallingUserId()); 5278 5279 final ActiveAdmin admin; 5280 synchronized (this) { 5281 admin = getActiveAdminForCallerLocked(null, DeviceAdminInfo.USES_POLICY_WIPE_DATA); 5282 } 5283 String reason = "DevicePolicyManager.wipeData() from " 5284 + admin.info.getComponent().flattenToShortString(); 5285 wipeDataNoLock( 5286 admin.info.getComponent(), flags, reason, admin.getUserHandle().getIdentifier()); 5287 } 5288 5289 private void wipeDataNoLock(ComponentName admin, int flags, String reason, int userId) { 5290 wtfIfInLock(); 5291 5292 long ident = mInjector.binderClearCallingIdentity(); 5293 try { 5294 // First check whether the admin is allowed to wipe the device/user/profile. 5295 final String restriction; 5296 if (userId == UserHandle.USER_SYSTEM) { 5297 restriction = UserManager.DISALLOW_FACTORY_RESET; 5298 } else if (isManagedProfile(userId)) { 5299 restriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE; 5300 } else { 5301 restriction = UserManager.DISALLOW_REMOVE_USER; 5302 } 5303 if (isAdminAffectedByRestriction(admin, restriction, userId)) { 5304 throw new SecurityException("Cannot wipe data. " + restriction 5305 + " restriction is set for user " + userId); 5306 } 5307 5308 if ((flags & WIPE_RESET_PROTECTION_DATA) != 0) { 5309 if (!isDeviceOwner(admin, userId)) { 5310 throw new SecurityException( 5311 "Only device owner admins can set WIPE_RESET_PROTECTION_DATA"); 5312 } 5313 PersistentDataBlockManager manager = (PersistentDataBlockManager) 5314 mContext.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 5315 if (manager != null) { 5316 manager.wipe(); 5317 } 5318 } 5319 5320 // TODO If split user is enabled and the device owner is set in the primary user 5321 // (rather than system), we should probably trigger factory reset. Current code just 5322 // removes that user (but still clears FRP...) 5323 if (userId == UserHandle.USER_SYSTEM) { 5324 forceWipeDeviceNoLock(/*wipeExtRequested=*/ (flags & WIPE_EXTERNAL_STORAGE) != 0, 5325 reason); 5326 } else { 5327 forceWipeUser(userId); 5328 } 5329 } finally { 5330 mInjector.binderRestoreCallingIdentity(ident); 5331 } 5332 } 5333 5334 private void sendWipeProfileNotification() { 5335 String contentText = mContext.getString(R.string.work_profile_deleted_description_dpm_wipe); 5336 Notification notification = 5337 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 5338 .setSmallIcon(android.R.drawable.stat_sys_warning) 5339 .setContentTitle(mContext.getString(R.string.work_profile_deleted)) 5340 .setContentText(contentText) 5341 .setColor(mContext.getColor(R.color.system_notification_accent_color)) 5342 .setStyle(new Notification.BigTextStyle().bigText(contentText)) 5343 .build(); 5344 mInjector.getNotificationManager().notify(SystemMessage.NOTE_PROFILE_WIPED, notification); 5345 } 5346 5347 private void clearWipeProfileNotification() { 5348 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_PROFILE_WIPED); 5349 } 5350 5351 @Override 5352 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 5353 if (!mHasFeature) { 5354 return; 5355 } 5356 enforceFullCrossUsersPermission(userHandle); 5357 mContext.enforceCallingOrSelfPermission( 5358 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5359 5360 synchronized (this) { 5361 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 5362 if (admin == null) { 5363 result.sendResult(null); 5364 return; 5365 } 5366 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 5367 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 5368 intent.setComponent(admin.info.getComponent()); 5369 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 5370 null, new BroadcastReceiver() { 5371 @Override 5372 public void onReceive(Context context, Intent intent) { 5373 result.sendResult(getResultExtras(false)); 5374 } 5375 }, null, Activity.RESULT_OK, null, null); 5376 } 5377 } 5378 5379 @Override 5380 public void setActivePasswordState(PasswordMetrics metrics, int userHandle) { 5381 if (!mHasFeature) { 5382 return; 5383 } 5384 enforceFullCrossUsersPermission(userHandle); 5385 mContext.enforceCallingOrSelfPermission( 5386 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5387 5388 // If the managed profile doesn't have a separate password, set the metrics to default 5389 if (isManagedProfile(userHandle) && !isSeparateProfileChallengeEnabled(userHandle)) { 5390 metrics = new PasswordMetrics(); 5391 } 5392 5393 validateQualityConstant(metrics.quality); 5394 DevicePolicyData policy = getUserData(userHandle); 5395 synchronized (this) { 5396 policy.mActivePasswordMetrics = metrics; 5397 } 5398 } 5399 5400 @Override 5401 public void reportPasswordChanged(@UserIdInt int userId) { 5402 if (!mHasFeature) { 5403 return; 5404 } 5405 enforceFullCrossUsersPermission(userId); 5406 5407 // Managed Profile password can only be changed when it has a separate challenge. 5408 if (!isSeparateProfileChallengeEnabled(userId)) { 5409 enforceNotManagedProfile(userId, "set the active password"); 5410 } 5411 5412 mContext.enforceCallingOrSelfPermission( 5413 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5414 5415 DevicePolicyData policy = getUserData(userId); 5416 5417 long ident = mInjector.binderClearCallingIdentity(); 5418 try { 5419 synchronized (this) { 5420 policy.mFailedPasswordAttempts = 0; 5421 saveSettingsLocked(userId); 5422 updatePasswordExpirationsLocked(userId); 5423 setExpirationAlarmCheckLocked(mContext, userId, /* parent */ false); 5424 5425 // Send a broadcast to each profile using this password as its primary unlock. 5426 sendAdminCommandForLockscreenPoliciesLocked( 5427 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 5428 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userId); 5429 } 5430 removeCaApprovalsIfNeeded(userId); 5431 } finally { 5432 mInjector.binderRestoreCallingIdentity(ident); 5433 } 5434 } 5435 5436 /** 5437 * Called any time the device password is updated. Resets all password expiration clocks. 5438 */ 5439 private void updatePasswordExpirationsLocked(int userHandle) { 5440 ArraySet<Integer> affectedUserIds = new ArraySet<Integer>(); 5441 List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked( 5442 userHandle, /* parent */ false); 5443 final int N = admins.size(); 5444 for (int i = 0; i < N; i++) { 5445 ActiveAdmin admin = admins.get(i); 5446 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 5447 affectedUserIds.add(admin.getUserHandle().getIdentifier()); 5448 long timeout = admin.passwordExpirationTimeout; 5449 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 5450 admin.passwordExpirationDate = expiration; 5451 } 5452 } 5453 for (int affectedUserId : affectedUserIds) { 5454 saveSettingsLocked(affectedUserId); 5455 } 5456 } 5457 5458 @Override 5459 public void reportFailedPasswordAttempt(int userHandle) { 5460 enforceFullCrossUsersPermission(userHandle); 5461 if (!isSeparateProfileChallengeEnabled(userHandle)) { 5462 enforceNotManagedProfile(userHandle, 5463 "report failed password attempt if separate profile challenge is not in place"); 5464 } 5465 mContext.enforceCallingOrSelfPermission( 5466 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5467 5468 boolean wipeData = false; 5469 ActiveAdmin strictestAdmin = null; 5470 final long ident = mInjector.binderClearCallingIdentity(); 5471 try { 5472 synchronized (this) { 5473 DevicePolicyData policy = getUserData(userHandle); 5474 policy.mFailedPasswordAttempts++; 5475 saveSettingsLocked(userHandle); 5476 if (mHasFeature) { 5477 strictestAdmin = getAdminWithMinimumFailedPasswordsForWipeLocked( 5478 userHandle, /* parent */ false); 5479 int max = strictestAdmin != null 5480 ? strictestAdmin.maximumFailedPasswordsForWipe : 0; 5481 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 5482 wipeData = true; 5483 } 5484 5485 sendAdminCommandForLockscreenPoliciesLocked( 5486 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 5487 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5488 } 5489 } 5490 } finally { 5491 mInjector.binderRestoreCallingIdentity(ident); 5492 } 5493 5494 if (wipeData && strictestAdmin != null) { 5495 final int userId = strictestAdmin.getUserHandle().getIdentifier(); 5496 Slog.i(LOG_TAG, "Max failed password attempts policy reached for admin: " 5497 + strictestAdmin.info.getComponent().flattenToShortString() 5498 + ". Calling wipeData for user " + userId); 5499 5500 // Attempt to wipe the device/user/profile associated with the admin, as if the 5501 // admin had called wipeData(). That way we can check whether the admin is actually 5502 // allowed to wipe the device (e.g. a regular device admin shouldn't be able to wipe the 5503 // device if the device owner has set DISALLOW_FACTORY_RESET, but the DO should be 5504 // able to do so). 5505 // IMPORTANT: Call without holding the lock to prevent deadlock. 5506 try { 5507 wipeDataNoLock(strictestAdmin.info.getComponent(), 5508 /*flags=*/ 0, 5509 /*reason=*/ "reportFailedPasswordAttempt()", 5510 userId); 5511 } catch (SecurityException e) { 5512 Slog.w(LOG_TAG, "Failed to wipe user " + userId 5513 + " after max failed password attempts reached.", e); 5514 } 5515 } 5516 5517 if (mInjector.securityLogIsLoggingEnabled()) { 5518 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5519 /*method strength*/ 1); 5520 } 5521 } 5522 5523 @Override 5524 public void reportSuccessfulPasswordAttempt(int userHandle) { 5525 enforceFullCrossUsersPermission(userHandle); 5526 mContext.enforceCallingOrSelfPermission( 5527 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5528 5529 synchronized (this) { 5530 DevicePolicyData policy = getUserData(userHandle); 5531 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 5532 long ident = mInjector.binderClearCallingIdentity(); 5533 try { 5534 policy.mFailedPasswordAttempts = 0; 5535 policy.mPasswordOwner = -1; 5536 saveSettingsLocked(userHandle); 5537 if (mHasFeature) { 5538 sendAdminCommandForLockscreenPoliciesLocked( 5539 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 5540 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 5541 } 5542 } finally { 5543 mInjector.binderRestoreCallingIdentity(ident); 5544 } 5545 } 5546 } 5547 5548 if (mInjector.securityLogIsLoggingEnabled()) { 5549 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5550 /*method strength*/ 1); 5551 } 5552 } 5553 5554 @Override 5555 public void reportFailedFingerprintAttempt(int userHandle) { 5556 enforceFullCrossUsersPermission(userHandle); 5557 mContext.enforceCallingOrSelfPermission( 5558 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5559 if (mInjector.securityLogIsLoggingEnabled()) { 5560 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 0, 5561 /*method strength*/ 0); 5562 } 5563 } 5564 5565 @Override 5566 public void reportSuccessfulFingerprintAttempt(int userHandle) { 5567 enforceFullCrossUsersPermission(userHandle); 5568 mContext.enforceCallingOrSelfPermission( 5569 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5570 if (mInjector.securityLogIsLoggingEnabled()) { 5571 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT, /*result*/ 1, 5572 /*method strength*/ 0); 5573 } 5574 } 5575 5576 @Override 5577 public void reportKeyguardDismissed(int userHandle) { 5578 enforceFullCrossUsersPermission(userHandle); 5579 mContext.enforceCallingOrSelfPermission( 5580 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5581 5582 if (mInjector.securityLogIsLoggingEnabled()) { 5583 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_DISMISSED); 5584 } 5585 } 5586 5587 @Override 5588 public void reportKeyguardSecured(int userHandle) { 5589 enforceFullCrossUsersPermission(userHandle); 5590 mContext.enforceCallingOrSelfPermission( 5591 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 5592 5593 if (mInjector.securityLogIsLoggingEnabled()) { 5594 SecurityLog.writeEvent(SecurityLog.TAG_KEYGUARD_SECURED); 5595 } 5596 } 5597 5598 @Override 5599 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 5600 String exclusionList) { 5601 if (!mHasFeature) { 5602 return null; 5603 } 5604 synchronized(this) { 5605 Preconditions.checkNotNull(who, "ComponentName is null"); 5606 5607 // Only check if system user has set global proxy. We don't allow other users to set it. 5608 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5609 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5610 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 5611 5612 // Scan through active admins and find if anyone has already 5613 // set the global proxy. 5614 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 5615 for (ComponentName component : compSet) { 5616 ActiveAdmin ap = policy.mAdminMap.get(component); 5617 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 5618 // Another admin already sets the global proxy 5619 // Return it to the caller. 5620 return component; 5621 } 5622 } 5623 5624 // If the user is not system, don't set the global proxy. Fail silently. 5625 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 5626 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 5627 + UserHandle.getCallingUserId() + " is not permitted."); 5628 return null; 5629 } 5630 if (proxySpec == null) { 5631 admin.specifiesGlobalProxy = false; 5632 admin.globalProxySpec = null; 5633 admin.globalProxyExclusionList = null; 5634 } else { 5635 5636 admin.specifiesGlobalProxy = true; 5637 admin.globalProxySpec = proxySpec; 5638 admin.globalProxyExclusionList = exclusionList; 5639 } 5640 5641 // Reset the global proxy accordingly 5642 // Do this using system permissions, as apps cannot write to secure settings 5643 long origId = mInjector.binderClearCallingIdentity(); 5644 try { 5645 resetGlobalProxyLocked(policy); 5646 } finally { 5647 mInjector.binderRestoreCallingIdentity(origId); 5648 } 5649 return null; 5650 } 5651 } 5652 5653 @Override 5654 public ComponentName getGlobalProxyAdmin(int userHandle) { 5655 if (!mHasFeature) { 5656 return null; 5657 } 5658 enforceFullCrossUsersPermission(userHandle); 5659 synchronized(this) { 5660 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5661 // Scan through active admins and find if anyone has already 5662 // set the global proxy. 5663 final int N = policy.mAdminList.size(); 5664 for (int i = 0; i < N; i++) { 5665 ActiveAdmin ap = policy.mAdminList.get(i); 5666 if (ap.specifiesGlobalProxy) { 5667 // Device admin sets the global proxy 5668 // Return it to the caller. 5669 return ap.info.getComponent(); 5670 } 5671 } 5672 } 5673 // No device admin sets the global proxy. 5674 return null; 5675 } 5676 5677 @Override 5678 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 5679 synchronized (this) { 5680 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 5681 } 5682 long token = mInjector.binderClearCallingIdentity(); 5683 try { 5684 ConnectivityManager connectivityManager = (ConnectivityManager) 5685 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 5686 connectivityManager.setGlobalProxy(proxyInfo); 5687 } finally { 5688 mInjector.binderRestoreCallingIdentity(token); 5689 } 5690 } 5691 5692 private void resetGlobalProxyLocked(DevicePolicyData policy) { 5693 final int N = policy.mAdminList.size(); 5694 for (int i = 0; i < N; i++) { 5695 ActiveAdmin ap = policy.mAdminList.get(i); 5696 if (ap.specifiesGlobalProxy) { 5697 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 5698 return; 5699 } 5700 } 5701 // No device admins defining global proxies - reset global proxy settings to none 5702 saveGlobalProxyLocked(null, null); 5703 } 5704 5705 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 5706 if (exclusionList == null) { 5707 exclusionList = ""; 5708 } 5709 if (proxySpec == null) { 5710 proxySpec = ""; 5711 } 5712 // Remove white spaces 5713 proxySpec = proxySpec.trim(); 5714 String data[] = proxySpec.split(":"); 5715 int proxyPort = 8080; 5716 if (data.length > 1) { 5717 try { 5718 proxyPort = Integer.parseInt(data[1]); 5719 } catch (NumberFormatException e) {} 5720 } 5721 exclusionList = exclusionList.trim(); 5722 5723 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 5724 if (!proxyProperties.isValid()) { 5725 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 5726 return; 5727 } 5728 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 5729 mInjector.settingsGlobalPutInt(Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 5730 mInjector.settingsGlobalPutString(Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 5731 exclusionList); 5732 } 5733 5734 /** 5735 * Set the storage encryption request for a single admin. Returns the new total request 5736 * status (for all admins). 5737 */ 5738 @Override 5739 public int setStorageEncryption(ComponentName who, boolean encrypt) { 5740 if (!mHasFeature) { 5741 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5742 } 5743 Preconditions.checkNotNull(who, "ComponentName is null"); 5744 final int userHandle = UserHandle.getCallingUserId(); 5745 synchronized (this) { 5746 // Check for permissions 5747 // Only system user can set storage encryption 5748 if (userHandle != UserHandle.USER_SYSTEM) { 5749 Slog.w(LOG_TAG, "Only owner/system user is allowed to set storage encryption. User " 5750 + UserHandle.getCallingUserId() + " is not permitted."); 5751 return 0; 5752 } 5753 5754 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5755 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 5756 5757 // Quick exit: If the filesystem does not support encryption, we can exit early. 5758 if (!isEncryptionSupported()) { 5759 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5760 } 5761 5762 // (1) Record the value for the admin so it's sticky 5763 if (ap.encryptionRequested != encrypt) { 5764 ap.encryptionRequested = encrypt; 5765 saveSettingsLocked(userHandle); 5766 } 5767 5768 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 5769 // (2) Compute "max" for all admins 5770 boolean newRequested = false; 5771 final int N = policy.mAdminList.size(); 5772 for (int i = 0; i < N; i++) { 5773 newRequested |= policy.mAdminList.get(i).encryptionRequested; 5774 } 5775 5776 // Notify OS of new request 5777 setEncryptionRequested(newRequested); 5778 5779 // Return the new global request status 5780 return newRequested 5781 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 5782 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5783 } 5784 } 5785 5786 /** 5787 * Get the current storage encryption request status for a given admin, or aggregate of all 5788 * active admins. 5789 */ 5790 @Override 5791 public boolean getStorageEncryption(ComponentName who, int userHandle) { 5792 if (!mHasFeature) { 5793 return false; 5794 } 5795 enforceFullCrossUsersPermission(userHandle); 5796 synchronized (this) { 5797 // Check for permissions if a particular caller is specified 5798 if (who != null) { 5799 // When checking for a single caller, status is based on caller's request 5800 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 5801 return ap != null ? ap.encryptionRequested : false; 5802 } 5803 5804 // If no particular caller is specified, return the aggregate set of requests. 5805 // This is short circuited by returning true on the first hit. 5806 DevicePolicyData policy = getUserData(userHandle); 5807 final int N = policy.mAdminList.size(); 5808 for (int i = 0; i < N; i++) { 5809 if (policy.mAdminList.get(i).encryptionRequested) { 5810 return true; 5811 } 5812 } 5813 return false; 5814 } 5815 } 5816 5817 /** 5818 * Get the current encryption status of the device. 5819 */ 5820 @Override 5821 public int getStorageEncryptionStatus(@Nullable String callerPackage, int userHandle) { 5822 if (!mHasFeature) { 5823 // Ok to return current status. 5824 } 5825 enforceFullCrossUsersPermission(userHandle); 5826 5827 // It's not critical here, but let's make sure the package name is correct, in case 5828 // we start using it for different purposes. 5829 ensureCallerPackage(callerPackage); 5830 5831 final ApplicationInfo ai; 5832 try { 5833 ai = mIPackageManager.getApplicationInfo(callerPackage, 0, userHandle); 5834 } catch (RemoteException e) { 5835 throw new SecurityException(e); 5836 } 5837 5838 boolean legacyApp = false; 5839 if (ai.targetSdkVersion <= Build.VERSION_CODES.M) { 5840 legacyApp = true; 5841 } 5842 5843 final int rawStatus = getEncryptionStatus(); 5844 if ((rawStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER) && legacyApp) { 5845 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5846 } 5847 return rawStatus; 5848 } 5849 5850 /** 5851 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 5852 */ 5853 private boolean isEncryptionSupported() { 5854 // Note, this can be implemented as 5855 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5856 // But is provided as a separate internal method if there's a faster way to do a 5857 // simple check for supported-or-not. 5858 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5859 } 5860 5861 /** 5862 * Hook to low-levels: Reporting the current status of encryption. 5863 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED}, 5864 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE}, 5865 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY}, 5866 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE_PER_USER}, or 5867 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 5868 */ 5869 private int getEncryptionStatus() { 5870 if (mInjector.storageManagerIsFileBasedEncryptionEnabled()) { 5871 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER; 5872 } else if (mInjector.storageManagerIsNonDefaultBlockEncrypted()) { 5873 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 5874 } else if (mInjector.storageManagerIsEncrypted()) { 5875 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY; 5876 } else if (mInjector.storageManagerIsEncryptable()) { 5877 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 5878 } else { 5879 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 5880 } 5881 } 5882 5883 /** 5884 * Hook to low-levels: If needed, record the new admin setting for encryption. 5885 */ 5886 private void setEncryptionRequested(boolean encrypt) { 5887 } 5888 5889 /** 5890 * Set whether the screen capture is disabled for the user managed by the specified admin. 5891 */ 5892 @Override 5893 public void setScreenCaptureDisabled(ComponentName who, boolean disabled) { 5894 if (!mHasFeature) { 5895 return; 5896 } 5897 Preconditions.checkNotNull(who, "ComponentName is null"); 5898 final int userHandle = UserHandle.getCallingUserId(); 5899 synchronized (this) { 5900 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 5901 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5902 if (ap.disableScreenCapture != disabled) { 5903 ap.disableScreenCapture = disabled; 5904 saveSettingsLocked(userHandle); 5905 updateScreenCaptureDisabledInWindowManager(userHandle, disabled); 5906 } 5907 } 5908 } 5909 5910 /** 5911 * Returns whether or not screen capture is disabled for a given admin, or disabled for any 5912 * active admin (if given admin is null). 5913 */ 5914 @Override 5915 public boolean getScreenCaptureDisabled(ComponentName who, int userHandle) { 5916 if (!mHasFeature) { 5917 return false; 5918 } 5919 synchronized (this) { 5920 if (who != null) { 5921 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 5922 return (admin != null) ? admin.disableScreenCapture : false; 5923 } 5924 5925 DevicePolicyData policy = getUserData(userHandle); 5926 final int N = policy.mAdminList.size(); 5927 for (int i = 0; i < N; i++) { 5928 ActiveAdmin admin = policy.mAdminList.get(i); 5929 if (admin.disableScreenCapture) { 5930 return true; 5931 } 5932 } 5933 return false; 5934 } 5935 } 5936 5937 private void updateScreenCaptureDisabledInWindowManager(final int userHandle, 5938 final boolean disabled) { 5939 mHandler.post(new Runnable() { 5940 @Override 5941 public void run() { 5942 try { 5943 mInjector.getIWindowManager().setScreenCaptureDisabled(userHandle, disabled); 5944 } catch (RemoteException e) { 5945 Log.w(LOG_TAG, "Unable to notify WindowManager.", e); 5946 } 5947 } 5948 }); 5949 } 5950 5951 /** 5952 * Set whether auto time is required by the specified admin (must be device or profile owner). 5953 */ 5954 @Override 5955 public void setAutoTimeRequired(ComponentName who, boolean required) { 5956 if (!mHasFeature) { 5957 return; 5958 } 5959 Preconditions.checkNotNull(who, "ComponentName is null"); 5960 final int userHandle = UserHandle.getCallingUserId(); 5961 synchronized (this) { 5962 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 5963 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 5964 if (admin.requireAutoTime != required) { 5965 admin.requireAutoTime = required; 5966 saveSettingsLocked(userHandle); 5967 } 5968 } 5969 5970 // Turn AUTO_TIME on in settings if it is required 5971 if (required) { 5972 long ident = mInjector.binderClearCallingIdentity(); 5973 try { 5974 mInjector.settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1 /* AUTO_TIME on */); 5975 } finally { 5976 mInjector.binderRestoreCallingIdentity(ident); 5977 } 5978 } 5979 } 5980 5981 /** 5982 * Returns whether or not auto time is required by the device owner or any profile owner. 5983 */ 5984 @Override 5985 public boolean getAutoTimeRequired() { 5986 if (!mHasFeature) { 5987 return false; 5988 } 5989 synchronized (this) { 5990 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 5991 if (deviceOwner != null && deviceOwner.requireAutoTime) { 5992 // If the device owner enforces auto time, we don't need to check the PO's 5993 return true; 5994 } 5995 5996 // Now check to see if any profile owner on any user enforces auto time 5997 for (Integer userId : mOwners.getProfileOwnerKeys()) { 5998 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 5999 if (profileOwner != null && profileOwner.requireAutoTime) { 6000 return true; 6001 } 6002 } 6003 6004 return false; 6005 } 6006 } 6007 6008 @Override 6009 public void setForceEphemeralUsers(ComponentName who, boolean forceEphemeralUsers) { 6010 if (!mHasFeature) { 6011 return; 6012 } 6013 Preconditions.checkNotNull(who, "ComponentName is null"); 6014 // Allow setting this policy to true only if there is a split system user. 6015 if (forceEphemeralUsers && !mInjector.userManagerIsSplitSystemUser()) { 6016 throw new UnsupportedOperationException( 6017 "Cannot force ephemeral users on systems without split system user."); 6018 } 6019 boolean removeAllUsers = false; 6020 synchronized (this) { 6021 final ActiveAdmin deviceOwner = 6022 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6023 if (deviceOwner.forceEphemeralUsers != forceEphemeralUsers) { 6024 deviceOwner.forceEphemeralUsers = forceEphemeralUsers; 6025 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 6026 mUserManagerInternal.setForceEphemeralUsers(forceEphemeralUsers); 6027 removeAllUsers = forceEphemeralUsers; 6028 } 6029 } 6030 if (removeAllUsers) { 6031 long identitity = mInjector.binderClearCallingIdentity(); 6032 try { 6033 mUserManagerInternal.removeAllUsers(); 6034 } finally { 6035 mInjector.binderRestoreCallingIdentity(identitity); 6036 } 6037 } 6038 } 6039 6040 @Override 6041 public boolean getForceEphemeralUsers(ComponentName who) { 6042 if (!mHasFeature) { 6043 return false; 6044 } 6045 Preconditions.checkNotNull(who, "ComponentName is null"); 6046 synchronized (this) { 6047 final ActiveAdmin deviceOwner = 6048 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6049 return deviceOwner.forceEphemeralUsers; 6050 } 6051 } 6052 6053 private void ensureDeviceOwnerAndAllUsersAffiliated(ComponentName who) throws SecurityException { 6054 synchronized (this) { 6055 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6056 if (!areAllUsersAffiliatedWithDeviceLocked()) { 6057 throw new SecurityException("Not all users are affiliated."); 6058 } 6059 } 6060 } 6061 6062 @Override 6063 public boolean requestBugreport(ComponentName who) { 6064 if (!mHasFeature) { 6065 return false; 6066 } 6067 Preconditions.checkNotNull(who, "ComponentName is null"); 6068 6069 // TODO: If an unaffiliated user is removed, the admin will be able to request a bugreport 6070 // which could still contain data related to that user. Should we disallow that, e.g. until 6071 // next boot? Might not be needed given that this still requires user consent. 6072 ensureDeviceOwnerAndAllUsersAffiliated(who); 6073 6074 if (mRemoteBugreportServiceIsActive.get() 6075 || (getDeviceOwnerRemoteBugreportUri() != null)) { 6076 Slog.d(LOG_TAG, "Remote bugreport wasn't started because there's already one running."); 6077 return false; 6078 } 6079 6080 final long currentTime = System.currentTimeMillis(); 6081 synchronized (this) { 6082 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 6083 if (currentTime > policyData.mLastBugReportRequestTime) { 6084 policyData.mLastBugReportRequestTime = currentTime; 6085 saveSettingsLocked(UserHandle.USER_SYSTEM); 6086 } 6087 } 6088 6089 final long callingIdentity = mInjector.binderClearCallingIdentity(); 6090 try { 6091 mInjector.getIActivityManager().requestBugReport( 6092 ActivityManager.BUGREPORT_OPTION_REMOTE); 6093 6094 mRemoteBugreportServiceIsActive.set(true); 6095 mRemoteBugreportSharingAccepted.set(false); 6096 registerRemoteBugreportReceivers(); 6097 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, 6098 RemoteBugreportUtils.NOTIFICATION_ID, 6099 RemoteBugreportUtils.buildNotification(mContext, 6100 DevicePolicyManager.NOTIFICATION_BUGREPORT_STARTED), UserHandle.ALL); 6101 mHandler.postDelayed(mRemoteBugreportTimeoutRunnable, 6102 RemoteBugreportUtils.REMOTE_BUGREPORT_TIMEOUT_MILLIS); 6103 return true; 6104 } catch (RemoteException re) { 6105 // should never happen 6106 Slog.e(LOG_TAG, "Failed to make remote calls to start bugreportremote service", re); 6107 return false; 6108 } finally { 6109 mInjector.binderRestoreCallingIdentity(callingIdentity); 6110 } 6111 } 6112 6113 synchronized void sendDeviceOwnerCommand(String action, Bundle extras) { 6114 Intent intent = new Intent(action); 6115 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6116 if (extras != null) { 6117 intent.putExtras(extras); 6118 } 6119 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6120 } 6121 6122 private synchronized String getDeviceOwnerRemoteBugreportUri() { 6123 return mOwners.getDeviceOwnerRemoteBugreportUri(); 6124 } 6125 6126 private synchronized void setDeviceOwnerRemoteBugreportUriAndHash(String bugreportUri, 6127 String bugreportHash) { 6128 mOwners.setDeviceOwnerRemoteBugreportUriAndHash(bugreportUri, bugreportHash); 6129 } 6130 6131 private void registerRemoteBugreportReceivers() { 6132 try { 6133 IntentFilter filterFinished = new IntentFilter( 6134 DevicePolicyManager.ACTION_REMOTE_BUGREPORT_DISPATCH, 6135 RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6136 mContext.registerReceiver(mRemoteBugreportFinishedReceiver, filterFinished); 6137 } catch (IntentFilter.MalformedMimeTypeException e) { 6138 // should never happen, as setting a constant 6139 Slog.w(LOG_TAG, "Failed to set type " + RemoteBugreportUtils.BUGREPORT_MIMETYPE, e); 6140 } 6141 IntentFilter filterConsent = new IntentFilter(); 6142 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_DECLINED); 6143 filterConsent.addAction(DevicePolicyManager.ACTION_BUGREPORT_SHARING_ACCEPTED); 6144 mContext.registerReceiver(mRemoteBugreportConsentReceiver, filterConsent); 6145 } 6146 6147 private void onBugreportFinished(Intent intent) { 6148 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6149 mRemoteBugreportServiceIsActive.set(false); 6150 Uri bugreportUri = intent.getData(); 6151 String bugreportUriString = null; 6152 if (bugreportUri != null) { 6153 bugreportUriString = bugreportUri.toString(); 6154 } 6155 String bugreportHash = intent.getStringExtra( 6156 DevicePolicyManager.EXTRA_REMOTE_BUGREPORT_HASH); 6157 if (mRemoteBugreportSharingAccepted.get()) { 6158 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6159 mInjector.getNotificationManager().cancel(LOG_TAG, 6160 RemoteBugreportUtils.NOTIFICATION_ID); 6161 } else { 6162 setDeviceOwnerRemoteBugreportUriAndHash(bugreportUriString, bugreportHash); 6163 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6164 RemoteBugreportUtils.buildNotification(mContext, 6165 DevicePolicyManager.NOTIFICATION_BUGREPORT_FINISHED_NOT_ACCEPTED), 6166 UserHandle.ALL); 6167 } 6168 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6169 } 6170 6171 private void onBugreportFailed() { 6172 mRemoteBugreportServiceIsActive.set(false); 6173 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6174 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6175 mRemoteBugreportSharingAccepted.set(false); 6176 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6177 mInjector.getNotificationManager().cancel(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID); 6178 Bundle extras = new Bundle(); 6179 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6180 DeviceAdminReceiver.BUGREPORT_FAILURE_FAILED_COMPLETING); 6181 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6182 mContext.unregisterReceiver(mRemoteBugreportConsentReceiver); 6183 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6184 } 6185 6186 private void onBugreportSharingAccepted() { 6187 mRemoteBugreportSharingAccepted.set(true); 6188 String bugreportUriString = null; 6189 String bugreportHash = null; 6190 synchronized (this) { 6191 bugreportUriString = getDeviceOwnerRemoteBugreportUri(); 6192 bugreportHash = mOwners.getDeviceOwnerRemoteBugreportHash(); 6193 } 6194 if (bugreportUriString != null) { 6195 shareBugreportWithDeviceOwnerIfExists(bugreportUriString, bugreportHash); 6196 } else if (mRemoteBugreportServiceIsActive.get()) { 6197 mInjector.getNotificationManager().notifyAsUser(LOG_TAG, RemoteBugreportUtils.NOTIFICATION_ID, 6198 RemoteBugreportUtils.buildNotification(mContext, 6199 DevicePolicyManager.NOTIFICATION_BUGREPORT_ACCEPTED_NOT_FINISHED), 6200 UserHandle.ALL); 6201 } 6202 } 6203 6204 private void onBugreportSharingDeclined() { 6205 if (mRemoteBugreportServiceIsActive.get()) { 6206 mInjector.systemPropertiesSet(RemoteBugreportUtils.CTL_STOP, 6207 RemoteBugreportUtils.REMOTE_BUGREPORT_SERVICE); 6208 mRemoteBugreportServiceIsActive.set(false); 6209 mHandler.removeCallbacks(mRemoteBugreportTimeoutRunnable); 6210 mContext.unregisterReceiver(mRemoteBugreportFinishedReceiver); 6211 } 6212 mRemoteBugreportSharingAccepted.set(false); 6213 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6214 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_SHARING_DECLINED, null); 6215 } 6216 6217 private void shareBugreportWithDeviceOwnerIfExists(String bugreportUriString, 6218 String bugreportHash) { 6219 ParcelFileDescriptor pfd = null; 6220 try { 6221 if (bugreportUriString == null) { 6222 throw new FileNotFoundException(); 6223 } 6224 Uri bugreportUri = Uri.parse(bugreportUriString); 6225 pfd = mContext.getContentResolver().openFileDescriptor(bugreportUri, "r"); 6226 6227 synchronized (this) { 6228 Intent intent = new Intent(DeviceAdminReceiver.ACTION_BUGREPORT_SHARE); 6229 intent.setComponent(mOwners.getDeviceOwnerComponent()); 6230 intent.setDataAndType(bugreportUri, RemoteBugreportUtils.BUGREPORT_MIMETYPE); 6231 intent.putExtra(DeviceAdminReceiver.EXTRA_BUGREPORT_HASH, bugreportHash); 6232 intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6233 6234 LocalServices.getService(ActivityManagerInternal.class) 6235 .grantUriPermissionFromIntent(Process.SHELL_UID, 6236 mOwners.getDeviceOwnerComponent().getPackageName(), 6237 intent, mOwners.getDeviceOwnerUserId()); 6238 mContext.sendBroadcastAsUser(intent, UserHandle.of(mOwners.getDeviceOwnerUserId())); 6239 } 6240 } catch (FileNotFoundException e) { 6241 Bundle extras = new Bundle(); 6242 extras.putInt(DeviceAdminReceiver.EXTRA_BUGREPORT_FAILURE_REASON, 6243 DeviceAdminReceiver.BUGREPORT_FAILURE_FILE_NO_LONGER_AVAILABLE); 6244 sendDeviceOwnerCommand(DeviceAdminReceiver.ACTION_BUGREPORT_FAILED, extras); 6245 } finally { 6246 try { 6247 if (pfd != null) { 6248 pfd.close(); 6249 } 6250 } catch (IOException ex) { 6251 // Ignore 6252 } 6253 mRemoteBugreportSharingAccepted.set(false); 6254 setDeviceOwnerRemoteBugreportUriAndHash(null, null); 6255 } 6256 } 6257 6258 /** 6259 * Disables all device cameras according to the specified admin. 6260 */ 6261 @Override 6262 public void setCameraDisabled(ComponentName who, boolean disabled) { 6263 if (!mHasFeature) { 6264 return; 6265 } 6266 Preconditions.checkNotNull(who, "ComponentName is null"); 6267 final int userHandle = mInjector.userHandleGetCallingUserId(); 6268 synchronized (this) { 6269 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 6270 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 6271 if (ap.disableCamera != disabled) { 6272 ap.disableCamera = disabled; 6273 saveSettingsLocked(userHandle); 6274 } 6275 } 6276 // Tell the user manager that the restrictions have changed. 6277 pushUserRestrictions(userHandle); 6278 } 6279 6280 /** 6281 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 6282 * active admins. 6283 */ 6284 @Override 6285 public boolean getCameraDisabled(ComponentName who, int userHandle) { 6286 return getCameraDisabled(who, userHandle, /* mergeDeviceOwnerRestriction= */ true); 6287 } 6288 6289 private boolean getCameraDisabled(ComponentName who, int userHandle, 6290 boolean mergeDeviceOwnerRestriction) { 6291 if (!mHasFeature) { 6292 return false; 6293 } 6294 synchronized (this) { 6295 if (who != null) { 6296 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 6297 return (admin != null) ? admin.disableCamera : false; 6298 } 6299 // First, see if DO has set it. If so, it's device-wide. 6300 if (mergeDeviceOwnerRestriction) { 6301 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6302 if (deviceOwner != null && deviceOwner.disableCamera) { 6303 return true; 6304 } 6305 } 6306 6307 // Then check each device admin on the user. 6308 DevicePolicyData policy = getUserData(userHandle); 6309 // Determine whether or not the device camera is disabled for any active admins. 6310 final int N = policy.mAdminList.size(); 6311 for (int i = 0; i < N; i++) { 6312 ActiveAdmin admin = policy.mAdminList.get(i); 6313 if (admin.disableCamera) { 6314 return true; 6315 } 6316 } 6317 return false; 6318 } 6319 } 6320 6321 @Override 6322 public void setKeyguardDisabledFeatures(ComponentName who, int which, boolean parent) { 6323 if (!mHasFeature) { 6324 return; 6325 } 6326 Preconditions.checkNotNull(who, "ComponentName is null"); 6327 final int userHandle = mInjector.userHandleGetCallingUserId(); 6328 if (isManagedProfile(userHandle)) { 6329 if (parent) { 6330 which = which & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER; 6331 } else { 6332 which = which & PROFILE_KEYGUARD_FEATURES; 6333 } 6334 } 6335 synchronized (this) { 6336 ActiveAdmin ap = getActiveAdminForCallerLocked( 6337 who, DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 6338 if (ap.disabledKeyguardFeatures != which) { 6339 ap.disabledKeyguardFeatures = which; 6340 saveSettingsLocked(userHandle); 6341 } 6342 } 6343 } 6344 6345 /** 6346 * Gets the disabled state for features in keyguard for the given admin, 6347 * or the aggregate of all active admins if who is null. 6348 */ 6349 @Override 6350 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle, boolean parent) { 6351 if (!mHasFeature) { 6352 return 0; 6353 } 6354 enforceFullCrossUsersPermission(userHandle); 6355 final long ident = mInjector.binderClearCallingIdentity(); 6356 try { 6357 synchronized (this) { 6358 if (who != null) { 6359 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle, parent); 6360 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 6361 } 6362 6363 final List<ActiveAdmin> admins; 6364 if (!parent && isManagedProfile(userHandle)) { 6365 // If we are being asked about a managed profile, just return keyguard features 6366 // disabled by admins in the profile. 6367 admins = getUserDataUnchecked(userHandle).mAdminList; 6368 } else { 6369 // Otherwise return those set by admins in the user and its profiles. 6370 admins = getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 6371 } 6372 6373 int which = DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_NONE; 6374 final int N = admins.size(); 6375 for (int i = 0; i < N; i++) { 6376 ActiveAdmin admin = admins.get(i); 6377 int userId = admin.getUserHandle().getIdentifier(); 6378 boolean isRequestedUser = !parent && (userId == userHandle); 6379 if (isRequestedUser || !isManagedProfile(userId)) { 6380 // If we are being asked explicitly about this user 6381 // return all disabled features even if its a managed profile. 6382 which |= admin.disabledKeyguardFeatures; 6383 } else { 6384 // Otherwise a managed profile is only allowed to disable 6385 // some features on the parent user. 6386 which |= (admin.disabledKeyguardFeatures 6387 & PROFILE_KEYGUARD_FEATURES_AFFECT_OWNER); 6388 } 6389 } 6390 return which; 6391 } 6392 } finally { 6393 mInjector.binderRestoreCallingIdentity(ident); 6394 } 6395 } 6396 6397 @Override 6398 public void setKeepUninstalledPackages(ComponentName who, String callerPackage, 6399 List<String> packageList) { 6400 if (!mHasFeature) { 6401 return; 6402 } 6403 Preconditions.checkNotNull(packageList, "packageList is null"); 6404 final int userHandle = UserHandle.getCallingUserId(); 6405 synchronized (this) { 6406 // Ensure the caller is a DO or a keep uninstalled packages delegate. 6407 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6408 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 6409 // Get the device owner 6410 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6411 // Set list of packages to be kept even if uninstalled. 6412 deviceOwner.keepUninstalledPackages = packageList; 6413 // Save settings. 6414 saveSettingsLocked(userHandle); 6415 // Notify package manager. 6416 mInjector.getPackageManagerInternal().setKeepUninstalledPackages(packageList); 6417 } 6418 } 6419 6420 @Override 6421 public List<String> getKeepUninstalledPackages(ComponentName who, String callerPackage) { 6422 if (!mHasFeature) { 6423 return null; 6424 } 6425 // TODO In split system user mode, allow apps on user 0 to query the list 6426 synchronized (this) { 6427 // Ensure the caller is a DO or a keep uninstalled packages delegate. 6428 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 6429 DELEGATION_KEEP_UNINSTALLED_PACKAGES); 6430 return getKeepUninstalledPackagesLocked(); 6431 } 6432 } 6433 6434 private List<String> getKeepUninstalledPackagesLocked() { 6435 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 6436 return (deviceOwner != null) ? deviceOwner.keepUninstalledPackages : null; 6437 } 6438 6439 @Override 6440 public boolean setDeviceOwner(ComponentName admin, String ownerName, int userId) { 6441 if (!mHasFeature) { 6442 return false; 6443 } 6444 if (admin == null 6445 || !isPackageInstalledForUser(admin.getPackageName(), userId)) { 6446 throw new IllegalArgumentException("Invalid component " + admin 6447 + " for device owner"); 6448 } 6449 final boolean hasIncompatibleAccountsOrNonAdb = 6450 hasIncompatibleAccountsOrNonAdbNoLock(userId, admin); 6451 synchronized (this) { 6452 enforceCanSetDeviceOwnerLocked(admin, userId, hasIncompatibleAccountsOrNonAdb); 6453 final ActiveAdmin activeAdmin = getActiveAdminUncheckedLocked(admin, userId); 6454 if (activeAdmin == null 6455 || getUserData(userId).mRemovingAdmins.contains(admin)) { 6456 throw new IllegalArgumentException("Not active admin: " + admin); 6457 } 6458 6459 // Shutting down backup manager service permanently. 6460 long ident = mInjector.binderClearCallingIdentity(); 6461 try { 6462 if (mInjector.getIBackupManager() != null) { 6463 mInjector.getIBackupManager() 6464 .setBackupServiceActive(UserHandle.USER_SYSTEM, false); 6465 } 6466 } catch (RemoteException e) { 6467 throw new IllegalStateException("Failed deactivating backup service.", e); 6468 } finally { 6469 mInjector.binderRestoreCallingIdentity(ident); 6470 } 6471 6472 if (isAdb()) { 6473 // Log device owner provisioning was started using adb. 6474 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_DEVICE_OWNER); 6475 } 6476 6477 mOwners.setDeviceOwner(admin, ownerName, userId); 6478 mOwners.writeDeviceOwner(); 6479 updateDeviceOwnerLocked(); 6480 setDeviceOwnerSystemPropertyLocked(); 6481 6482 final Set<String> restrictions = 6483 UserRestrictionsUtils.getDefaultEnabledForDeviceOwner(); 6484 if (!restrictions.isEmpty()) { 6485 for (String restriction : restrictions) { 6486 activeAdmin.ensureUserRestrictions().putBoolean(restriction, true); 6487 } 6488 activeAdmin.defaultEnabledRestrictionsAlreadySet.addAll(restrictions); 6489 Slog.i(LOG_TAG, "Enabled the following restrictions by default: " + restrictions); 6490 6491 saveUserRestrictionsLocked(userId); 6492 } 6493 6494 ident = mInjector.binderClearCallingIdentity(); 6495 try { 6496 // TODO Send to system too? 6497 mContext.sendBroadcastAsUser( 6498 new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED) 6499 .addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND), 6500 UserHandle.of(userId)); 6501 } finally { 6502 mInjector.binderRestoreCallingIdentity(ident); 6503 } 6504 mDeviceAdminServiceController.startServiceForOwner( 6505 admin.getPackageName(), userId, "set-device-owner"); 6506 6507 Slog.i(LOG_TAG, "Device owner set: " + admin + " on user " + userId); 6508 return true; 6509 } 6510 } 6511 6512 @Override 6513 public boolean hasDeviceOwner() { 6514 enforceDeviceOwnerOrManageUsers(); 6515 return mOwners.hasDeviceOwner(); 6516 } 6517 6518 boolean isDeviceOwner(ActiveAdmin admin) { 6519 return isDeviceOwner(admin.info.getComponent(), admin.getUserHandle().getIdentifier()); 6520 } 6521 6522 public boolean isDeviceOwner(ComponentName who, int userId) { 6523 synchronized (this) { 6524 return mOwners.hasDeviceOwner() 6525 && mOwners.getDeviceOwnerUserId() == userId 6526 && mOwners.getDeviceOwnerComponent().equals(who); 6527 } 6528 } 6529 6530 private boolean isDeviceOwnerPackage(String packageName, int userId) { 6531 synchronized (this) { 6532 return mOwners.hasDeviceOwner() 6533 && mOwners.getDeviceOwnerUserId() == userId 6534 && mOwners.getDeviceOwnerPackageName().equals(packageName); 6535 } 6536 } 6537 6538 private boolean isProfileOwnerPackage(String packageName, int userId) { 6539 synchronized (this) { 6540 return mOwners.hasProfileOwner(userId) 6541 && mOwners.getProfileOwnerPackage(userId).equals(packageName); 6542 } 6543 } 6544 6545 public boolean isProfileOwner(ComponentName who, int userId) { 6546 final ComponentName profileOwner = getProfileOwner(userId); 6547 return who != null && who.equals(profileOwner); 6548 } 6549 6550 @Override 6551 public ComponentName getDeviceOwnerComponent(boolean callingUserOnly) { 6552 if (!mHasFeature) { 6553 return null; 6554 } 6555 if (!callingUserOnly) { 6556 enforceManageUsers(); 6557 } 6558 synchronized (this) { 6559 if (!mOwners.hasDeviceOwner()) { 6560 return null; 6561 } 6562 if (callingUserOnly && mInjector.userHandleGetCallingUserId() != 6563 mOwners.getDeviceOwnerUserId()) { 6564 return null; 6565 } 6566 return mOwners.getDeviceOwnerComponent(); 6567 } 6568 } 6569 6570 @Override 6571 public int getDeviceOwnerUserId() { 6572 if (!mHasFeature) { 6573 return UserHandle.USER_NULL; 6574 } 6575 enforceManageUsers(); 6576 synchronized (this) { 6577 return mOwners.hasDeviceOwner() ? mOwners.getDeviceOwnerUserId() : UserHandle.USER_NULL; 6578 } 6579 } 6580 6581 /** 6582 * Returns the "name" of the device owner. It'll work for non-DO users too, but requires 6583 * MANAGE_USERS. 6584 */ 6585 @Override 6586 public String getDeviceOwnerName() { 6587 if (!mHasFeature) { 6588 return null; 6589 } 6590 enforceManageUsers(); 6591 synchronized (this) { 6592 if (!mOwners.hasDeviceOwner()) { 6593 return null; 6594 } 6595 // TODO This totally ignores the name passed to setDeviceOwner (change for b/20679292) 6596 // Should setDeviceOwner/ProfileOwner still take a name? 6597 String deviceOwnerPackage = mOwners.getDeviceOwnerPackageName(); 6598 return getApplicationLabel(deviceOwnerPackage, UserHandle.USER_SYSTEM); 6599 } 6600 } 6601 6602 /** Returns the active device owner or {@code null} if there is no device owner. */ 6603 @VisibleForTesting 6604 ActiveAdmin getDeviceOwnerAdminLocked() { 6605 ComponentName component = mOwners.getDeviceOwnerComponent(); 6606 if (component == null) { 6607 return null; 6608 } 6609 6610 DevicePolicyData policy = getUserData(mOwners.getDeviceOwnerUserId()); 6611 final int n = policy.mAdminList.size(); 6612 for (int i = 0; i < n; i++) { 6613 ActiveAdmin admin = policy.mAdminList.get(i); 6614 if (component.equals(admin.info.getComponent())) { 6615 return admin; 6616 } 6617 } 6618 Slog.wtf(LOG_TAG, "Active admin for device owner not found. component=" + component); 6619 return null; 6620 } 6621 6622 @Override 6623 public void clearDeviceOwner(String packageName) { 6624 Preconditions.checkNotNull(packageName, "packageName is null"); 6625 final int callingUid = mInjector.binderGetCallingUid(); 6626 try { 6627 int uid = mInjector.getPackageManager().getPackageUidAsUser(packageName, 6628 UserHandle.getUserId(callingUid)); 6629 if (uid != callingUid) { 6630 throw new SecurityException("Invalid packageName"); 6631 } 6632 } catch (NameNotFoundException e) { 6633 throw new SecurityException(e); 6634 } 6635 synchronized (this) { 6636 final ComponentName deviceOwnerComponent = mOwners.getDeviceOwnerComponent(); 6637 final int deviceOwnerUserId = mOwners.getDeviceOwnerUserId(); 6638 if (!mOwners.hasDeviceOwner() 6639 || !deviceOwnerComponent.getPackageName().equals(packageName) 6640 || (deviceOwnerUserId != UserHandle.getUserId(callingUid))) { 6641 throw new SecurityException( 6642 "clearDeviceOwner can only be called by the device owner"); 6643 } 6644 enforceUserUnlocked(deviceOwnerUserId); 6645 6646 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 6647 long ident = mInjector.binderClearCallingIdentity(); 6648 try { 6649 clearDeviceOwnerLocked(admin, deviceOwnerUserId); 6650 removeActiveAdminLocked(deviceOwnerComponent, deviceOwnerUserId); 6651 Intent intent = new Intent(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED); 6652 intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 6653 mContext.sendBroadcastAsUser(intent, UserHandle.of(deviceOwnerUserId)); 6654 } finally { 6655 mInjector.binderRestoreCallingIdentity(ident); 6656 } 6657 Slog.i(LOG_TAG, "Device owner removed: " + deviceOwnerComponent); 6658 } 6659 } 6660 6661 private void clearDeviceOwnerLocked(ActiveAdmin admin, int userId) { 6662 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-device-owner"); 6663 6664 if (admin != null) { 6665 admin.disableCamera = false; 6666 admin.userRestrictions = null; 6667 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6668 admin.forceEphemeralUsers = false; 6669 admin.isNetworkLoggingEnabled = false; 6670 mUserManagerInternal.setForceEphemeralUsers(admin.forceEphemeralUsers); 6671 } 6672 final DevicePolicyData policyData = getUserData(userId); 6673 policyData.mCurrentInputMethodSet = false; 6674 saveSettingsLocked(userId); 6675 final DevicePolicyData systemPolicyData = getUserData(UserHandle.USER_SYSTEM); 6676 systemPolicyData.mLastSecurityLogRetrievalTime = -1; 6677 systemPolicyData.mLastBugReportRequestTime = -1; 6678 systemPolicyData.mLastNetworkLogsRetrievalTime = -1; 6679 saveSettingsLocked(UserHandle.USER_SYSTEM); 6680 clearUserPoliciesLocked(userId); 6681 6682 mOwners.clearDeviceOwner(); 6683 mOwners.writeDeviceOwner(); 6684 updateDeviceOwnerLocked(); 6685 6686 clearDeviceOwnerUserRestrictionLocked(UserHandle.of(userId)); 6687 mInjector.securityLogSetLoggingEnabledProperty(false); 6688 mSecurityLogMonitor.stop(); 6689 setNetworkLoggingActiveInternal(false); 6690 6691 try { 6692 if (mInjector.getIBackupManager() != null) { 6693 // Reactivate backup service. 6694 mInjector.getIBackupManager().setBackupServiceActive(UserHandle.USER_SYSTEM, true); 6695 } 6696 } catch (RemoteException e) { 6697 throw new IllegalStateException("Failed reactivating backup service.", e); 6698 } 6699 } 6700 6701 @Override 6702 public boolean setProfileOwner(ComponentName who, String ownerName, int userHandle) { 6703 if (!mHasFeature) { 6704 return false; 6705 } 6706 if (who == null 6707 || !isPackageInstalledForUser(who.getPackageName(), userHandle)) { 6708 throw new IllegalArgumentException("Component " + who 6709 + " not installed for userId:" + userHandle); 6710 } 6711 final boolean hasIncompatibleAccountsOrNonAdb = 6712 hasIncompatibleAccountsOrNonAdbNoLock(userHandle, who); 6713 synchronized (this) { 6714 enforceCanSetProfileOwnerLocked(who, userHandle, hasIncompatibleAccountsOrNonAdb); 6715 6716 if (getActiveAdminUncheckedLocked(who, userHandle) == null 6717 || getUserData(userHandle).mRemovingAdmins.contains(who)) { 6718 throw new IllegalArgumentException("Not active admin: " + who); 6719 } 6720 6721 if (isAdb()) { 6722 // Log profile owner provisioning was started using adb. 6723 MetricsLogger.action(mContext, PROVISIONING_ENTRY_POINT_ADB, LOG_TAG_PROFILE_OWNER); 6724 } 6725 6726 mOwners.setProfileOwner(who, ownerName, userHandle); 6727 mOwners.writeProfileOwner(userHandle); 6728 Slog.i(LOG_TAG, "Profile owner set: " + who + " on user " + userHandle); 6729 6730 final long id = mInjector.binderClearCallingIdentity(); 6731 try { 6732 if (mUserManager.isManagedProfile(userHandle)) { 6733 setUserRestrictionOnBehalfOfProfileOwnerLocked( 6734 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userHandle); 6735 mInjector.settingsSecurePutIntForUser( 6736 Settings.Secure.UNKNOWN_SOURCES_DEFAULT_REVERSED, 0, userHandle); 6737 } 6738 } finally { 6739 mInjector.binderRestoreCallingIdentity(id); 6740 } 6741 mDeviceAdminServiceController.startServiceForOwner( 6742 who.getPackageName(), userHandle, "set-profile-owner"); 6743 return true; 6744 } 6745 } 6746 6747 @Override 6748 public void clearProfileOwner(ComponentName who) { 6749 if (!mHasFeature) { 6750 return; 6751 } 6752 Preconditions.checkNotNull(who, "ComponentName is null"); 6753 6754 final int userId = mInjector.userHandleGetCallingUserId(); 6755 enforceNotManagedProfile(userId, "clear profile owner"); 6756 enforceUserUnlocked(userId); 6757 synchronized (this) { 6758 // Check if this is the profile owner who is calling 6759 final ActiveAdmin admin = 6760 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6761 6762 final long ident = mInjector.binderClearCallingIdentity(); 6763 try { 6764 clearProfileOwnerLocked(admin, userId); 6765 removeActiveAdminLocked(who, userId); 6766 } finally { 6767 mInjector.binderRestoreCallingIdentity(ident); 6768 } 6769 Slog.i(LOG_TAG, "Profile owner " + who + " removed from user " + userId); 6770 } 6771 } 6772 6773 public void clearProfileOwnerLocked(ActiveAdmin admin, int userId) { 6774 mDeviceAdminServiceController.stopServiceForOwner(userId, "clear-profile-owner"); 6775 6776 if (admin != null) { 6777 admin.disableCamera = false; 6778 admin.userRestrictions = null; 6779 admin.defaultEnabledRestrictionsAlreadySet.clear(); 6780 } 6781 final DevicePolicyData policyData = getUserData(userId); 6782 policyData.mCurrentInputMethodSet = false; 6783 policyData.mOwnerInstalledCaCerts.clear(); 6784 saveSettingsLocked(userId); 6785 clearUserPoliciesLocked(userId); 6786 mOwners.removeProfileOwner(userId); 6787 mOwners.writeProfileOwner(userId); 6788 } 6789 6790 @Override 6791 public void setDeviceOwnerLockScreenInfo(ComponentName who, CharSequence info) { 6792 Preconditions.checkNotNull(who, "ComponentName is null"); 6793 if (!mHasFeature) { 6794 return; 6795 } 6796 6797 synchronized (this) { 6798 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 6799 long token = mInjector.binderClearCallingIdentity(); 6800 try { 6801 mLockPatternUtils.setDeviceOwnerInfo(info != null ? info.toString() : null); 6802 } finally { 6803 mInjector.binderRestoreCallingIdentity(token); 6804 } 6805 } 6806 } 6807 6808 @Override 6809 public CharSequence getDeviceOwnerLockScreenInfo() { 6810 return mLockPatternUtils.getDeviceOwnerInfo(); 6811 } 6812 6813 private void clearUserPoliciesLocked(int userId) { 6814 // Reset some of the user-specific policies. 6815 final DevicePolicyData policy = getUserData(userId); 6816 policy.mPermissionPolicy = DevicePolicyManager.PERMISSION_POLICY_PROMPT; 6817 // Clear delegations. 6818 policy.mDelegationMap.clear(); 6819 policy.mStatusBarDisabled = false; 6820 policy.mUserProvisioningState = DevicePolicyManager.STATE_USER_UNMANAGED; 6821 policy.mAffiliationIds.clear(); 6822 policy.mLockTaskPackages.clear(); 6823 saveSettingsLocked(userId); 6824 6825 try { 6826 mIPackageManager.updatePermissionFlagsForAllApps( 6827 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 6828 0 /* flagValues */, userId); 6829 pushUserRestrictions(userId); 6830 } catch (RemoteException re) { 6831 // Shouldn't happen. 6832 } 6833 } 6834 6835 @Override 6836 public boolean hasUserSetupCompleted() { 6837 return hasUserSetupCompleted(UserHandle.getCallingUserId()); 6838 } 6839 6840 // This checks only if the Setup Wizard has run. Since Wear devices pair before 6841 // completing Setup Wizard, and pairing involves transferring user data, calling 6842 // logic may want to check mIsWatch or mPaired in addition to hasUserSetupCompleted(). 6843 private boolean hasUserSetupCompleted(int userHandle) { 6844 if (!mHasFeature) { 6845 return true; 6846 } 6847 return getUserData(userHandle).mUserSetupComplete; 6848 } 6849 6850 private boolean hasPaired(int userHandle) { 6851 if (!mHasFeature) { 6852 return true; 6853 } 6854 return getUserData(userHandle).mPaired; 6855 } 6856 6857 @Override 6858 public int getUserProvisioningState() { 6859 if (!mHasFeature) { 6860 return DevicePolicyManager.STATE_USER_UNMANAGED; 6861 } 6862 int userHandle = mInjector.userHandleGetCallingUserId(); 6863 return getUserProvisioningState(userHandle); 6864 } 6865 6866 private int getUserProvisioningState(int userHandle) { 6867 return getUserData(userHandle).mUserProvisioningState; 6868 } 6869 6870 @Override 6871 public void setUserProvisioningState(int newState, int userHandle) { 6872 if (!mHasFeature) { 6873 return; 6874 } 6875 6876 if (userHandle != mOwners.getDeviceOwnerUserId() && !mOwners.hasProfileOwner(userHandle) 6877 && getManagedUserId(userHandle) == -1) { 6878 // No managed device, user or profile, so setting provisioning state makes no sense. 6879 throw new IllegalStateException("Not allowed to change provisioning state unless a " 6880 + "device or profile owner is set."); 6881 } 6882 6883 synchronized (this) { 6884 boolean transitionCheckNeeded = true; 6885 6886 // Calling identity/permission checks. 6887 if (isAdb()) { 6888 // ADB shell can only move directly from un-managed to finalized as part of directly 6889 // setting profile-owner or device-owner. 6890 if (getUserProvisioningState(userHandle) != 6891 DevicePolicyManager.STATE_USER_UNMANAGED 6892 || newState != DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6893 throw new IllegalStateException("Not allowed to change provisioning state " 6894 + "unless current provisioning state is unmanaged, and new state is " 6895 + "finalized."); 6896 } 6897 transitionCheckNeeded = false; 6898 } else { 6899 // For all other cases, caller must have MANAGE_PROFILE_AND_DEVICE_OWNERS. 6900 enforceCanManageProfileAndDeviceOwners(); 6901 } 6902 6903 final DevicePolicyData policyData = getUserData(userHandle); 6904 if (transitionCheckNeeded) { 6905 // Optional state transition check for non-ADB case. 6906 checkUserProvisioningStateTransition(policyData.mUserProvisioningState, newState); 6907 } 6908 policyData.mUserProvisioningState = newState; 6909 saveSettingsLocked(userHandle); 6910 } 6911 } 6912 6913 private void checkUserProvisioningStateTransition(int currentState, int newState) { 6914 // Valid transitions for normal use-cases. 6915 switch (currentState) { 6916 case DevicePolicyManager.STATE_USER_UNMANAGED: 6917 // Can move to any state from unmanaged (except itself as an edge case).. 6918 if (newState != DevicePolicyManager.STATE_USER_UNMANAGED) { 6919 return; 6920 } 6921 break; 6922 case DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE: 6923 case DevicePolicyManager.STATE_USER_SETUP_COMPLETE: 6924 // Can only move to finalized from these states. 6925 if (newState == DevicePolicyManager.STATE_USER_SETUP_FINALIZED) { 6926 return; 6927 } 6928 break; 6929 case DevicePolicyManager.STATE_USER_PROFILE_COMPLETE: 6930 // Current user has a managed-profile, but current user is not managed, so 6931 // rather than moving to finalized state, go back to unmanaged once 6932 // profile provisioning is complete. 6933 if (newState == DevicePolicyManager.STATE_USER_UNMANAGED) { 6934 return; 6935 } 6936 break; 6937 case DevicePolicyManager.STATE_USER_SETUP_FINALIZED: 6938 // Cannot transition out of finalized. 6939 break; 6940 } 6941 6942 // Didn't meet any of the accepted state transition checks above, throw appropriate error. 6943 throw new IllegalStateException("Cannot move to user provisioning state [" + newState + "] " 6944 + "from state [" + currentState + "]"); 6945 } 6946 6947 @Override 6948 public void setProfileEnabled(ComponentName who) { 6949 if (!mHasFeature) { 6950 return; 6951 } 6952 Preconditions.checkNotNull(who, "ComponentName is null"); 6953 synchronized (this) { 6954 // Check if this is the profile owner who is calling 6955 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6956 final int userId = UserHandle.getCallingUserId(); 6957 enforceManagedProfile(userId, "enable the profile"); 6958 // Check if the profile is already enabled. 6959 UserInfo managedProfile = getUserInfo(userId); 6960 if (managedProfile.isEnabled()) { 6961 Slog.e(LOG_TAG, 6962 "setProfileEnabled is called when the profile is already enabled"); 6963 return; 6964 } 6965 long id = mInjector.binderClearCallingIdentity(); 6966 try { 6967 mUserManager.setUserEnabled(userId); 6968 UserInfo parent = mUserManager.getProfileParent(userId); 6969 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 6970 intent.putExtra(Intent.EXTRA_USER, new UserHandle(userId)); 6971 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 6972 Intent.FLAG_RECEIVER_FOREGROUND); 6973 mContext.sendBroadcastAsUser(intent, new UserHandle(parent.id)); 6974 } finally { 6975 mInjector.binderRestoreCallingIdentity(id); 6976 } 6977 } 6978 } 6979 6980 @Override 6981 public void setProfileName(ComponentName who, String profileName) { 6982 Preconditions.checkNotNull(who, "ComponentName is null"); 6983 int userId = UserHandle.getCallingUserId(); 6984 // Check if this is the profile owner (includes device owner). 6985 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 6986 6987 long id = mInjector.binderClearCallingIdentity(); 6988 try { 6989 mUserManager.setUserName(userId, profileName); 6990 } finally { 6991 mInjector.binderRestoreCallingIdentity(id); 6992 } 6993 } 6994 6995 @Override 6996 public ComponentName getProfileOwner(int userHandle) { 6997 if (!mHasFeature) { 6998 return null; 6999 } 7000 7001 synchronized (this) { 7002 return mOwners.getProfileOwnerComponent(userHandle); 7003 } 7004 } 7005 7006 // Returns the active profile owner for this user or null if the current user has no 7007 // profile owner. 7008 @VisibleForTesting 7009 ActiveAdmin getProfileOwnerAdminLocked(int userHandle) { 7010 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userHandle); 7011 if (profileOwner == null) { 7012 return null; 7013 } 7014 DevicePolicyData policy = getUserData(userHandle); 7015 final int n = policy.mAdminList.size(); 7016 for (int i = 0; i < n; i++) { 7017 ActiveAdmin admin = policy.mAdminList.get(i); 7018 if (profileOwner.equals(admin.info.getComponent())) { 7019 return admin; 7020 } 7021 } 7022 return null; 7023 } 7024 7025 @Override 7026 public String getProfileOwnerName(int userHandle) { 7027 if (!mHasFeature) { 7028 return null; 7029 } 7030 enforceManageUsers(); 7031 ComponentName profileOwner = getProfileOwner(userHandle); 7032 if (profileOwner == null) { 7033 return null; 7034 } 7035 return getApplicationLabel(profileOwner.getPackageName(), userHandle); 7036 } 7037 7038 /** 7039 * Canonical name for a given package. 7040 */ 7041 private String getApplicationLabel(String packageName, int userHandle) { 7042 long token = mInjector.binderClearCallingIdentity(); 7043 try { 7044 final Context userContext; 7045 try { 7046 UserHandle handle = new UserHandle(userHandle); 7047 userContext = mContext.createPackageContextAsUser(packageName, 0, handle); 7048 } catch (PackageManager.NameNotFoundException nnfe) { 7049 Log.w(LOG_TAG, packageName + " is not installed for user " + userHandle, nnfe); 7050 return null; 7051 } 7052 ApplicationInfo appInfo = userContext.getApplicationInfo(); 7053 CharSequence result = null; 7054 if (appInfo != null) { 7055 PackageManager pm = userContext.getPackageManager(); 7056 result = pm.getApplicationLabel(appInfo); 7057 } 7058 return result != null ? result.toString() : null; 7059 } finally { 7060 mInjector.binderRestoreCallingIdentity(token); 7061 } 7062 } 7063 7064 /** 7065 * Calls wtfStack() if called with the DPMS lock held. 7066 */ 7067 private void wtfIfInLock() { 7068 if (Thread.holdsLock(this)) { 7069 Slog.wtfStack(LOG_TAG, "Shouldn't be called with DPMS lock held"); 7070 } 7071 } 7072 7073 /** 7074 * The profile owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7075 * permission. 7076 * The profile owner can only be set before the user setup phase has completed, 7077 * except for: 7078 * - SYSTEM_UID 7079 * - adb unless hasIncompatibleAccountsOrNonAdb is true. 7080 */ 7081 private void enforceCanSetProfileOwnerLocked(@Nullable ComponentName owner, int userHandle, 7082 boolean hasIncompatibleAccountsOrNonAdb) { 7083 UserInfo info = getUserInfo(userHandle); 7084 if (info == null) { 7085 // User doesn't exist. 7086 throw new IllegalArgumentException( 7087 "Attempted to set profile owner for invalid userId: " + userHandle); 7088 } 7089 if (info.isGuest()) { 7090 throw new IllegalStateException("Cannot set a profile owner on a guest"); 7091 } 7092 if (mOwners.hasProfileOwner(userHandle)) { 7093 throw new IllegalStateException("Trying to set the profile owner, but profile owner " 7094 + "is already set."); 7095 } 7096 if (mOwners.hasDeviceOwner() && mOwners.getDeviceOwnerUserId() == userHandle) { 7097 throw new IllegalStateException("Trying to set the profile owner, but the user " 7098 + "already has a device owner."); 7099 } 7100 if (isAdb()) { 7101 if ((mIsWatch || hasUserSetupCompleted(userHandle)) 7102 && hasIncompatibleAccountsOrNonAdb) { 7103 throw new IllegalStateException("Not allowed to set the profile owner because " 7104 + "there are already some accounts on the profile"); 7105 } 7106 return; 7107 } 7108 enforceCanManageProfileAndDeviceOwners(); 7109 if ((mIsWatch || hasUserSetupCompleted(userHandle)) && !isCallerWithSystemUid()) { 7110 throw new IllegalStateException("Cannot set the profile owner on a user which is " 7111 + "already set-up"); 7112 } 7113 } 7114 7115 /** 7116 * The Device owner can only be set by adb or an app with the MANAGE_PROFILE_AND_DEVICE_OWNERS 7117 * permission. 7118 */ 7119 private void enforceCanSetDeviceOwnerLocked(@Nullable ComponentName owner, int userId, 7120 boolean hasIncompatibleAccountsOrNonAdb) { 7121 if (!isAdb()) { 7122 enforceCanManageProfileAndDeviceOwners(); 7123 } 7124 7125 final int code = checkDeviceOwnerProvisioningPreConditionLocked( 7126 owner, userId, isAdb(), hasIncompatibleAccountsOrNonAdb); 7127 switch (code) { 7128 case CODE_OK: 7129 return; 7130 case CODE_HAS_DEVICE_OWNER: 7131 throw new IllegalStateException( 7132 "Trying to set the device owner, but device owner is already set."); 7133 case CODE_USER_HAS_PROFILE_OWNER: 7134 throw new IllegalStateException("Trying to set the device owner, but the user " 7135 + "already has a profile owner."); 7136 case CODE_USER_NOT_RUNNING: 7137 throw new IllegalStateException("User not running: " + userId); 7138 case CODE_NOT_SYSTEM_USER: 7139 throw new IllegalStateException("User is not system user"); 7140 case CODE_USER_SETUP_COMPLETED: 7141 throw new IllegalStateException( 7142 "Cannot set the device owner if the device is already set-up"); 7143 case CODE_NONSYSTEM_USER_EXISTS: 7144 throw new IllegalStateException("Not allowed to set the device owner because there " 7145 + "are already several users on the device"); 7146 case CODE_ACCOUNTS_NOT_EMPTY: 7147 throw new IllegalStateException("Not allowed to set the device owner because there " 7148 + "are already some accounts on the device"); 7149 case CODE_HAS_PAIRED: 7150 throw new IllegalStateException("Not allowed to set the device owner because this " 7151 + "device has already paired"); 7152 default: 7153 throw new IllegalStateException("Unexpected @ProvisioningPreCondition " + code); 7154 } 7155 } 7156 7157 private void enforceUserUnlocked(int userId) { 7158 // Since we're doing this operation on behalf of an app, we only 7159 // want to use the actual "unlocked" state. 7160 Preconditions.checkState(mUserManager.isUserUnlocked(userId), 7161 "User must be running and unlocked"); 7162 } 7163 7164 private void enforceUserUnlocked(@UserIdInt int userId, boolean parent) { 7165 if (parent) { 7166 enforceUserUnlocked(getProfileParentId(userId)); 7167 } else { 7168 enforceUserUnlocked(userId); 7169 } 7170 } 7171 7172 private void enforceManageUsers() { 7173 final int callingUid = mInjector.binderGetCallingUid(); 7174 if (!(isCallerWithSystemUid() || callingUid == Process.ROOT_UID)) { 7175 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7176 } 7177 } 7178 7179 private void enforceFullCrossUsersPermission(int userHandle) { 7180 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7181 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7182 } 7183 7184 private void enforceCrossUsersPermission(int userHandle) { 7185 enforceSystemUserOrPermissionIfCrossUser(userHandle, 7186 android.Manifest.permission.INTERACT_ACROSS_USERS); 7187 } 7188 7189 private void enforceSystemUserOrPermission(String permission) { 7190 if (!(isCallerWithSystemUid() || mInjector.binderGetCallingUid() == Process.ROOT_UID)) { 7191 mContext.enforceCallingOrSelfPermission(permission, 7192 "Must be system or have " + permission + " permission"); 7193 } 7194 } 7195 7196 private void enforceSystemUserOrPermissionIfCrossUser(int userHandle, String permission) { 7197 if (userHandle < 0) { 7198 throw new IllegalArgumentException("Invalid userId " + userHandle); 7199 } 7200 if (userHandle == mInjector.userHandleGetCallingUserId()) { 7201 return; 7202 } 7203 enforceSystemUserOrPermission(permission); 7204 } 7205 7206 private void enforceManagedProfile(int userHandle, String message) { 7207 if(!isManagedProfile(userHandle)) { 7208 throw new SecurityException("You can not " + message + " outside a managed profile."); 7209 } 7210 } 7211 7212 private void enforceNotManagedProfile(int userHandle, String message) { 7213 if(isManagedProfile(userHandle)) { 7214 throw new SecurityException("You can not " + message + " for a managed profile."); 7215 } 7216 } 7217 7218 private void enforceDeviceOwnerOrManageUsers() { 7219 synchronized (this) { 7220 if (getActiveAdminWithPolicyForUidLocked(null, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER, 7221 mInjector.binderGetCallingUid()) != null) { 7222 return; 7223 } 7224 } 7225 enforceManageUsers(); 7226 } 7227 7228 private void enforceProfileOwnerOrSystemUser() { 7229 synchronized (this) { 7230 if (getActiveAdminWithPolicyForUidLocked(null, 7231 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7232 != null) { 7233 return; 7234 } 7235 } 7236 Preconditions.checkState(isCallerWithSystemUid(), 7237 "Only profile owner, device owner and system may call this method."); 7238 } 7239 7240 private void enforceProfileOwnerOrFullCrossUsersPermission(int userId) { 7241 if (userId == mInjector.userHandleGetCallingUserId()) { 7242 synchronized (this) { 7243 if (getActiveAdminWithPolicyForUidLocked(null, 7244 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, mInjector.binderGetCallingUid()) 7245 != null) { 7246 // Device Owner/Profile Owner may access the user it runs on. 7247 return; 7248 } 7249 } 7250 } 7251 // Otherwise, INTERACT_ACROSS_USERS_FULL permission, system UID or root UID is required. 7252 enforceSystemUserOrPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 7253 } 7254 7255 private void ensureCallerPackage(@Nullable String packageName) { 7256 if (packageName == null) { 7257 Preconditions.checkState(isCallerWithSystemUid(), 7258 "Only caller can omit package name"); 7259 } else { 7260 final int callingUid = mInjector.binderGetCallingUid(); 7261 final int userId = mInjector.userHandleGetCallingUserId(); 7262 try { 7263 final ApplicationInfo ai = mIPackageManager.getApplicationInfo( 7264 packageName, 0, userId); 7265 Preconditions.checkState(ai.uid == callingUid, "Unmatching package name"); 7266 } catch (RemoteException e) { 7267 // Shouldn't happen 7268 } 7269 } 7270 } 7271 7272 private boolean isCallerWithSystemUid() { 7273 return UserHandle.isSameApp(mInjector.binderGetCallingUid(), Process.SYSTEM_UID); 7274 } 7275 7276 protected int getProfileParentId(int userHandle) { 7277 final long ident = mInjector.binderClearCallingIdentity(); 7278 try { 7279 UserInfo parentUser = mUserManager.getProfileParent(userHandle); 7280 return parentUser != null ? parentUser.id : userHandle; 7281 } finally { 7282 mInjector.binderRestoreCallingIdentity(ident); 7283 } 7284 } 7285 7286 private int getCredentialOwner(int userHandle, boolean parent) { 7287 final long ident = mInjector.binderClearCallingIdentity(); 7288 try { 7289 if (parent) { 7290 UserInfo parentProfile = mUserManager.getProfileParent(userHandle); 7291 if (parentProfile != null) { 7292 userHandle = parentProfile.id; 7293 } 7294 } 7295 return mUserManager.getCredentialOwnerProfile(userHandle); 7296 } finally { 7297 mInjector.binderRestoreCallingIdentity(ident); 7298 } 7299 } 7300 7301 private boolean isManagedProfile(int userHandle) { 7302 final UserInfo user = getUserInfo(userHandle); 7303 return user != null && user.isManagedProfile(); 7304 } 7305 7306 private void enableIfNecessary(String packageName, int userId) { 7307 try { 7308 ApplicationInfo ai = mIPackageManager.getApplicationInfo(packageName, 7309 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 7310 userId); 7311 if (ai.enabledSetting 7312 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 7313 mIPackageManager.setApplicationEnabledSetting(packageName, 7314 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 7315 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 7316 } 7317 } catch (RemoteException e) { 7318 } 7319 } 7320 7321 @Override 7322 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 7323 if (!DumpUtils.checkDumpPermission(mContext, LOG_TAG, pw)) return; 7324 7325 synchronized (this) { 7326 pw.println("Current Device Policy Manager state:"); 7327 mOwners.dump(" ", pw); 7328 mDeviceAdminServiceController.dump(" ", pw); 7329 int userCount = mUserData.size(); 7330 for (int u = 0; u < userCount; u++) { 7331 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 7332 pw.println(); 7333 pw.println(" Enabled Device Admins (User " + policy.mUserHandle 7334 + ", provisioningState: " + policy.mUserProvisioningState + "):"); 7335 final int N = policy.mAdminList.size(); 7336 for (int i=0; i<N; i++) { 7337 ActiveAdmin ap = policy.mAdminList.get(i); 7338 if (ap != null) { 7339 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 7340 pw.println(":"); 7341 ap.dump(" ", pw); 7342 } 7343 } 7344 if (!policy.mRemovingAdmins.isEmpty()) { 7345 pw.println(" Removing Device Admins (User " + policy.mUserHandle + "): " 7346 + policy.mRemovingAdmins); 7347 } 7348 7349 pw.println(" "); 7350 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 7351 } 7352 pw.println(); 7353 pw.println("Encryption Status: " + getEncryptionStatusName(getEncryptionStatus())); 7354 } 7355 } 7356 7357 private String getEncryptionStatusName(int encryptionStatus) { 7358 switch (encryptionStatus) { 7359 case DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE: 7360 return "inactive"; 7361 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_DEFAULT_KEY: 7362 return "block default key"; 7363 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE: 7364 return "block"; 7365 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE_PER_USER: 7366 return "per-user"; 7367 case DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED: 7368 return "unsupported"; 7369 case DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING: 7370 return "activating"; 7371 default: 7372 return "unknown"; 7373 } 7374 } 7375 7376 @Override 7377 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 7378 ComponentName activity) { 7379 Preconditions.checkNotNull(who, "ComponentName is null"); 7380 final int userHandle = UserHandle.getCallingUserId(); 7381 synchronized (this) { 7382 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7383 7384 long id = mInjector.binderClearCallingIdentity(); 7385 try { 7386 mIPackageManager.addPersistentPreferredActivity(filter, activity, userHandle); 7387 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 7388 } catch (RemoteException re) { 7389 // Shouldn't happen 7390 } finally { 7391 mInjector.binderRestoreCallingIdentity(id); 7392 } 7393 } 7394 } 7395 7396 @Override 7397 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 7398 Preconditions.checkNotNull(who, "ComponentName is null"); 7399 final int userHandle = UserHandle.getCallingUserId(); 7400 synchronized (this) { 7401 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7402 7403 long id = mInjector.binderClearCallingIdentity(); 7404 try { 7405 mIPackageManager.clearPackagePersistentPreferredActivities(packageName, userHandle); 7406 mIPackageManager.flushPackageRestrictionsAsUser(userHandle); 7407 } catch (RemoteException re) { 7408 // Shouldn't happen 7409 } finally { 7410 mInjector.binderRestoreCallingIdentity(id); 7411 } 7412 } 7413 } 7414 7415 @Override 7416 public boolean setApplicationRestrictionsManagingPackage(ComponentName admin, 7417 String packageName) { 7418 try { 7419 setDelegatedScopePreO(admin, packageName, DELEGATION_APP_RESTRICTIONS); 7420 } catch (IllegalArgumentException e) { 7421 return false; 7422 } 7423 return true; 7424 } 7425 7426 @Override 7427 public String getApplicationRestrictionsManagingPackage(ComponentName admin) { 7428 final List<String> delegatePackages = getDelegatePackages(admin, 7429 DELEGATION_APP_RESTRICTIONS); 7430 return delegatePackages.size() > 0 ? delegatePackages.get(0) : null; 7431 } 7432 7433 @Override 7434 public boolean isCallerApplicationRestrictionsManagingPackage(String callerPackage) { 7435 return isCallerDelegate(callerPackage, DELEGATION_APP_RESTRICTIONS); 7436 } 7437 7438 @Override 7439 public void setApplicationRestrictions(ComponentName who, String callerPackage, 7440 String packageName, Bundle settings) { 7441 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 7442 DELEGATION_APP_RESTRICTIONS); 7443 7444 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 7445 final long id = mInjector.binderClearCallingIdentity(); 7446 try { 7447 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 7448 } finally { 7449 mInjector.binderRestoreCallingIdentity(id); 7450 } 7451 } 7452 7453 @Override 7454 public void setTrustAgentConfiguration(ComponentName admin, ComponentName agent, 7455 PersistableBundle args, boolean parent) { 7456 if (!mHasFeature) { 7457 return; 7458 } 7459 Preconditions.checkNotNull(admin, "admin is null"); 7460 Preconditions.checkNotNull(agent, "agent is null"); 7461 final int userHandle = UserHandle.getCallingUserId(); 7462 synchronized (this) { 7463 ActiveAdmin ap = getActiveAdminForCallerLocked(admin, 7464 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES, parent); 7465 ap.trustAgentInfos.put(agent.flattenToString(), new TrustAgentInfo(args)); 7466 saveSettingsLocked(userHandle); 7467 } 7468 } 7469 7470 @Override 7471 public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, 7472 ComponentName agent, int userHandle, boolean parent) { 7473 if (!mHasFeature) { 7474 return null; 7475 } 7476 Preconditions.checkNotNull(agent, "agent null"); 7477 enforceFullCrossUsersPermission(userHandle); 7478 7479 synchronized (this) { 7480 final String componentName = agent.flattenToString(); 7481 if (admin != null) { 7482 final ActiveAdmin ap = getActiveAdminUncheckedLocked(admin, userHandle, parent); 7483 if (ap == null) return null; 7484 TrustAgentInfo trustAgentInfo = ap.trustAgentInfos.get(componentName); 7485 if (trustAgentInfo == null || trustAgentInfo.options == null) return null; 7486 List<PersistableBundle> result = new ArrayList<>(); 7487 result.add(trustAgentInfo.options); 7488 return result; 7489 } 7490 7491 // Return strictest policy for this user and profiles that are visible from this user. 7492 List<PersistableBundle> result = null; 7493 // Search through all admins that use KEYGUARD_DISABLE_TRUST_AGENTS and keep track 7494 // of the options. If any admin doesn't have options, discard options for the rest 7495 // and return null. 7496 List<ActiveAdmin> admins = 7497 getActiveAdminsForLockscreenPoliciesLocked(userHandle, parent); 7498 boolean allAdminsHaveOptions = true; 7499 final int N = admins.size(); 7500 for (int i = 0; i < N; i++) { 7501 final ActiveAdmin active = admins.get(i); 7502 7503 final boolean disablesTrust = (active.disabledKeyguardFeatures 7504 & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 7505 final TrustAgentInfo info = active.trustAgentInfos.get(componentName); 7506 if (info != null && info.options != null && !info.options.isEmpty()) { 7507 if (disablesTrust) { 7508 if (result == null) { 7509 result = new ArrayList<>(); 7510 } 7511 result.add(info.options); 7512 } else { 7513 Log.w(LOG_TAG, "Ignoring admin " + active.info 7514 + " because it has trust options but doesn't declare " 7515 + "KEYGUARD_DISABLE_TRUST_AGENTS"); 7516 } 7517 } else if (disablesTrust) { 7518 allAdminsHaveOptions = false; 7519 break; 7520 } 7521 } 7522 return allAdminsHaveOptions ? result : null; 7523 } 7524 } 7525 7526 @Override 7527 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 7528 Preconditions.checkNotNull(who, "ComponentName is null"); 7529 synchronized (this) { 7530 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7531 7532 int userHandle = UserHandle.getCallingUserId(); 7533 DevicePolicyData userData = getUserData(userHandle); 7534 userData.mRestrictionsProvider = permissionProvider; 7535 saveSettingsLocked(userHandle); 7536 } 7537 } 7538 7539 @Override 7540 public ComponentName getRestrictionsProvider(int userHandle) { 7541 synchronized (this) { 7542 if (!isCallerWithSystemUid()) { 7543 throw new SecurityException("Only the system can query the permission provider"); 7544 } 7545 DevicePolicyData userData = getUserData(userHandle); 7546 return userData != null ? userData.mRestrictionsProvider : null; 7547 } 7548 } 7549 7550 @Override 7551 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 7552 Preconditions.checkNotNull(who, "ComponentName is null"); 7553 int callingUserId = UserHandle.getCallingUserId(); 7554 synchronized (this) { 7555 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7556 7557 long id = mInjector.binderClearCallingIdentity(); 7558 try { 7559 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7560 if (parent == null) { 7561 Slog.e(LOG_TAG, "Cannot call addCrossProfileIntentFilter if there is no " 7562 + "parent"); 7563 return; 7564 } 7565 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 7566 mIPackageManager.addCrossProfileIntentFilter( 7567 filter, who.getPackageName(), callingUserId, parent.id, 0); 7568 } 7569 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 7570 mIPackageManager.addCrossProfileIntentFilter(filter, who.getPackageName(), 7571 parent.id, callingUserId, 0); 7572 } 7573 } catch (RemoteException re) { 7574 // Shouldn't happen 7575 } finally { 7576 mInjector.binderRestoreCallingIdentity(id); 7577 } 7578 } 7579 } 7580 7581 @Override 7582 public void clearCrossProfileIntentFilters(ComponentName who) { 7583 Preconditions.checkNotNull(who, "ComponentName is null"); 7584 int callingUserId = UserHandle.getCallingUserId(); 7585 synchronized (this) { 7586 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7587 long id = mInjector.binderClearCallingIdentity(); 7588 try { 7589 UserInfo parent = mUserManager.getProfileParent(callingUserId); 7590 if (parent == null) { 7591 Slog.e(LOG_TAG, "Cannot call clearCrossProfileIntentFilter if there is no " 7592 + "parent"); 7593 return; 7594 } 7595 // Removing those that go from the managed profile to the parent. 7596 mIPackageManager.clearCrossProfileIntentFilters( 7597 callingUserId, who.getPackageName()); 7598 // And those that go from the parent to the managed profile. 7599 // If we want to support multiple managed profiles, we will have to only remove 7600 // those that have callingUserId as their target. 7601 mIPackageManager.clearCrossProfileIntentFilters(parent.id, who.getPackageName()); 7602 } catch (RemoteException re) { 7603 // Shouldn't happen 7604 } finally { 7605 mInjector.binderRestoreCallingIdentity(id); 7606 } 7607 } 7608 } 7609 7610 /** 7611 * @return true if all packages in enabledPackages are either in the list 7612 * permittedList or are a system app. 7613 */ 7614 private boolean checkPackagesInPermittedListOrSystem(List<String> enabledPackages, 7615 List<String> permittedList, int userIdToCheck) { 7616 long id = mInjector.binderClearCallingIdentity(); 7617 try { 7618 // If we have an enabled packages list for a managed profile the packages 7619 // we should check are installed for the parent user. 7620 UserInfo user = getUserInfo(userIdToCheck); 7621 if (user.isManagedProfile()) { 7622 userIdToCheck = user.profileGroupId; 7623 } 7624 7625 for (String enabledPackage : enabledPackages) { 7626 boolean systemService = false; 7627 try { 7628 ApplicationInfo applicationInfo = mIPackageManager.getApplicationInfo( 7629 enabledPackage, PackageManager.MATCH_UNINSTALLED_PACKAGES, 7630 userIdToCheck); 7631 systemService = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7632 } catch (RemoteException e) { 7633 Log.i(LOG_TAG, "Can't talk to package managed", e); 7634 } 7635 if (!systemService && !permittedList.contains(enabledPackage)) { 7636 return false; 7637 } 7638 } 7639 } finally { 7640 mInjector.binderRestoreCallingIdentity(id); 7641 } 7642 return true; 7643 } 7644 7645 private AccessibilityManager getAccessibilityManagerForUser(int userId) { 7646 // Not using AccessibilityManager.getInstance because that guesses 7647 // at the user you require based on callingUid and caches for a given 7648 // process. 7649 IBinder iBinder = ServiceManager.getService(Context.ACCESSIBILITY_SERVICE); 7650 IAccessibilityManager service = iBinder == null 7651 ? null : IAccessibilityManager.Stub.asInterface(iBinder); 7652 return new AccessibilityManager(mContext, service, userId); 7653 } 7654 7655 @Override 7656 public boolean setPermittedAccessibilityServices(ComponentName who, List packageList) { 7657 if (!mHasFeature) { 7658 return false; 7659 } 7660 Preconditions.checkNotNull(who, "ComponentName is null"); 7661 7662 if (packageList != null) { 7663 int userId = UserHandle.getCallingUserId(); 7664 List<AccessibilityServiceInfo> enabledServices = null; 7665 long id = mInjector.binderClearCallingIdentity(); 7666 try { 7667 UserInfo user = getUserInfo(userId); 7668 if (user.isManagedProfile()) { 7669 userId = user.profileGroupId; 7670 } 7671 AccessibilityManager accessibilityManager = getAccessibilityManagerForUser(userId); 7672 enabledServices = accessibilityManager.getEnabledAccessibilityServiceList( 7673 AccessibilityServiceInfo.FEEDBACK_ALL_MASK); 7674 } finally { 7675 mInjector.binderRestoreCallingIdentity(id); 7676 } 7677 7678 if (enabledServices != null) { 7679 List<String> enabledPackages = new ArrayList<String>(); 7680 for (AccessibilityServiceInfo service : enabledServices) { 7681 enabledPackages.add(service.getResolveInfo().serviceInfo.packageName); 7682 } 7683 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7684 userId)) { 7685 Slog.e(LOG_TAG, "Cannot set permitted accessibility services, " 7686 + "because it contains already enabled accesibility services."); 7687 return false; 7688 } 7689 } 7690 } 7691 7692 synchronized (this) { 7693 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7694 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7695 admin.permittedAccessiblityServices = packageList; 7696 saveSettingsLocked(UserHandle.getCallingUserId()); 7697 } 7698 return true; 7699 } 7700 7701 @Override 7702 public List getPermittedAccessibilityServices(ComponentName who) { 7703 if (!mHasFeature) { 7704 return null; 7705 } 7706 Preconditions.checkNotNull(who, "ComponentName is null"); 7707 7708 synchronized (this) { 7709 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7710 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7711 return admin.permittedAccessiblityServices; 7712 } 7713 } 7714 7715 @Override 7716 public List getPermittedAccessibilityServicesForUser(int userId) { 7717 if (!mHasFeature) { 7718 return null; 7719 } 7720 synchronized (this) { 7721 List<String> result = null; 7722 // If we have multiple profiles we return the intersection of the 7723 // permitted lists. This can happen in cases where we have a device 7724 // and profile owner. 7725 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7726 for (int profileId : profileIds) { 7727 // Just loop though all admins, only device or profiles 7728 // owners can have permitted lists set. 7729 DevicePolicyData policy = getUserDataUnchecked(profileId); 7730 final int N = policy.mAdminList.size(); 7731 for (int j = 0; j < N; j++) { 7732 ActiveAdmin admin = policy.mAdminList.get(j); 7733 List<String> fromAdmin = admin.permittedAccessiblityServices; 7734 if (fromAdmin != null) { 7735 if (result == null) { 7736 result = new ArrayList<>(fromAdmin); 7737 } else { 7738 result.retainAll(fromAdmin); 7739 } 7740 } 7741 } 7742 } 7743 7744 // If we have a permitted list add all system accessibility services. 7745 if (result != null) { 7746 long id = mInjector.binderClearCallingIdentity(); 7747 try { 7748 UserInfo user = getUserInfo(userId); 7749 if (user.isManagedProfile()) { 7750 userId = user.profileGroupId; 7751 } 7752 AccessibilityManager accessibilityManager = 7753 getAccessibilityManagerForUser(userId); 7754 List<AccessibilityServiceInfo> installedServices = 7755 accessibilityManager.getInstalledAccessibilityServiceList(); 7756 7757 if (installedServices != null) { 7758 for (AccessibilityServiceInfo service : installedServices) { 7759 ServiceInfo serviceInfo = service.getResolveInfo().serviceInfo; 7760 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7761 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7762 result.add(serviceInfo.packageName); 7763 } 7764 } 7765 } 7766 } finally { 7767 mInjector.binderRestoreCallingIdentity(id); 7768 } 7769 } 7770 7771 return result; 7772 } 7773 } 7774 7775 @Override 7776 public boolean isAccessibilityServicePermittedByAdmin(ComponentName who, String packageName, 7777 int userHandle) { 7778 if (!mHasFeature) { 7779 return true; 7780 } 7781 Preconditions.checkNotNull(who, "ComponentName is null"); 7782 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7783 if (!isCallerWithSystemUid()){ 7784 throw new SecurityException( 7785 "Only the system can query if an accessibility service is disabled by admin"); 7786 } 7787 synchronized (this) { 7788 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7789 if (admin == null) { 7790 return false; 7791 } 7792 if (admin.permittedAccessiblityServices == null) { 7793 return true; 7794 } 7795 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7796 admin.permittedAccessiblityServices, userHandle); 7797 } 7798 } 7799 7800 private boolean checkCallerIsCurrentUserOrProfile() { 7801 int callingUserId = UserHandle.getCallingUserId(); 7802 long token = mInjector.binderClearCallingIdentity(); 7803 try { 7804 UserInfo currentUser; 7805 UserInfo callingUser = getUserInfo(callingUserId); 7806 try { 7807 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7808 } catch (RemoteException e) { 7809 Slog.e(LOG_TAG, "Failed to talk to activity managed.", e); 7810 return false; 7811 } 7812 7813 if (callingUser.isManagedProfile() && callingUser.profileGroupId != currentUser.id) { 7814 Slog.e(LOG_TAG, "Cannot set permitted input methods for managed profile " 7815 + "of a user that isn't the foreground user."); 7816 return false; 7817 } 7818 if (!callingUser.isManagedProfile() && callingUserId != currentUser.id ) { 7819 Slog.e(LOG_TAG, "Cannot set permitted input methods " 7820 + "of a user that isn't the foreground user."); 7821 return false; 7822 } 7823 } finally { 7824 mInjector.binderRestoreCallingIdentity(token); 7825 } 7826 return true; 7827 } 7828 7829 @Override 7830 public boolean setPermittedInputMethods(ComponentName who, List packageList) { 7831 if (!mHasFeature) { 7832 return false; 7833 } 7834 Preconditions.checkNotNull(who, "ComponentName is null"); 7835 7836 // TODO When InputMethodManager supports per user calls remove 7837 // this restriction. 7838 if (!checkCallerIsCurrentUserOrProfile()) { 7839 return false; 7840 } 7841 7842 if (packageList != null) { 7843 // InputMethodManager fetches input methods for current user. 7844 // So this can only be set when calling user is the current user 7845 // or parent is current user in case of managed profiles. 7846 InputMethodManager inputMethodManager = 7847 mContext.getSystemService(InputMethodManager.class); 7848 List<InputMethodInfo> enabledImes = inputMethodManager.getEnabledInputMethodList(); 7849 7850 if (enabledImes != null) { 7851 List<String> enabledPackages = new ArrayList<String>(); 7852 for (InputMethodInfo ime : enabledImes) { 7853 enabledPackages.add(ime.getPackageName()); 7854 } 7855 if (!checkPackagesInPermittedListOrSystem(enabledPackages, packageList, 7856 mInjector.binderGetCallingUserHandle().getIdentifier())) { 7857 Slog.e(LOG_TAG, "Cannot set permitted input methods, " 7858 + "because it contains already enabled input method."); 7859 return false; 7860 } 7861 } 7862 } 7863 7864 synchronized (this) { 7865 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7866 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7867 admin.permittedInputMethods = packageList; 7868 saveSettingsLocked(UserHandle.getCallingUserId()); 7869 } 7870 return true; 7871 } 7872 7873 @Override 7874 public List getPermittedInputMethods(ComponentName who) { 7875 if (!mHasFeature) { 7876 return null; 7877 } 7878 Preconditions.checkNotNull(who, "ComponentName is null"); 7879 7880 synchronized (this) { 7881 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 7882 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 7883 return admin.permittedInputMethods; 7884 } 7885 } 7886 7887 @Override 7888 public List getPermittedInputMethodsForCurrentUser() { 7889 UserInfo currentUser; 7890 try { 7891 currentUser = mInjector.getIActivityManager().getCurrentUser(); 7892 } catch (RemoteException e) { 7893 Slog.e(LOG_TAG, "Failed to make remote calls to get current user", e); 7894 // Activity managed is dead, just allow all IMEs 7895 return null; 7896 } 7897 7898 int userId = currentUser.id; 7899 synchronized (this) { 7900 List<String> result = null; 7901 // If we have multiple profiles we return the intersection of the 7902 // permitted lists. This can happen in cases where we have a device 7903 // and profile owner. 7904 int[] profileIds = mUserManager.getProfileIdsWithDisabled(userId); 7905 for (int profileId : profileIds) { 7906 // Just loop though all admins, only device or profiles 7907 // owners can have permitted lists set. 7908 DevicePolicyData policy = getUserDataUnchecked(profileId); 7909 final int N = policy.mAdminList.size(); 7910 for (int j = 0; j < N; j++) { 7911 ActiveAdmin admin = policy.mAdminList.get(j); 7912 List<String> fromAdmin = admin.permittedInputMethods; 7913 if (fromAdmin != null) { 7914 if (result == null) { 7915 result = new ArrayList<String>(fromAdmin); 7916 } else { 7917 result.retainAll(fromAdmin); 7918 } 7919 } 7920 } 7921 } 7922 7923 // If we have a permitted list add all system input methods. 7924 if (result != null) { 7925 InputMethodManager inputMethodManager = 7926 mContext.getSystemService(InputMethodManager.class); 7927 List<InputMethodInfo> imes = inputMethodManager.getInputMethodList(); 7928 long id = mInjector.binderClearCallingIdentity(); 7929 try { 7930 if (imes != null) { 7931 for (InputMethodInfo ime : imes) { 7932 ServiceInfo serviceInfo = ime.getServiceInfo(); 7933 ApplicationInfo applicationInfo = serviceInfo.applicationInfo; 7934 if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 7935 result.add(serviceInfo.packageName); 7936 } 7937 } 7938 } 7939 } finally { 7940 mInjector.binderRestoreCallingIdentity(id); 7941 } 7942 } 7943 return result; 7944 } 7945 } 7946 7947 @Override 7948 public boolean isInputMethodPermittedByAdmin(ComponentName who, String packageName, 7949 int userHandle) { 7950 if (!mHasFeature) { 7951 return true; 7952 } 7953 Preconditions.checkNotNull(who, "ComponentName is null"); 7954 Preconditions.checkStringNotEmpty(packageName, "packageName is null"); 7955 if (!isCallerWithSystemUid()) { 7956 throw new SecurityException( 7957 "Only the system can query if an input method is disabled by admin"); 7958 } 7959 synchronized (this) { 7960 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 7961 if (admin == null) { 7962 return false; 7963 } 7964 if (admin.permittedInputMethods == null) { 7965 return true; 7966 } 7967 return checkPackagesInPermittedListOrSystem(Arrays.asList(packageName), 7968 admin.permittedInputMethods, userHandle); 7969 } 7970 } 7971 7972 private void sendAdminEnabledBroadcastLocked(int userHandle) { 7973 DevicePolicyData policyData = getUserData(userHandle); 7974 if (policyData.mAdminBroadcastPending) { 7975 // Send the initialization data to profile owner and delete the data 7976 ActiveAdmin admin = getProfileOwnerAdminLocked(userHandle); 7977 if (admin != null) { 7978 PersistableBundle initBundle = policyData.mInitBundle; 7979 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 7980 initBundle == null ? null : new Bundle(initBundle), null); 7981 } 7982 policyData.mInitBundle = null; 7983 policyData.mAdminBroadcastPending = false; 7984 saveSettingsLocked(userHandle); 7985 } 7986 } 7987 7988 @Override 7989 public UserHandle createAndManageUser(ComponentName admin, String name, 7990 ComponentName profileOwner, PersistableBundle adminExtras, int flags) { 7991 Preconditions.checkNotNull(admin, "admin is null"); 7992 Preconditions.checkNotNull(profileOwner, "profileOwner is null"); 7993 if (!admin.getPackageName().equals(profileOwner.getPackageName())) { 7994 throw new IllegalArgumentException("profileOwner " + profileOwner + " and admin " 7995 + admin + " are not in the same package"); 7996 } 7997 // Only allow the system user to use this method 7998 if (!mInjector.binderGetCallingUserHandle().isSystem()) { 7999 throw new SecurityException("createAndManageUser was called from non-system user"); 8000 } 8001 if (!mInjector.userManagerIsSplitSystemUser() 8002 && (flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 8003 throw new IllegalArgumentException( 8004 "Ephemeral users are only supported on systems with a split system user."); 8005 } 8006 // Create user. 8007 UserHandle user = null; 8008 synchronized (this) { 8009 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8010 8011 final long id = mInjector.binderClearCallingIdentity(); 8012 try { 8013 int userInfoFlags = 0; 8014 if ((flags & DevicePolicyManager.MAKE_USER_EPHEMERAL) != 0) { 8015 userInfoFlags |= UserInfo.FLAG_EPHEMERAL; 8016 } 8017 UserInfo userInfo = mUserManagerInternal.createUserEvenWhenDisallowed(name, 8018 userInfoFlags); 8019 if (userInfo != null) { 8020 user = userInfo.getUserHandle(); 8021 } 8022 } finally { 8023 mInjector.binderRestoreCallingIdentity(id); 8024 } 8025 } 8026 if (user == null) { 8027 return null; 8028 } 8029 // Set admin. 8030 final long id = mInjector.binderClearCallingIdentity(); 8031 try { 8032 final String adminPkg = admin.getPackageName(); 8033 8034 final int userHandle = user.getIdentifier(); 8035 try { 8036 // Install the profile owner if not present. 8037 if (!mIPackageManager.isPackageAvailable(adminPkg, userHandle)) { 8038 mIPackageManager.installExistingPackageAsUser(adminPkg, userHandle, 8039 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8040 } 8041 } catch (RemoteException e) { 8042 Slog.e(LOG_TAG, "Failed to make remote calls for createAndManageUser, " 8043 + "removing created user", e); 8044 mUserManager.removeUser(user.getIdentifier()); 8045 return null; 8046 } 8047 8048 setActiveAdmin(profileOwner, true, userHandle); 8049 // User is not started yet, the broadcast by setActiveAdmin will not be received. 8050 // So we store adminExtras for broadcasting when the user starts for first time. 8051 synchronized(this) { 8052 DevicePolicyData policyData = getUserData(userHandle); 8053 policyData.mInitBundle = adminExtras; 8054 policyData.mAdminBroadcastPending = true; 8055 saveSettingsLocked(userHandle); 8056 } 8057 final String ownerName = getProfileOwnerName(Process.myUserHandle().getIdentifier()); 8058 setProfileOwner(profileOwner, ownerName, userHandle); 8059 8060 if ((flags & DevicePolicyManager.SKIP_SETUP_WIZARD) != 0) { 8061 Settings.Secure.putIntForUser(mContext.getContentResolver(), 8062 Settings.Secure.USER_SETUP_COMPLETE, 1, userHandle); 8063 } 8064 8065 return user; 8066 } finally { 8067 mInjector.binderRestoreCallingIdentity(id); 8068 } 8069 } 8070 8071 @Override 8072 public boolean removeUser(ComponentName who, UserHandle userHandle) { 8073 Preconditions.checkNotNull(who, "ComponentName is null"); 8074 synchronized (this) { 8075 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8076 } 8077 8078 final int callingUserId = mInjector.userHandleGetCallingUserId(); 8079 final long id = mInjector.binderClearCallingIdentity(); 8080 try { 8081 String restriction = isManagedProfile(userHandle.getIdentifier()) 8082 ? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE 8083 : UserManager.DISALLOW_REMOVE_USER; 8084 if (isAdminAffectedByRestriction(who, restriction, callingUserId)) { 8085 Log.w(LOG_TAG, "The device owner cannot remove a user because " 8086 + restriction + " is enabled, and was not set by the device owner"); 8087 return false; 8088 } 8089 return mUserManagerInternal.removeUserEvenWhenDisallowed(userHandle.getIdentifier()); 8090 } finally { 8091 mInjector.binderRestoreCallingIdentity(id); 8092 } 8093 } 8094 8095 private boolean isAdminAffectedByRestriction( 8096 ComponentName admin, String userRestriction, int userId) { 8097 switch(mUserManager.getUserRestrictionSource(userRestriction, UserHandle.of(userId))) { 8098 case UserManager.RESTRICTION_NOT_SET: 8099 return false; 8100 case UserManager.RESTRICTION_SOURCE_DEVICE_OWNER: 8101 return !isDeviceOwner(admin, userId); 8102 case UserManager.RESTRICTION_SOURCE_PROFILE_OWNER: 8103 return !isProfileOwner(admin, userId); 8104 default: 8105 return true; 8106 } 8107 } 8108 8109 @Override 8110 public boolean switchUser(ComponentName who, UserHandle userHandle) { 8111 Preconditions.checkNotNull(who, "ComponentName is null"); 8112 synchronized (this) { 8113 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8114 8115 long id = mInjector.binderClearCallingIdentity(); 8116 try { 8117 int userId = UserHandle.USER_SYSTEM; 8118 if (userHandle != null) { 8119 userId = userHandle.getIdentifier(); 8120 } 8121 return mInjector.getIActivityManager().switchUser(userId); 8122 } catch (RemoteException e) { 8123 Log.e(LOG_TAG, "Couldn't switch user", e); 8124 return false; 8125 } finally { 8126 mInjector.binderRestoreCallingIdentity(id); 8127 } 8128 } 8129 } 8130 8131 @Override 8132 public Bundle getApplicationRestrictions(ComponentName who, String callerPackage, 8133 String packageName) { 8134 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8135 DELEGATION_APP_RESTRICTIONS); 8136 8137 final UserHandle userHandle = mInjector.binderGetCallingUserHandle(); 8138 final long id = mInjector.binderClearCallingIdentity(); 8139 try { 8140 Bundle bundle = mUserManager.getApplicationRestrictions(packageName, userHandle); 8141 // if no restrictions were saved, mUserManager.getApplicationRestrictions 8142 // returns null, but DPM method should return an empty Bundle as per JavaDoc 8143 return bundle != null ? bundle : Bundle.EMPTY; 8144 } finally { 8145 mInjector.binderRestoreCallingIdentity(id); 8146 } 8147 } 8148 8149 @Override 8150 public String[] setPackagesSuspended(ComponentName who, String callerPackage, 8151 String[] packageNames, boolean suspended) { 8152 int callingUserId = UserHandle.getCallingUserId(); 8153 synchronized (this) { 8154 // Ensure the caller is a DO/PO or a package access delegate. 8155 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8156 DELEGATION_PACKAGE_ACCESS); 8157 8158 long id = mInjector.binderClearCallingIdentity(); 8159 try { 8160 return mIPackageManager.setPackagesSuspendedAsUser( 8161 packageNames, suspended, callingUserId); 8162 } catch (RemoteException re) { 8163 // Shouldn't happen. 8164 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 8165 } finally { 8166 mInjector.binderRestoreCallingIdentity(id); 8167 } 8168 return packageNames; 8169 } 8170 } 8171 8172 @Override 8173 public boolean isPackageSuspended(ComponentName who, String callerPackage, String packageName) { 8174 int callingUserId = UserHandle.getCallingUserId(); 8175 synchronized (this) { 8176 // Ensure the caller is a DO/PO or a package access delegate. 8177 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8178 DELEGATION_PACKAGE_ACCESS); 8179 8180 long id = mInjector.binderClearCallingIdentity(); 8181 try { 8182 return mIPackageManager.isPackageSuspendedForUser(packageName, callingUserId); 8183 } catch (RemoteException re) { 8184 // Shouldn't happen. 8185 Slog.e(LOG_TAG, "Failed talking to the package manager", re); 8186 } finally { 8187 mInjector.binderRestoreCallingIdentity(id); 8188 } 8189 return false; 8190 } 8191 } 8192 8193 @Override 8194 public void setUserRestriction(ComponentName who, String key, boolean enabledFromThisOwner) { 8195 Preconditions.checkNotNull(who, "ComponentName is null"); 8196 if (!UserRestrictionsUtils.isValidRestriction(key)) { 8197 return; 8198 } 8199 8200 final int userHandle = mInjector.userHandleGetCallingUserId(); 8201 synchronized (this) { 8202 final ActiveAdmin activeAdmin = 8203 getActiveAdminForCallerLocked(who, 8204 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8205 final boolean isDeviceOwner = isDeviceOwner(who, userHandle); 8206 if (isDeviceOwner) { 8207 if (!UserRestrictionsUtils.canDeviceOwnerChange(key)) { 8208 throw new SecurityException("Device owner cannot set user restriction " + key); 8209 } 8210 } else { // profile owner 8211 if (!UserRestrictionsUtils.canProfileOwnerChange(key, userHandle)) { 8212 throw new SecurityException("Profile owner cannot set user restriction " + key); 8213 } 8214 } 8215 8216 // Save the restriction to ActiveAdmin. 8217 final Bundle restrictions = activeAdmin.ensureUserRestrictions(); 8218 if (enabledFromThisOwner) { 8219 restrictions.putBoolean(key, true); 8220 } else { 8221 restrictions.remove(key); 8222 } 8223 saveUserRestrictionsLocked(userHandle); 8224 } 8225 } 8226 8227 private void saveUserRestrictionsLocked(int userId) { 8228 saveSettingsLocked(userId); 8229 pushUserRestrictions(userId); 8230 sendChangedNotification(userId); 8231 } 8232 8233 private void pushUserRestrictions(int userId) { 8234 synchronized (this) { 8235 final boolean isDeviceOwner = mOwners.isDeviceOwnerUserId(userId); 8236 final Bundle userRestrictions; 8237 // Whether device owner enforces camera restriction. 8238 boolean disallowCameraGlobally = false; 8239 8240 if (isDeviceOwner) { 8241 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 8242 if (deviceOwner == null) { 8243 return; // Shouldn't happen. 8244 } 8245 userRestrictions = deviceOwner.userRestrictions; 8246 // DO can disable camera globally. 8247 disallowCameraGlobally = deviceOwner.disableCamera; 8248 } else { 8249 final ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userId); 8250 userRestrictions = profileOwner != null ? profileOwner.userRestrictions : null; 8251 } 8252 8253 // Whether any admin enforces camera restriction. 8254 final int cameraRestrictionScope = 8255 getCameraRestrictionScopeLocked(userId, disallowCameraGlobally); 8256 8257 mUserManagerInternal.setDevicePolicyUserRestrictions(userId, userRestrictions, 8258 isDeviceOwner, cameraRestrictionScope); 8259 } 8260 } 8261 8262 /** 8263 * Get the scope of camera restriction for a given user if any. 8264 */ 8265 private int getCameraRestrictionScopeLocked(int userId, boolean disallowCameraGlobally) { 8266 if (disallowCameraGlobally) { 8267 return UserManagerInternal.CAMERA_DISABLED_GLOBALLY; 8268 } else if (getCameraDisabled( 8269 /* who= */ null, userId, /* mergeDeviceOwnerRestriction= */ false)) { 8270 return UserManagerInternal.CAMERA_DISABLED_LOCALLY; 8271 } 8272 return UserManagerInternal.CAMERA_NOT_DISABLED; 8273 } 8274 8275 @Override 8276 public Bundle getUserRestrictions(ComponentName who) { 8277 if (!mHasFeature) { 8278 return null; 8279 } 8280 Preconditions.checkNotNull(who, "ComponentName is null"); 8281 synchronized (this) { 8282 final ActiveAdmin activeAdmin = getActiveAdminForCallerLocked(who, 8283 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8284 return activeAdmin.userRestrictions; 8285 } 8286 } 8287 8288 @Override 8289 public boolean setApplicationHidden(ComponentName who, String callerPackage, String packageName, 8290 boolean hidden) { 8291 int callingUserId = UserHandle.getCallingUserId(); 8292 synchronized (this) { 8293 // Ensure the caller is a DO/PO or a package access delegate. 8294 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8295 DELEGATION_PACKAGE_ACCESS); 8296 8297 long id = mInjector.binderClearCallingIdentity(); 8298 try { 8299 return mIPackageManager.setApplicationHiddenSettingAsUser( 8300 packageName, hidden, callingUserId); 8301 } catch (RemoteException re) { 8302 // shouldn't happen 8303 Slog.e(LOG_TAG, "Failed to setApplicationHiddenSetting", re); 8304 } finally { 8305 mInjector.binderRestoreCallingIdentity(id); 8306 } 8307 return false; 8308 } 8309 } 8310 8311 @Override 8312 public boolean isApplicationHidden(ComponentName who, String callerPackage, 8313 String packageName) { 8314 int callingUserId = UserHandle.getCallingUserId(); 8315 synchronized (this) { 8316 // Ensure the caller is a DO/PO or a package access delegate. 8317 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8318 DELEGATION_PACKAGE_ACCESS); 8319 8320 long id = mInjector.binderClearCallingIdentity(); 8321 try { 8322 return mIPackageManager.getApplicationHiddenSettingAsUser( 8323 packageName, callingUserId); 8324 } catch (RemoteException re) { 8325 // shouldn't happen 8326 Slog.e(LOG_TAG, "Failed to getApplicationHiddenSettingAsUser", re); 8327 } finally { 8328 mInjector.binderRestoreCallingIdentity(id); 8329 } 8330 return false; 8331 } 8332 } 8333 8334 @Override 8335 public void enableSystemApp(ComponentName who, String callerPackage, String packageName) { 8336 synchronized (this) { 8337 // Ensure the caller is a DO/PO or an enable system app delegate. 8338 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8339 DELEGATION_ENABLE_SYSTEM_APP); 8340 8341 int userId = UserHandle.getCallingUserId(); 8342 long id = mInjector.binderClearCallingIdentity(); 8343 8344 try { 8345 if (VERBOSE_LOG) { 8346 Slog.v(LOG_TAG, "installing " + packageName + " for " 8347 + userId); 8348 } 8349 8350 int parentUserId = getProfileParentId(userId); 8351 if (!isSystemApp(mIPackageManager, packageName, parentUserId)) { 8352 throw new IllegalArgumentException("Only system apps can be enabled this way."); 8353 } 8354 8355 // Install the app. 8356 mIPackageManager.installExistingPackageAsUser(packageName, userId, 8357 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8358 8359 } catch (RemoteException re) { 8360 // shouldn't happen 8361 Slog.wtf(LOG_TAG, "Failed to install " + packageName, re); 8362 } finally { 8363 mInjector.binderRestoreCallingIdentity(id); 8364 } 8365 } 8366 } 8367 8368 @Override 8369 public int enableSystemAppWithIntent(ComponentName who, String callerPackage, Intent intent) { 8370 synchronized (this) { 8371 // Ensure the caller is a DO/PO or an enable system app delegate. 8372 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8373 DELEGATION_ENABLE_SYSTEM_APP); 8374 8375 int userId = UserHandle.getCallingUserId(); 8376 long id = mInjector.binderClearCallingIdentity(); 8377 8378 try { 8379 int parentUserId = getProfileParentId(userId); 8380 List<ResolveInfo> activitiesToEnable = mIPackageManager 8381 .queryIntentActivities(intent, 8382 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 8383 PackageManager.MATCH_DIRECT_BOOT_AWARE 8384 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE, 8385 parentUserId) 8386 .getList(); 8387 8388 if (VERBOSE_LOG) { 8389 Slog.d(LOG_TAG, "Enabling system activities: " + activitiesToEnable); 8390 } 8391 int numberOfAppsInstalled = 0; 8392 if (activitiesToEnable != null) { 8393 for (ResolveInfo info : activitiesToEnable) { 8394 if (info.activityInfo != null) { 8395 String packageName = info.activityInfo.packageName; 8396 if (isSystemApp(mIPackageManager, packageName, parentUserId)) { 8397 numberOfAppsInstalled++; 8398 mIPackageManager.installExistingPackageAsUser(packageName, userId, 8399 0 /*installFlags*/, PackageManager.INSTALL_REASON_POLICY); 8400 } else { 8401 Slog.d(LOG_TAG, "Not enabling " + packageName + " since is not a" 8402 + " system app"); 8403 } 8404 } 8405 } 8406 } 8407 return numberOfAppsInstalled; 8408 } catch (RemoteException e) { 8409 // shouldn't happen 8410 Slog.wtf(LOG_TAG, "Failed to resolve intent for: " + intent); 8411 return 0; 8412 } finally { 8413 mInjector.binderRestoreCallingIdentity(id); 8414 } 8415 } 8416 } 8417 8418 private boolean isSystemApp(IPackageManager pm, String packageName, int userId) 8419 throws RemoteException { 8420 ApplicationInfo appInfo = pm.getApplicationInfo(packageName, MATCH_UNINSTALLED_PACKAGES, 8421 userId); 8422 if (appInfo == null) { 8423 throw new IllegalArgumentException("The application " + packageName + 8424 " is not present on this device"); 8425 } 8426 return (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 8427 } 8428 8429 @Override 8430 public void setAccountManagementDisabled(ComponentName who, String accountType, 8431 boolean disabled) { 8432 if (!mHasFeature) { 8433 return; 8434 } 8435 Preconditions.checkNotNull(who, "ComponentName is null"); 8436 synchronized (this) { 8437 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 8438 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8439 if (disabled) { 8440 ap.accountTypesWithManagementDisabled.add(accountType); 8441 } else { 8442 ap.accountTypesWithManagementDisabled.remove(accountType); 8443 } 8444 saveSettingsLocked(UserHandle.getCallingUserId()); 8445 } 8446 } 8447 8448 @Override 8449 public String[] getAccountTypesWithManagementDisabled() { 8450 return getAccountTypesWithManagementDisabledAsUser(UserHandle.getCallingUserId()); 8451 } 8452 8453 @Override 8454 public String[] getAccountTypesWithManagementDisabledAsUser(int userId) { 8455 enforceFullCrossUsersPermission(userId); 8456 if (!mHasFeature) { 8457 return null; 8458 } 8459 synchronized (this) { 8460 DevicePolicyData policy = getUserData(userId); 8461 final int N = policy.mAdminList.size(); 8462 ArraySet<String> resultSet = new ArraySet<>(); 8463 for (int i = 0; i < N; i++) { 8464 ActiveAdmin admin = policy.mAdminList.get(i); 8465 resultSet.addAll(admin.accountTypesWithManagementDisabled); 8466 } 8467 return resultSet.toArray(new String[resultSet.size()]); 8468 } 8469 } 8470 8471 @Override 8472 public void setUninstallBlocked(ComponentName who, String callerPackage, String packageName, 8473 boolean uninstallBlocked) { 8474 final int userId = UserHandle.getCallingUserId(); 8475 synchronized (this) { 8476 // Ensure the caller is a DO/PO or a block uninstall delegate 8477 enforceCanManageScope(who, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 8478 DELEGATION_BLOCK_UNINSTALL); 8479 8480 long id = mInjector.binderClearCallingIdentity(); 8481 try { 8482 mIPackageManager.setBlockUninstallForUser(packageName, uninstallBlocked, userId); 8483 } catch (RemoteException re) { 8484 // Shouldn't happen. 8485 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 8486 } finally { 8487 mInjector.binderRestoreCallingIdentity(id); 8488 } 8489 } 8490 } 8491 8492 @Override 8493 public boolean isUninstallBlocked(ComponentName who, String packageName) { 8494 // This function should return true if and only if the package is blocked by 8495 // setUninstallBlocked(). It should still return false for other cases of blocks, such as 8496 // when the package is a system app, or when it is an active device admin. 8497 final int userId = UserHandle.getCallingUserId(); 8498 8499 synchronized (this) { 8500 if (who != null) { 8501 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8502 } 8503 8504 long id = mInjector.binderClearCallingIdentity(); 8505 try { 8506 return mIPackageManager.getBlockUninstallForUser(packageName, userId); 8507 } catch (RemoteException re) { 8508 // Shouldn't happen. 8509 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 8510 } finally { 8511 mInjector.binderRestoreCallingIdentity(id); 8512 } 8513 } 8514 return false; 8515 } 8516 8517 @Override 8518 public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { 8519 if (!mHasFeature) { 8520 return; 8521 } 8522 Preconditions.checkNotNull(who, "ComponentName is null"); 8523 synchronized (this) { 8524 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8525 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8526 if (admin.disableCallerId != disabled) { 8527 admin.disableCallerId = disabled; 8528 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8529 } 8530 } 8531 } 8532 8533 @Override 8534 public boolean getCrossProfileCallerIdDisabled(ComponentName who) { 8535 if (!mHasFeature) { 8536 return false; 8537 } 8538 Preconditions.checkNotNull(who, "ComponentName is null"); 8539 synchronized (this) { 8540 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8541 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8542 return admin.disableCallerId; 8543 } 8544 } 8545 8546 @Override 8547 public boolean getCrossProfileCallerIdDisabledForUser(int userId) { 8548 enforceCrossUsersPermission(userId); 8549 synchronized (this) { 8550 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8551 return (admin != null) ? admin.disableCallerId : false; 8552 } 8553 } 8554 8555 @Override 8556 public void setCrossProfileContactsSearchDisabled(ComponentName who, boolean disabled) { 8557 if (!mHasFeature) { 8558 return; 8559 } 8560 Preconditions.checkNotNull(who, "ComponentName is null"); 8561 synchronized (this) { 8562 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8563 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8564 if (admin.disableContactsSearch != disabled) { 8565 admin.disableContactsSearch = disabled; 8566 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 8567 } 8568 } 8569 } 8570 8571 @Override 8572 public boolean getCrossProfileContactsSearchDisabled(ComponentName who) { 8573 if (!mHasFeature) { 8574 return false; 8575 } 8576 Preconditions.checkNotNull(who, "ComponentName is null"); 8577 synchronized (this) { 8578 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8579 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8580 return admin.disableContactsSearch; 8581 } 8582 } 8583 8584 @Override 8585 public boolean getCrossProfileContactsSearchDisabledForUser(int userId) { 8586 enforceCrossUsersPermission(userId); 8587 synchronized (this) { 8588 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8589 return (admin != null) ? admin.disableContactsSearch : false; 8590 } 8591 } 8592 8593 @Override 8594 public void startManagedQuickContact(String actualLookupKey, long actualContactId, 8595 boolean isContactIdIgnored, long actualDirectoryId, Intent originalIntent) { 8596 final Intent intent = QuickContact.rebuildManagedQuickContactsIntent(actualLookupKey, 8597 actualContactId, isContactIdIgnored, actualDirectoryId, originalIntent); 8598 final int callingUserId = UserHandle.getCallingUserId(); 8599 8600 final long ident = mInjector.binderClearCallingIdentity(); 8601 try { 8602 synchronized (this) { 8603 final int managedUserId = getManagedUserId(callingUserId); 8604 if (managedUserId < 0) { 8605 return; 8606 } 8607 if (isCrossProfileQuickContactDisabled(managedUserId)) { 8608 if (VERBOSE_LOG) { 8609 Log.v(LOG_TAG, 8610 "Cross-profile contacts access disabled for user " + managedUserId); 8611 } 8612 return; 8613 } 8614 ContactsInternal.startQuickContactWithErrorToastForUser( 8615 mContext, intent, new UserHandle(managedUserId)); 8616 } 8617 } finally { 8618 mInjector.binderRestoreCallingIdentity(ident); 8619 } 8620 } 8621 8622 /** 8623 * @return true if cross-profile QuickContact is disabled 8624 */ 8625 private boolean isCrossProfileQuickContactDisabled(int userId) { 8626 return getCrossProfileCallerIdDisabledForUser(userId) 8627 && getCrossProfileContactsSearchDisabledForUser(userId); 8628 } 8629 8630 /** 8631 * @return the user ID of the managed user that is linked to the current user, if any. 8632 * Otherwise -1. 8633 */ 8634 public int getManagedUserId(int callingUserId) { 8635 if (VERBOSE_LOG) { 8636 Log.v(LOG_TAG, "getManagedUserId: callingUserId=" + callingUserId); 8637 } 8638 8639 for (UserInfo ui : mUserManager.getProfiles(callingUserId)) { 8640 if (ui.id == callingUserId || !ui.isManagedProfile()) { 8641 continue; // Caller user self, or not a managed profile. Skip. 8642 } 8643 if (VERBOSE_LOG) { 8644 Log.v(LOG_TAG, "Managed user=" + ui.id); 8645 } 8646 return ui.id; 8647 } 8648 if (VERBOSE_LOG) { 8649 Log.v(LOG_TAG, "Managed user not found."); 8650 } 8651 return -1; 8652 } 8653 8654 @Override 8655 public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { 8656 if (!mHasFeature) { 8657 return; 8658 } 8659 Preconditions.checkNotNull(who, "ComponentName is null"); 8660 synchronized (this) { 8661 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8662 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8663 if (admin.disableBluetoothContactSharing != disabled) { 8664 admin.disableBluetoothContactSharing = disabled; 8665 saveSettingsLocked(UserHandle.getCallingUserId()); 8666 } 8667 } 8668 } 8669 8670 @Override 8671 public boolean getBluetoothContactSharingDisabled(ComponentName who) { 8672 if (!mHasFeature) { 8673 return false; 8674 } 8675 Preconditions.checkNotNull(who, "ComponentName is null"); 8676 synchronized (this) { 8677 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 8678 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8679 return admin.disableBluetoothContactSharing; 8680 } 8681 } 8682 8683 @Override 8684 public boolean getBluetoothContactSharingDisabledForUser(int userId) { 8685 // TODO: Should there be a check to make sure this relationship is 8686 // within a profile group? 8687 // enforceSystemProcess("getCrossProfileCallerIdDisabled can only be called by system"); 8688 synchronized (this) { 8689 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 8690 return (admin != null) ? admin.disableBluetoothContactSharing : false; 8691 } 8692 } 8693 8694 @Override 8695 public void setLockTaskPackages(ComponentName who, String[] packages) 8696 throws SecurityException { 8697 Preconditions.checkNotNull(who, "ComponentName is null"); 8698 Preconditions.checkNotNull(packages, "packages is null"); 8699 8700 synchronized (this) { 8701 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8702 final int userHandle = mInjector.userHandleGetCallingUserId(); 8703 if (isUserAffiliatedWithDeviceLocked(userHandle)) { 8704 setLockTaskPackagesLocked(userHandle, new ArrayList<>(Arrays.asList(packages))); 8705 } else { 8706 throw new SecurityException("Admin " + who + 8707 " is neither the device owner or affiliated user's profile owner."); 8708 } 8709 } 8710 } 8711 8712 private void setLockTaskPackagesLocked(int userHandle, List<String> packages) { 8713 DevicePolicyData policy = getUserData(userHandle); 8714 policy.mLockTaskPackages = packages; 8715 8716 // Store the settings persistently. 8717 saveSettingsLocked(userHandle); 8718 updateLockTaskPackagesLocked(packages, userHandle); 8719 } 8720 8721 private void maybeClearLockTaskPackagesLocked() { 8722 final long ident = mInjector.binderClearCallingIdentity(); 8723 try { 8724 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 8725 for (int i = 0; i < userInfos.size(); i++) { 8726 int userId = userInfos.get(i).id; 8727 final List<String> lockTaskPackages = getUserData(userId).mLockTaskPackages; 8728 if (!lockTaskPackages.isEmpty() && 8729 !isUserAffiliatedWithDeviceLocked(userId)) { 8730 Slog.d(LOG_TAG, 8731 "User id " + userId + " not affiliated. Clearing lock task packages"); 8732 setLockTaskPackagesLocked(userId, Collections.<String>emptyList()); 8733 } 8734 } 8735 } finally { 8736 mInjector.binderRestoreCallingIdentity(ident); 8737 } 8738 } 8739 8740 @Override 8741 public String[] getLockTaskPackages(ComponentName who) { 8742 Preconditions.checkNotNull(who, "ComponentName is null"); 8743 8744 final int userHandle = mInjector.binderGetCallingUserHandle().getIdentifier(); 8745 synchronized (this) { 8746 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8747 if (!isUserAffiliatedWithDeviceLocked(userHandle)) { 8748 throw new SecurityException("Admin " + who + 8749 " is neither the device owner or affiliated user's profile owner."); 8750 } 8751 8752 final List<String> packages = getUserData(userHandle).mLockTaskPackages; 8753 return packages.toArray(new String[packages.size()]); 8754 } 8755 } 8756 8757 @Override 8758 public boolean isLockTaskPermitted(String pkg) { 8759 final int userHandle = mInjector.userHandleGetCallingUserId(); 8760 synchronized (this) { 8761 return getUserData(userHandle).mLockTaskPackages.contains(pkg); 8762 } 8763 } 8764 8765 @Override 8766 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 8767 if (!isCallerWithSystemUid()) { 8768 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 8769 } 8770 synchronized (this) { 8771 final DevicePolicyData policy = getUserData(userHandle); 8772 Bundle adminExtras = new Bundle(); 8773 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 8774 for (ActiveAdmin admin : policy.mAdminList) { 8775 final boolean ownsDevice = isDeviceOwner(admin.info.getComponent(), userHandle); 8776 final boolean ownsProfile = isProfileOwner(admin.info.getComponent(), userHandle); 8777 if (ownsDevice || ownsProfile) { 8778 if (isEnabled) { 8779 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_ENTERING, 8780 adminExtras, null); 8781 } else { 8782 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_EXITING); 8783 } 8784 } 8785 } 8786 } 8787 } 8788 8789 @Override 8790 public void setGlobalSetting(ComponentName who, String setting, String value) { 8791 Preconditions.checkNotNull(who, "ComponentName is null"); 8792 8793 synchronized (this) { 8794 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8795 8796 // Some settings are no supported any more. However we do not want to throw a 8797 // SecurityException to avoid breaking apps. 8798 if (GLOBAL_SETTINGS_DEPRECATED.contains(setting)) { 8799 Log.i(LOG_TAG, "Global setting no longer supported: " + setting); 8800 return; 8801 } 8802 8803 if (!GLOBAL_SETTINGS_WHITELIST.contains(setting)) { 8804 throw new SecurityException(String.format( 8805 "Permission denial: device owners cannot update %1$s", setting)); 8806 } 8807 8808 if (Settings.Global.STAY_ON_WHILE_PLUGGED_IN.equals(setting)) { 8809 // ignore if it contradicts an existing policy 8810 long timeMs = getMaximumTimeToLock( 8811 who, mInjector.userHandleGetCallingUserId(), /* parent */ false); 8812 if (timeMs > 0 && timeMs < Integer.MAX_VALUE) { 8813 return; 8814 } 8815 } 8816 8817 long id = mInjector.binderClearCallingIdentity(); 8818 try { 8819 mInjector.settingsGlobalPutString(setting, value); 8820 } finally { 8821 mInjector.binderRestoreCallingIdentity(id); 8822 } 8823 } 8824 } 8825 8826 @Override 8827 public void setSecureSetting(ComponentName who, String setting, String value) { 8828 Preconditions.checkNotNull(who, "ComponentName is null"); 8829 int callingUserId = mInjector.userHandleGetCallingUserId(); 8830 8831 synchronized (this) { 8832 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8833 8834 if (isDeviceOwner(who, callingUserId)) { 8835 if (!SECURE_SETTINGS_DEVICEOWNER_WHITELIST.contains(setting)) { 8836 throw new SecurityException(String.format( 8837 "Permission denial: Device owners cannot update %1$s", setting)); 8838 } 8839 } else if (!SECURE_SETTINGS_WHITELIST.contains(setting)) { 8840 throw new SecurityException(String.format( 8841 "Permission denial: Profile owners cannot update %1$s", setting)); 8842 } 8843 if (setting.equals(Settings.Secure.INSTALL_NON_MARKET_APPS)) { 8844 if (getTargetSdk(who.getPackageName(), callingUserId) >= Build.VERSION_CODES.O) { 8845 throw new UnsupportedOperationException(Settings.Secure.INSTALL_NON_MARKET_APPS 8846 + " is deprecated. Please use the user restriction " 8847 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES + " instead."); 8848 } 8849 if (!mUserManager.isManagedProfile(callingUserId)) { 8850 Slog.e(LOG_TAG, "Ignoring setSecureSetting request for " 8851 + setting + ". User restriction " 8852 + UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES 8853 + " should be used instead."); 8854 } else { 8855 try { 8856 setUserRestriction(who, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, 8857 (Integer.parseInt(value) == 0) ? true : false); 8858 } catch (NumberFormatException exc) { 8859 Slog.e(LOG_TAG, "Invalid value: " + value + " for setting " + setting); 8860 } 8861 } 8862 return; 8863 } 8864 long id = mInjector.binderClearCallingIdentity(); 8865 try { 8866 if (Settings.Secure.DEFAULT_INPUT_METHOD.equals(setting)) { 8867 final String currentValue = mInjector.settingsSecureGetStringForUser( 8868 Settings.Secure.DEFAULT_INPUT_METHOD, callingUserId); 8869 if (!TextUtils.equals(currentValue, value)) { 8870 // Tell the content observer that the next change will be due to the owner 8871 // changing the value. There is a small race condition here that we cannot 8872 // avoid: Change notifications are sent asynchronously, so it is possible 8873 // that there are prior notifications queued up before the one we are about 8874 // to trigger. This is a corner case that will have no impact in practice. 8875 mSetupContentObserver.addPendingChangeByOwnerLocked(callingUserId); 8876 } 8877 getUserData(callingUserId).mCurrentInputMethodSet = true; 8878 saveSettingsLocked(callingUserId); 8879 } 8880 mInjector.settingsSecurePutStringForUser(setting, value, callingUserId); 8881 } finally { 8882 mInjector.binderRestoreCallingIdentity(id); 8883 } 8884 } 8885 } 8886 8887 @Override 8888 public void setMasterVolumeMuted(ComponentName who, boolean on) { 8889 Preconditions.checkNotNull(who, "ComponentName is null"); 8890 synchronized (this) { 8891 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8892 setUserRestriction(who, UserManager.DISALLOW_UNMUTE_DEVICE, on); 8893 } 8894 } 8895 8896 @Override 8897 public boolean isMasterVolumeMuted(ComponentName who) { 8898 Preconditions.checkNotNull(who, "ComponentName is null"); 8899 synchronized (this) { 8900 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8901 8902 AudioManager audioManager = 8903 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 8904 return audioManager.isMasterMute(); 8905 } 8906 } 8907 8908 @Override 8909 public void setUserIcon(ComponentName who, Bitmap icon) { 8910 synchronized (this) { 8911 Preconditions.checkNotNull(who, "ComponentName is null"); 8912 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 8913 8914 int userId = UserHandle.getCallingUserId(); 8915 long id = mInjector.binderClearCallingIdentity(); 8916 try { 8917 mUserManagerInternal.setUserIcon(userId, icon); 8918 } finally { 8919 mInjector.binderRestoreCallingIdentity(id); 8920 } 8921 } 8922 } 8923 8924 @Override 8925 public boolean setKeyguardDisabled(ComponentName who, boolean disabled) { 8926 Preconditions.checkNotNull(who, "ComponentName is null"); 8927 synchronized (this) { 8928 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8929 } 8930 final int userId = UserHandle.getCallingUserId(); 8931 8932 long ident = mInjector.binderClearCallingIdentity(); 8933 try { 8934 // disallow disabling the keyguard if a password is currently set 8935 if (disabled && mLockPatternUtils.isSecure(userId)) { 8936 return false; 8937 } 8938 mLockPatternUtils.setLockScreenDisabled(disabled, userId); 8939 } finally { 8940 mInjector.binderRestoreCallingIdentity(ident); 8941 } 8942 return true; 8943 } 8944 8945 @Override 8946 public boolean setStatusBarDisabled(ComponentName who, boolean disabled) { 8947 int userId = UserHandle.getCallingUserId(); 8948 synchronized (this) { 8949 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 8950 DevicePolicyData policy = getUserData(userId); 8951 if (policy.mStatusBarDisabled != disabled) { 8952 if (!setStatusBarDisabledInternal(disabled, userId)) { 8953 return false; 8954 } 8955 policy.mStatusBarDisabled = disabled; 8956 saveSettingsLocked(userId); 8957 } 8958 } 8959 return true; 8960 } 8961 8962 private boolean setStatusBarDisabledInternal(boolean disabled, int userId) { 8963 long ident = mInjector.binderClearCallingIdentity(); 8964 try { 8965 IStatusBarService statusBarService = IStatusBarService.Stub.asInterface( 8966 ServiceManager.checkService(Context.STATUS_BAR_SERVICE)); 8967 if (statusBarService != null) { 8968 int flags1 = disabled ? STATUS_BAR_DISABLE_MASK : StatusBarManager.DISABLE_NONE; 8969 int flags2 = disabled ? STATUS_BAR_DISABLE2_MASK : StatusBarManager.DISABLE2_NONE; 8970 statusBarService.disableForUser(flags1, mToken, mContext.getPackageName(), userId); 8971 statusBarService.disable2ForUser(flags2, mToken, mContext.getPackageName(), userId); 8972 return true; 8973 } 8974 } catch (RemoteException e) { 8975 Slog.e(LOG_TAG, "Failed to disable the status bar", e); 8976 } finally { 8977 mInjector.binderRestoreCallingIdentity(ident); 8978 } 8979 return false; 8980 } 8981 8982 /** 8983 * We need to update the internal state of whether a user has completed setup or a 8984 * device has paired once. After that, we ignore any changes that reset the 8985 * Settings.Secure.USER_SETUP_COMPLETE or Settings.Secure.DEVICE_PAIRED change 8986 * as we don't trust any apps that might try to reset them. 8987 * <p> 8988 * Unfortunately, we don't know which user's setup state was changed, so we write all of 8989 * them. 8990 */ 8991 void updateUserSetupCompleteAndPaired() { 8992 List<UserInfo> users = mUserManager.getUsers(true); 8993 final int N = users.size(); 8994 for (int i = 0; i < N; i++) { 8995 int userHandle = users.get(i).id; 8996 if (mInjector.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0, 8997 userHandle) != 0) { 8998 DevicePolicyData policy = getUserData(userHandle); 8999 if (!policy.mUserSetupComplete) { 9000 policy.mUserSetupComplete = true; 9001 synchronized (this) { 9002 saveSettingsLocked(userHandle); 9003 } 9004 } 9005 } 9006 if (mIsWatch && mInjector.settingsSecureGetIntForUser(Settings.Secure.DEVICE_PAIRED, 0, 9007 userHandle) != 0) { 9008 DevicePolicyData policy = getUserData(userHandle); 9009 if (!policy.mPaired) { 9010 policy.mPaired = true; 9011 synchronized (this) { 9012 saveSettingsLocked(userHandle); 9013 } 9014 } 9015 } 9016 } 9017 } 9018 9019 private class SetupContentObserver extends ContentObserver { 9020 private final Uri mUserSetupComplete = Settings.Secure.getUriFor( 9021 Settings.Secure.USER_SETUP_COMPLETE); 9022 private final Uri mDeviceProvisioned = Settings.Global.getUriFor( 9023 Settings.Global.DEVICE_PROVISIONED); 9024 private final Uri mPaired = Settings.Secure.getUriFor(Settings.Secure.DEVICE_PAIRED); 9025 private final Uri mDefaultImeChanged = Settings.Secure.getUriFor( 9026 Settings.Secure.DEFAULT_INPUT_METHOD); 9027 9028 @GuardedBy("DevicePolicyManagerService.this") 9029 private Set<Integer> mUserIdsWithPendingChangesByOwner = new ArraySet<>(); 9030 9031 public SetupContentObserver(Handler handler) { 9032 super(handler); 9033 } 9034 9035 void register() { 9036 mInjector.registerContentObserver(mUserSetupComplete, false, this, UserHandle.USER_ALL); 9037 mInjector.registerContentObserver(mDeviceProvisioned, false, this, UserHandle.USER_ALL); 9038 if (mIsWatch) { 9039 mInjector.registerContentObserver(mPaired, false, this, UserHandle.USER_ALL); 9040 } 9041 mInjector.registerContentObserver(mDefaultImeChanged, false, this, UserHandle.USER_ALL); 9042 } 9043 9044 private void addPendingChangeByOwnerLocked(int userId) { 9045 mUserIdsWithPendingChangesByOwner.add(userId); 9046 } 9047 9048 @Override 9049 public void onChange(boolean selfChange, Uri uri, int userId) { 9050 if (mUserSetupComplete.equals(uri) || (mIsWatch && mPaired.equals(uri))) { 9051 updateUserSetupCompleteAndPaired(); 9052 } else if (mDeviceProvisioned.equals(uri)) { 9053 synchronized (DevicePolicyManagerService.this) { 9054 // Set PROPERTY_DEVICE_OWNER_PRESENT, for the SUW case where setting the property 9055 // is delayed until device is marked as provisioned. 9056 setDeviceOwnerSystemPropertyLocked(); 9057 } 9058 } else if (mDefaultImeChanged.equals(uri)) { 9059 synchronized (DevicePolicyManagerService.this) { 9060 if (mUserIdsWithPendingChangesByOwner.contains(userId)) { 9061 // This change notification was triggered by the owner changing the current 9062 // IME. Ignore it. 9063 mUserIdsWithPendingChangesByOwner.remove(userId); 9064 } else { 9065 // This change notification was triggered by the user manually changing the 9066 // current IME. 9067 getUserData(userId).mCurrentInputMethodSet = false; 9068 saveSettingsLocked(userId); 9069 } 9070 } 9071 } 9072 } 9073 } 9074 9075 @VisibleForTesting 9076 final class LocalService extends DevicePolicyManagerInternal { 9077 private List<OnCrossProfileWidgetProvidersChangeListener> mWidgetProviderListeners; 9078 9079 @Override 9080 public List<String> getCrossProfileWidgetProviders(int profileId) { 9081 synchronized (DevicePolicyManagerService.this) { 9082 if (mOwners == null) { 9083 return Collections.emptyList(); 9084 } 9085 ComponentName ownerComponent = mOwners.getProfileOwnerComponent(profileId); 9086 if (ownerComponent == null) { 9087 return Collections.emptyList(); 9088 } 9089 9090 DevicePolicyData policy = getUserDataUnchecked(profileId); 9091 ActiveAdmin admin = policy.mAdminMap.get(ownerComponent); 9092 9093 if (admin == null || admin.crossProfileWidgetProviders == null 9094 || admin.crossProfileWidgetProviders.isEmpty()) { 9095 return Collections.emptyList(); 9096 } 9097 9098 return admin.crossProfileWidgetProviders; 9099 } 9100 } 9101 9102 @Override 9103 public void addOnCrossProfileWidgetProvidersChangeListener( 9104 OnCrossProfileWidgetProvidersChangeListener listener) { 9105 synchronized (DevicePolicyManagerService.this) { 9106 if (mWidgetProviderListeners == null) { 9107 mWidgetProviderListeners = new ArrayList<>(); 9108 } 9109 if (!mWidgetProviderListeners.contains(listener)) { 9110 mWidgetProviderListeners.add(listener); 9111 } 9112 } 9113 } 9114 9115 @Override 9116 public boolean isActiveAdminWithPolicy(int uid, int reqPolicy) { 9117 synchronized(DevicePolicyManagerService.this) { 9118 return getActiveAdminWithPolicyForUidLocked(null, reqPolicy, uid) != null; 9119 } 9120 } 9121 9122 private void notifyCrossProfileProvidersChanged(int userId, List<String> packages) { 9123 final List<OnCrossProfileWidgetProvidersChangeListener> listeners; 9124 synchronized (DevicePolicyManagerService.this) { 9125 listeners = new ArrayList<>(mWidgetProviderListeners); 9126 } 9127 final int listenerCount = listeners.size(); 9128 for (int i = 0; i < listenerCount; i++) { 9129 OnCrossProfileWidgetProvidersChangeListener listener = listeners.get(i); 9130 listener.onCrossProfileWidgetProvidersChanged(userId, packages); 9131 } 9132 } 9133 9134 @Override 9135 public Intent createShowAdminSupportIntent(int userId, boolean useDefaultIfNoAdmin) { 9136 // This method is called from AM with its lock held, so don't take the DPMS lock. 9137 // b/29242568 9138 9139 ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 9140 if (profileOwner != null) { 9141 return DevicePolicyManagerService.this 9142 .createShowAdminSupportIntent(profileOwner, userId); 9143 } 9144 9145 final Pair<Integer, ComponentName> deviceOwner = 9146 mOwners.getDeviceOwnerUserIdAndComponent(); 9147 if (deviceOwner != null && deviceOwner.first == userId) { 9148 return DevicePolicyManagerService.this 9149 .createShowAdminSupportIntent(deviceOwner.second, userId); 9150 } 9151 9152 // We're not specifying the device admin because there isn't one. 9153 if (useDefaultIfNoAdmin) { 9154 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 9155 } 9156 return null; 9157 } 9158 9159 @Override 9160 public Intent createUserRestrictionSupportIntent(int userId, String userRestriction) { 9161 int source; 9162 long ident = mInjector.binderClearCallingIdentity(); 9163 try { 9164 source = mUserManager.getUserRestrictionSource(userRestriction, 9165 UserHandle.of(userId)); 9166 } finally { 9167 mInjector.binderRestoreCallingIdentity(ident); 9168 } 9169 if ((source & UserManager.RESTRICTION_SOURCE_SYSTEM) != 0) { 9170 /* 9171 * In this case, the user restriction is enforced by the system. 9172 * So we won't show an admin support intent, even if it is also 9173 * enforced by a profile/device owner. 9174 */ 9175 return null; 9176 } 9177 boolean enforcedByDo = (source & UserManager.RESTRICTION_SOURCE_DEVICE_OWNER) != 0; 9178 boolean enforcedByPo = (source & UserManager.RESTRICTION_SOURCE_PROFILE_OWNER) != 0; 9179 if (enforcedByDo && enforcedByPo) { 9180 // In this case, we'll show an admin support dialog that does not 9181 // specify the admin. 9182 return DevicePolicyManagerService.this.createShowAdminSupportIntent(null, userId); 9183 } else if (enforcedByPo) { 9184 final ComponentName profileOwner = mOwners.getProfileOwnerComponent(userId); 9185 if (profileOwner != null) { 9186 return DevicePolicyManagerService.this 9187 .createShowAdminSupportIntent(profileOwner, userId); 9188 } 9189 // This could happen if another thread has changed the profile owner since we called 9190 // getUserRestrictionSource 9191 return null; 9192 } else if (enforcedByDo) { 9193 final Pair<Integer, ComponentName> deviceOwner 9194 = mOwners.getDeviceOwnerUserIdAndComponent(); 9195 if (deviceOwner != null) { 9196 return DevicePolicyManagerService.this 9197 .createShowAdminSupportIntent(deviceOwner.second, deviceOwner.first); 9198 } 9199 // This could happen if another thread has changed the device owner since we called 9200 // getUserRestrictionSource 9201 return null; 9202 } 9203 return null; 9204 } 9205 } 9206 9207 private Intent createShowAdminSupportIntent(ComponentName admin, int userId) { 9208 // This method is called with AMS lock held, so don't take DPMS lock 9209 final Intent intent = new Intent(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS); 9210 intent.putExtra(Intent.EXTRA_USER_ID, userId); 9211 intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin); 9212 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 9213 return intent; 9214 } 9215 9216 @Override 9217 public Intent createAdminSupportIntent(String restriction) { 9218 Preconditions.checkNotNull(restriction); 9219 final int uid = mInjector.binderGetCallingUid(); 9220 final int userId = UserHandle.getUserId(uid); 9221 Intent intent = null; 9222 if (DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction) || 9223 DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction)) { 9224 synchronized(this) { 9225 final DevicePolicyData policy = getUserData(userId); 9226 final int N = policy.mAdminList.size(); 9227 for (int i = 0; i < N; i++) { 9228 final ActiveAdmin admin = policy.mAdminList.get(i); 9229 if ((admin.disableCamera && 9230 DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) || 9231 (admin.disableScreenCapture && DevicePolicyManager 9232 .POLICY_DISABLE_SCREEN_CAPTURE.equals(restriction))) { 9233 intent = createShowAdminSupportIntent(admin.info.getComponent(), userId); 9234 break; 9235 } 9236 } 9237 // For the camera, a device owner on a different user can disable it globally, 9238 // so we need an additional check. 9239 if (intent == null 9240 && DevicePolicyManager.POLICY_DISABLE_CAMERA.equals(restriction)) { 9241 final ActiveAdmin admin = getDeviceOwnerAdminLocked(); 9242 if (admin != null && admin.disableCamera) { 9243 intent = createShowAdminSupportIntent(admin.info.getComponent(), 9244 mOwners.getDeviceOwnerUserId()); 9245 } 9246 } 9247 } 9248 } else { 9249 // if valid, |restriction| can only be a user restriction 9250 intent = mLocalService.createUserRestrictionSupportIntent(userId, restriction); 9251 } 9252 if (intent != null) { 9253 intent.putExtra(DevicePolicyManager.EXTRA_RESTRICTION, restriction); 9254 } 9255 return intent; 9256 } 9257 9258 /** 9259 * Returns true if specified admin is allowed to limit passwords and has a 9260 * {@code minimumPasswordMetrics.quality} of at least {@code minPasswordQuality} 9261 */ 9262 private static boolean isLimitPasswordAllowed(ActiveAdmin admin, int minPasswordQuality) { 9263 if (admin.minimumPasswordMetrics.quality < minPasswordQuality) { 9264 return false; 9265 } 9266 return admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 9267 } 9268 9269 @Override 9270 public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { 9271 if (policy != null && !policy.isValid()) { 9272 throw new IllegalArgumentException("Invalid system update policy."); 9273 } 9274 synchronized (this) { 9275 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9276 if (policy == null) { 9277 mOwners.clearSystemUpdatePolicy(); 9278 } else { 9279 mOwners.setSystemUpdatePolicy(policy); 9280 } 9281 mOwners.writeDeviceOwner(); 9282 } 9283 mContext.sendBroadcastAsUser( 9284 new Intent(DevicePolicyManager.ACTION_SYSTEM_UPDATE_POLICY_CHANGED), 9285 UserHandle.SYSTEM); 9286 } 9287 9288 @Override 9289 public SystemUpdatePolicy getSystemUpdatePolicy() { 9290 if (UserManager.isDeviceInDemoMode(mContext)) { 9291 // Pretending to have an automatic update policy when the device is in retail demo 9292 // mode. This will allow the device to download and install an ota without 9293 // any user interaction. 9294 return SystemUpdatePolicy.createAutomaticInstallPolicy(); 9295 } 9296 synchronized (this) { 9297 SystemUpdatePolicy policy = mOwners.getSystemUpdatePolicy(); 9298 if (policy != null && !policy.isValid()) { 9299 Slog.w(LOG_TAG, "Stored system update policy is invalid, return null instead."); 9300 return null; 9301 } 9302 return policy; 9303 } 9304 } 9305 9306 /** 9307 * Checks if the caller of the method is the device owner app. 9308 * 9309 * @param callerUid UID of the caller. 9310 * @return true if the caller is the device owner app 9311 */ 9312 @VisibleForTesting 9313 boolean isCallerDeviceOwner(int callerUid) { 9314 synchronized (this) { 9315 if (!mOwners.hasDeviceOwner()) { 9316 return false; 9317 } 9318 if (UserHandle.getUserId(callerUid) != mOwners.getDeviceOwnerUserId()) { 9319 return false; 9320 } 9321 final String deviceOwnerPackageName = mOwners.getDeviceOwnerComponent() 9322 .getPackageName(); 9323 try { 9324 String[] pkgs = mInjector.getIPackageManager().getPackagesForUid(callerUid); 9325 for (String pkg : pkgs) { 9326 if (deviceOwnerPackageName.equals(pkg)) { 9327 return true; 9328 } 9329 } 9330 } catch (RemoteException e) { 9331 return false; 9332 } 9333 } 9334 9335 return false; 9336 } 9337 9338 @Override 9339 public void notifyPendingSystemUpdate(@Nullable SystemUpdateInfo info) { 9340 mContext.enforceCallingOrSelfPermission(permission.NOTIFY_PENDING_SYSTEM_UPDATE, 9341 "Only the system update service can broadcast update information"); 9342 9343 if (UserHandle.getCallingUserId() != UserHandle.USER_SYSTEM) { 9344 Slog.w(LOG_TAG, "Only the system update service in the system user " + 9345 "can broadcast update information."); 9346 return; 9347 } 9348 9349 if (!mOwners.saveSystemUpdateInfo(info)) { 9350 // Pending system update hasn't changed, don't send duplicate notification. 9351 return; 9352 } 9353 9354 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_NOTIFY_PENDING_SYSTEM_UPDATE) 9355 .putExtra(DeviceAdminReceiver.EXTRA_SYSTEM_UPDATE_RECEIVED_TIME, 9356 info == null ? -1 : info.getReceivedTime()); 9357 9358 final long ident = mInjector.binderClearCallingIdentity(); 9359 try { 9360 synchronized (this) { 9361 // Broadcast to device owner first if there is one. 9362 if (mOwners.hasDeviceOwner()) { 9363 final UserHandle deviceOwnerUser = 9364 UserHandle.of(mOwners.getDeviceOwnerUserId()); 9365 intent.setComponent(mOwners.getDeviceOwnerComponent()); 9366 mContext.sendBroadcastAsUser(intent, deviceOwnerUser); 9367 } 9368 } 9369 // Get running users. 9370 final int runningUserIds[]; 9371 try { 9372 runningUserIds = mInjector.getIActivityManager().getRunningUserIds(); 9373 } catch (RemoteException e) { 9374 // Shouldn't happen. 9375 Log.e(LOG_TAG, "Could not retrieve the list of running users", e); 9376 return; 9377 } 9378 // Send broadcasts to corresponding profile owners if any. 9379 for (final int userId : runningUserIds) { 9380 synchronized (this) { 9381 final ComponentName profileOwnerPackage = 9382 mOwners.getProfileOwnerComponent(userId); 9383 if (profileOwnerPackage != null) { 9384 intent.setComponent(profileOwnerPackage); 9385 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId)); 9386 } 9387 } 9388 } 9389 } finally { 9390 mInjector.binderRestoreCallingIdentity(ident); 9391 } 9392 } 9393 9394 @Override 9395 public SystemUpdateInfo getPendingSystemUpdate(ComponentName admin) { 9396 Preconditions.checkNotNull(admin, "ComponentName is null"); 9397 enforceProfileOrDeviceOwner(admin); 9398 9399 return mOwners.getSystemUpdateInfo(); 9400 } 9401 9402 @Override 9403 public void setPermissionPolicy(ComponentName admin, String callerPackage, int policy) 9404 throws RemoteException { 9405 int userId = UserHandle.getCallingUserId(); 9406 synchronized (this) { 9407 // Ensure the caller is a DO/PO or a permission grant state delegate. 9408 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9409 DELEGATION_PERMISSION_GRANT); 9410 DevicePolicyData userPolicy = getUserData(userId); 9411 if (userPolicy.mPermissionPolicy != policy) { 9412 userPolicy.mPermissionPolicy = policy; 9413 saveSettingsLocked(userId); 9414 } 9415 } 9416 } 9417 9418 @Override 9419 public int getPermissionPolicy(ComponentName admin) throws RemoteException { 9420 int userId = UserHandle.getCallingUserId(); 9421 synchronized (this) { 9422 DevicePolicyData userPolicy = getUserData(userId); 9423 return userPolicy.mPermissionPolicy; 9424 } 9425 } 9426 9427 @Override 9428 public boolean setPermissionGrantState(ComponentName admin, String callerPackage, 9429 String packageName, String permission, int grantState) throws RemoteException { 9430 UserHandle user = mInjector.binderGetCallingUserHandle(); 9431 synchronized (this) { 9432 // Ensure the caller is a DO/PO or a permission grant state delegate. 9433 enforceCanManageScope(admin, callerPackage, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, 9434 DELEGATION_PERMISSION_GRANT); 9435 long ident = mInjector.binderClearCallingIdentity(); 9436 try { 9437 if (getTargetSdk(packageName, user.getIdentifier()) 9438 < android.os.Build.VERSION_CODES.M) { 9439 return false; 9440 } 9441 final PackageManager packageManager = mInjector.getPackageManager(); 9442 switch (grantState) { 9443 case DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED: { 9444 mInjector.getPackageManagerInternal().grantRuntimePermission(packageName, 9445 permission, user.getIdentifier(), true /* override policy */); 9446 packageManager.updatePermissionFlags(permission, packageName, 9447 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 9448 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 9449 } break; 9450 9451 case DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED: { 9452 mInjector.getPackageManagerInternal().revokeRuntimePermission(packageName, 9453 permission, user.getIdentifier(), true /* override policy */); 9454 packageManager.updatePermissionFlags(permission, packageName, 9455 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 9456 PackageManager.FLAG_PERMISSION_POLICY_FIXED, user); 9457 } break; 9458 9459 case DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT: { 9460 packageManager.updatePermissionFlags(permission, packageName, 9461 PackageManager.FLAG_PERMISSION_POLICY_FIXED, 0, user); 9462 } break; 9463 } 9464 return true; 9465 } catch (SecurityException se) { 9466 return false; 9467 } finally { 9468 mInjector.binderRestoreCallingIdentity(ident); 9469 } 9470 } 9471 } 9472 9473 @Override 9474 public int getPermissionGrantState(ComponentName admin, String callerPackage, 9475 String packageName, String permission) throws RemoteException { 9476 PackageManager packageManager = mInjector.getPackageManager(); 9477 9478 UserHandle user = mInjector.binderGetCallingUserHandle(); 9479 if (!isCallerWithSystemUid()) { 9480 // Ensure the caller is a DO/PO or a permission grant state delegate. 9481 enforceCanManageScope(admin, callerPackage, 9482 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER, DELEGATION_PERMISSION_GRANT); 9483 } 9484 synchronized (this) { 9485 long ident = mInjector.binderClearCallingIdentity(); 9486 try { 9487 int granted = mIPackageManager.checkPermission(permission, 9488 packageName, user.getIdentifier()); 9489 int permFlags = packageManager.getPermissionFlags(permission, packageName, user); 9490 if ((permFlags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) 9491 != PackageManager.FLAG_PERMISSION_POLICY_FIXED) { 9492 // Not controlled by policy 9493 return DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT; 9494 } else { 9495 // Policy controlled so return result based on permission grant state 9496 return granted == PackageManager.PERMISSION_GRANTED 9497 ? DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED 9498 : DevicePolicyManager.PERMISSION_GRANT_STATE_DENIED; 9499 } 9500 } finally { 9501 mInjector.binderRestoreCallingIdentity(ident); 9502 } 9503 } 9504 } 9505 9506 boolean isPackageInstalledForUser(String packageName, int userHandle) { 9507 try { 9508 PackageInfo pi = mInjector.getIPackageManager().getPackageInfo(packageName, 0, 9509 userHandle); 9510 return (pi != null) && (pi.applicationInfo.flags != 0); 9511 } catch (RemoteException re) { 9512 throw new RuntimeException("Package manager has died", re); 9513 } 9514 } 9515 9516 @Override 9517 public boolean isProvisioningAllowed(String action, String packageName) { 9518 Preconditions.checkNotNull(packageName); 9519 9520 final int callingUid = mInjector.binderGetCallingUid(); 9521 final long ident = mInjector.binderClearCallingIdentity(); 9522 try { 9523 final int uidForPackage = mInjector.getPackageManager().getPackageUidAsUser( 9524 packageName, UserHandle.getUserId(callingUid)); 9525 Preconditions.checkArgument(callingUid == uidForPackage, 9526 "Caller uid doesn't match the one for the provided package."); 9527 } catch (NameNotFoundException e) { 9528 throw new IllegalArgumentException("Invalid package provided " + packageName, e); 9529 } finally { 9530 mInjector.binderRestoreCallingIdentity(ident); 9531 } 9532 9533 return checkProvisioningPreConditionSkipPermission(action, packageName) == CODE_OK; 9534 } 9535 9536 @Override 9537 public int checkProvisioningPreCondition(String action, String packageName) { 9538 Preconditions.checkNotNull(packageName); 9539 enforceCanManageProfileAndDeviceOwners(); 9540 return checkProvisioningPreConditionSkipPermission(action, packageName); 9541 } 9542 9543 private int checkProvisioningPreConditionSkipPermission(String action, String packageName) { 9544 if (!mHasFeature) { 9545 return CODE_DEVICE_ADMIN_NOT_SUPPORTED; 9546 } 9547 9548 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9549 if (action != null) { 9550 switch (action) { 9551 case DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE: 9552 return checkManagedProfileProvisioningPreCondition(packageName, callingUserId); 9553 case DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE: 9554 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9555 case DevicePolicyManager.ACTION_PROVISION_MANAGED_USER: 9556 return checkManagedUserProvisioningPreCondition(callingUserId); 9557 case DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE: 9558 return checkManagedShareableDeviceProvisioningPreCondition(callingUserId); 9559 } 9560 } 9561 throw new IllegalArgumentException("Unknown provisioning action " + action); 9562 } 9563 9564 /** 9565 * The device owner can only be set before the setup phase of the primary user has completed, 9566 * except for adb command if no accounts or additional users are present on the device. 9567 */ 9568 private int checkDeviceOwnerProvisioningPreConditionLocked(@Nullable ComponentName owner, 9569 int deviceOwnerUserId, boolean isAdb, boolean hasIncompatibleAccountsOrNonAdb) { 9570 if (mOwners.hasDeviceOwner()) { 9571 return CODE_HAS_DEVICE_OWNER; 9572 } 9573 if (mOwners.hasProfileOwner(deviceOwnerUserId)) { 9574 return CODE_USER_HAS_PROFILE_OWNER; 9575 } 9576 if (!mUserManager.isUserRunning(new UserHandle(deviceOwnerUserId))) { 9577 return CODE_USER_NOT_RUNNING; 9578 } 9579 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9580 return CODE_HAS_PAIRED; 9581 } 9582 if (isAdb) { 9583 // if shell command runs after user setup completed check device status. Otherwise, OK. 9584 if (mIsWatch || hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 9585 if (!mInjector.userManagerIsSplitSystemUser()) { 9586 if (mUserManager.getUserCount() > 1) { 9587 return CODE_NONSYSTEM_USER_EXISTS; 9588 } 9589 if (hasIncompatibleAccountsOrNonAdb) { 9590 return CODE_ACCOUNTS_NOT_EMPTY; 9591 } 9592 } else { 9593 // STOPSHIP Do proper check in split user mode 9594 } 9595 } 9596 return CODE_OK; 9597 } else { 9598 if (!mInjector.userManagerIsSplitSystemUser()) { 9599 // In non-split user mode, DO has to be user 0 9600 if (deviceOwnerUserId != UserHandle.USER_SYSTEM) { 9601 return CODE_NOT_SYSTEM_USER; 9602 } 9603 // In non-split user mode, only provision DO before setup wizard completes 9604 if (hasUserSetupCompleted(UserHandle.USER_SYSTEM)) { 9605 return CODE_USER_SETUP_COMPLETED; 9606 } 9607 } else { 9608 // STOPSHIP Do proper check in split user mode 9609 } 9610 return CODE_OK; 9611 } 9612 } 9613 9614 private int checkDeviceOwnerProvisioningPreCondition(int deviceOwnerUserId) { 9615 synchronized (this) { 9616 // hasIncompatibleAccountsOrNonAdb doesn't matter since the caller is not adb. 9617 return checkDeviceOwnerProvisioningPreConditionLocked(/* owner unknown */ null, 9618 deviceOwnerUserId, /* isAdb= */ false, 9619 /* hasIncompatibleAccountsOrNonAdb=*/ true); 9620 } 9621 } 9622 9623 private int checkManagedProfileProvisioningPreCondition(String packageName, int callingUserId) { 9624 if (!hasFeatureManagedUsers()) { 9625 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9626 } 9627 if (callingUserId == UserHandle.USER_SYSTEM 9628 && mInjector.userManagerIsSplitSystemUser()) { 9629 // Managed-profiles cannot be setup on the system user. 9630 return CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER; 9631 } 9632 if (getProfileOwner(callingUserId) != null) { 9633 // Managed user cannot have a managed profile. 9634 return CODE_USER_HAS_PROFILE_OWNER; 9635 } 9636 9637 final long ident = mInjector.binderClearCallingIdentity(); 9638 try { 9639 final UserHandle callingUserHandle = UserHandle.of(callingUserId); 9640 final ComponentName ownerAdmin = getOwnerComponent(packageName, callingUserId); 9641 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_ADD_MANAGED_PROFILE, 9642 callingUserHandle)) { 9643 // An admin can initiate provisioning if it has set the restriction. 9644 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 9645 UserManager.DISALLOW_ADD_MANAGED_PROFILE, callingUserId)) { 9646 return CODE_ADD_MANAGED_PROFILE_DISALLOWED; 9647 } 9648 } 9649 boolean canRemoveProfile = true; 9650 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 9651 callingUserHandle)) { 9652 // We can remove a profile if the admin itself has set the restriction. 9653 if (ownerAdmin == null || isAdminAffectedByRestriction(ownerAdmin, 9654 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE, 9655 callingUserId)) { 9656 canRemoveProfile = false; 9657 } 9658 } 9659 if (!mUserManager.canAddMoreManagedProfiles(callingUserId, canRemoveProfile)) { 9660 return CODE_CANNOT_ADD_MANAGED_PROFILE; 9661 } 9662 } finally { 9663 mInjector.binderRestoreCallingIdentity(ident); 9664 } 9665 return CODE_OK; 9666 } 9667 9668 private ComponentName getOwnerComponent(String packageName, int userId) { 9669 if (isDeviceOwnerPackage(packageName, userId)) { 9670 return mOwners.getDeviceOwnerComponent(); 9671 } 9672 if (isProfileOwnerPackage(packageName, userId)) { 9673 return mOwners.getProfileOwnerComponent(userId); 9674 } 9675 return null; 9676 } 9677 9678 /** 9679 * Return device owner or profile owner set on a given user. 9680 */ 9681 private @Nullable ComponentName getOwnerComponent(int userId) { 9682 synchronized (this) { 9683 if (mOwners.getDeviceOwnerUserId() == userId) { 9684 return mOwners.getDeviceOwnerComponent(); 9685 } 9686 if (mOwners.hasProfileOwner(userId)) { 9687 return mOwners.getProfileOwnerComponent(userId); 9688 } 9689 } 9690 return null; 9691 } 9692 9693 private int checkManagedUserProvisioningPreCondition(int callingUserId) { 9694 if (!hasFeatureManagedUsers()) { 9695 return CODE_MANAGED_USERS_NOT_SUPPORTED; 9696 } 9697 if (!mInjector.userManagerIsSplitSystemUser()) { 9698 // ACTION_PROVISION_MANAGED_USER only supported on split-user systems. 9699 return CODE_NOT_SYSTEM_USER_SPLIT; 9700 } 9701 if (callingUserId == UserHandle.USER_SYSTEM) { 9702 // System user cannot be a managed user. 9703 return CODE_SYSTEM_USER; 9704 } 9705 if (hasUserSetupCompleted(callingUserId)) { 9706 return CODE_USER_SETUP_COMPLETED; 9707 } 9708 if (mIsWatch && hasPaired(UserHandle.USER_SYSTEM)) { 9709 return CODE_HAS_PAIRED; 9710 } 9711 return CODE_OK; 9712 } 9713 9714 private int checkManagedShareableDeviceProvisioningPreCondition(int callingUserId) { 9715 if (!mInjector.userManagerIsSplitSystemUser()) { 9716 // ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE only supported on split-user systems. 9717 return CODE_NOT_SYSTEM_USER_SPLIT; 9718 } 9719 return checkDeviceOwnerProvisioningPreCondition(callingUserId); 9720 } 9721 9722 private boolean hasFeatureManagedUsers() { 9723 try { 9724 return mIPackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0); 9725 } catch (RemoteException e) { 9726 return false; 9727 } 9728 } 9729 9730 @Override 9731 public String getWifiMacAddress(ComponentName admin) { 9732 // Make sure caller has DO. 9733 synchronized (this) { 9734 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9735 } 9736 9737 final long ident = mInjector.binderClearCallingIdentity(); 9738 try { 9739 final WifiInfo wifiInfo = mInjector.getWifiManager().getConnectionInfo(); 9740 if (wifiInfo == null) { 9741 return null; 9742 } 9743 return wifiInfo.hasRealMacAddress() ? wifiInfo.getMacAddress() : null; 9744 } finally { 9745 mInjector.binderRestoreCallingIdentity(ident); 9746 } 9747 } 9748 9749 /** 9750 * Returns the target sdk version number that the given packageName was built for 9751 * in the given user. 9752 */ 9753 private int getTargetSdk(String packageName, int userId) { 9754 final ApplicationInfo ai; 9755 try { 9756 ai = mIPackageManager.getApplicationInfo(packageName, 0, userId); 9757 final int targetSdkVersion = ai == null ? 0 : ai.targetSdkVersion; 9758 return targetSdkVersion; 9759 } catch (RemoteException e) { 9760 // Shouldn't happen 9761 return 0; 9762 } 9763 } 9764 9765 @Override 9766 public boolean isManagedProfile(ComponentName admin) { 9767 enforceProfileOrDeviceOwner(admin); 9768 return isManagedProfile(mInjector.userHandleGetCallingUserId()); 9769 } 9770 9771 @Override 9772 public boolean isSystemOnlyUser(ComponentName admin) { 9773 synchronized (this) { 9774 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9775 } 9776 final int callingUserId = mInjector.userHandleGetCallingUserId(); 9777 return UserManager.isSplitSystemUser() && callingUserId == UserHandle.USER_SYSTEM; 9778 } 9779 9780 @Override 9781 public void reboot(ComponentName admin) { 9782 Preconditions.checkNotNull(admin); 9783 // Make sure caller has DO. 9784 synchronized (this) { 9785 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 9786 } 9787 long ident = mInjector.binderClearCallingIdentity(); 9788 try { 9789 // Make sure there are no ongoing calls on the device. 9790 if (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE) { 9791 throw new IllegalStateException("Cannot be called with ongoing call on the device"); 9792 } 9793 mInjector.powerManagerReboot(PowerManager.REBOOT_REQUESTED_BY_DEVICE_OWNER); 9794 } finally { 9795 mInjector.binderRestoreCallingIdentity(ident); 9796 } 9797 } 9798 9799 @Override 9800 public void setShortSupportMessage(@NonNull ComponentName who, CharSequence message) { 9801 if (!mHasFeature) { 9802 return; 9803 } 9804 Preconditions.checkNotNull(who, "ComponentName is null"); 9805 final int userHandle = mInjector.userHandleGetCallingUserId(); 9806 synchronized (this) { 9807 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9808 mInjector.binderGetCallingUid()); 9809 if (!TextUtils.equals(admin.shortSupportMessage, message)) { 9810 admin.shortSupportMessage = message; 9811 saveSettingsLocked(userHandle); 9812 } 9813 } 9814 } 9815 9816 @Override 9817 public CharSequence getShortSupportMessage(@NonNull ComponentName who) { 9818 if (!mHasFeature) { 9819 return null; 9820 } 9821 Preconditions.checkNotNull(who, "ComponentName is null"); 9822 synchronized (this) { 9823 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9824 mInjector.binderGetCallingUid()); 9825 return admin.shortSupportMessage; 9826 } 9827 } 9828 9829 @Override 9830 public void setLongSupportMessage(@NonNull ComponentName who, CharSequence message) { 9831 if (!mHasFeature) { 9832 return; 9833 } 9834 Preconditions.checkNotNull(who, "ComponentName is null"); 9835 final int userHandle = mInjector.userHandleGetCallingUserId(); 9836 synchronized (this) { 9837 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9838 mInjector.binderGetCallingUid()); 9839 if (!TextUtils.equals(admin.longSupportMessage, message)) { 9840 admin.longSupportMessage = message; 9841 saveSettingsLocked(userHandle); 9842 } 9843 } 9844 } 9845 9846 @Override 9847 public CharSequence getLongSupportMessage(@NonNull ComponentName who) { 9848 if (!mHasFeature) { 9849 return null; 9850 } 9851 Preconditions.checkNotNull(who, "ComponentName is null"); 9852 synchronized (this) { 9853 ActiveAdmin admin = getActiveAdminForUidLocked(who, 9854 mInjector.binderGetCallingUid()); 9855 return admin.longSupportMessage; 9856 } 9857 } 9858 9859 @Override 9860 public CharSequence getShortSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9861 if (!mHasFeature) { 9862 return null; 9863 } 9864 Preconditions.checkNotNull(who, "ComponentName is null"); 9865 if (!isCallerWithSystemUid()) { 9866 throw new SecurityException("Only the system can query support message for user"); 9867 } 9868 synchronized (this) { 9869 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9870 if (admin != null) { 9871 return admin.shortSupportMessage; 9872 } 9873 } 9874 return null; 9875 } 9876 9877 @Override 9878 public CharSequence getLongSupportMessageForUser(@NonNull ComponentName who, int userHandle) { 9879 if (!mHasFeature) { 9880 return null; 9881 } 9882 Preconditions.checkNotNull(who, "ComponentName is null"); 9883 if (!isCallerWithSystemUid()) { 9884 throw new SecurityException("Only the system can query support message for user"); 9885 } 9886 synchronized (this) { 9887 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 9888 if (admin != null) { 9889 return admin.longSupportMessage; 9890 } 9891 } 9892 return null; 9893 } 9894 9895 @Override 9896 public void setOrganizationColor(@NonNull ComponentName who, int color) { 9897 if (!mHasFeature) { 9898 return; 9899 } 9900 Preconditions.checkNotNull(who, "ComponentName is null"); 9901 final int userHandle = mInjector.userHandleGetCallingUserId(); 9902 enforceManagedProfile(userHandle, "set organization color"); 9903 synchronized (this) { 9904 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9905 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9906 admin.organizationColor = color; 9907 saveSettingsLocked(userHandle); 9908 } 9909 } 9910 9911 @Override 9912 public void setOrganizationColorForUser(int color, int userId) { 9913 if (!mHasFeature) { 9914 return; 9915 } 9916 enforceFullCrossUsersPermission(userId); 9917 enforceManageUsers(); 9918 enforceManagedProfile(userId, "set organization color"); 9919 synchronized (this) { 9920 ActiveAdmin admin = getProfileOwnerAdminLocked(userId); 9921 admin.organizationColor = color; 9922 saveSettingsLocked(userId); 9923 } 9924 } 9925 9926 @Override 9927 public int getOrganizationColor(@NonNull ComponentName who) { 9928 if (!mHasFeature) { 9929 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9930 } 9931 Preconditions.checkNotNull(who, "ComponentName is null"); 9932 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization color"); 9933 synchronized (this) { 9934 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9935 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9936 return admin.organizationColor; 9937 } 9938 } 9939 9940 @Override 9941 public int getOrganizationColorForUser(int userHandle) { 9942 if (!mHasFeature) { 9943 return ActiveAdmin.DEF_ORGANIZATION_COLOR; 9944 } 9945 enforceFullCrossUsersPermission(userHandle); 9946 enforceManagedProfile(userHandle, "get organization color"); 9947 synchronized (this) { 9948 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 9949 return (profileOwner != null) 9950 ? profileOwner.organizationColor 9951 : ActiveAdmin.DEF_ORGANIZATION_COLOR; 9952 } 9953 } 9954 9955 @Override 9956 public void setOrganizationName(@NonNull ComponentName who, CharSequence text) { 9957 if (!mHasFeature) { 9958 return; 9959 } 9960 Preconditions.checkNotNull(who, "ComponentName is null"); 9961 final int userHandle = mInjector.userHandleGetCallingUserId(); 9962 9963 synchronized (this) { 9964 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9965 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9966 if (!TextUtils.equals(admin.organizationName, text)) { 9967 admin.organizationName = (text == null || text.length() == 0) 9968 ? null : text.toString(); 9969 saveSettingsLocked(userHandle); 9970 } 9971 } 9972 } 9973 9974 @Override 9975 public CharSequence getOrganizationName(@NonNull ComponentName who) { 9976 if (!mHasFeature) { 9977 return null; 9978 } 9979 Preconditions.checkNotNull(who, "ComponentName is null"); 9980 enforceManagedProfile(mInjector.userHandleGetCallingUserId(), "get organization name"); 9981 synchronized(this) { 9982 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 9983 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 9984 return admin.organizationName; 9985 } 9986 } 9987 9988 @Override 9989 public CharSequence getDeviceOwnerOrganizationName() { 9990 if (!mHasFeature) { 9991 return null; 9992 } 9993 enforceDeviceOwnerOrManageUsers(); 9994 synchronized(this) { 9995 final ActiveAdmin deviceOwnerAdmin = getDeviceOwnerAdminLocked(); 9996 return deviceOwnerAdmin == null ? null : deviceOwnerAdmin.organizationName; 9997 } 9998 } 9999 10000 @Override 10001 public CharSequence getOrganizationNameForUser(int userHandle) { 10002 if (!mHasFeature) { 10003 return null; 10004 } 10005 enforceFullCrossUsersPermission(userHandle); 10006 enforceManagedProfile(userHandle, "get organization name"); 10007 synchronized (this) { 10008 ActiveAdmin profileOwner = getProfileOwnerAdminLocked(userHandle); 10009 return (profileOwner != null) 10010 ? profileOwner.organizationName 10011 : null; 10012 } 10013 } 10014 10015 @Override 10016 public void setAffiliationIds(ComponentName admin, List<String> ids) { 10017 if (!mHasFeature) { 10018 return; 10019 } 10020 if (ids == null) { 10021 throw new IllegalArgumentException("ids must not be null"); 10022 } 10023 for (String id : ids) { 10024 if (TextUtils.isEmpty(id)) { 10025 throw new IllegalArgumentException("ids must not contain empty string"); 10026 } 10027 } 10028 10029 final Set<String> affiliationIds = new ArraySet<>(ids); 10030 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10031 synchronized (this) { 10032 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10033 getUserData(callingUserId).mAffiliationIds = affiliationIds; 10034 saveSettingsLocked(callingUserId); 10035 if (callingUserId != UserHandle.USER_SYSTEM && isDeviceOwner(admin, callingUserId)) { 10036 // Affiliation ids specified by the device owner are additionally stored in 10037 // UserHandle.USER_SYSTEM's DevicePolicyData. 10038 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds = affiliationIds; 10039 saveSettingsLocked(UserHandle.USER_SYSTEM); 10040 } 10041 10042 // Affiliation status for any user, not just the calling user, might have changed. 10043 // The device owner user will still be affiliated after changing its affiliation ids, 10044 // but as a result of that other users might become affiliated or un-affiliated. 10045 maybePauseDeviceWideLoggingLocked(); 10046 maybeResumeDeviceWideLoggingLocked(); 10047 maybeClearLockTaskPackagesLocked(); 10048 } 10049 } 10050 10051 @Override 10052 public List<String> getAffiliationIds(ComponentName admin) { 10053 if (!mHasFeature) { 10054 return Collections.emptyList(); 10055 } 10056 10057 Preconditions.checkNotNull(admin); 10058 synchronized (this) { 10059 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10060 return new ArrayList<String>( 10061 getUserData(mInjector.userHandleGetCallingUserId()).mAffiliationIds); 10062 } 10063 } 10064 10065 @Override 10066 public boolean isAffiliatedUser() { 10067 if (!mHasFeature) { 10068 return false; 10069 } 10070 10071 synchronized (this) { 10072 return isUserAffiliatedWithDeviceLocked(mInjector.userHandleGetCallingUserId()); 10073 } 10074 } 10075 10076 private boolean isUserAffiliatedWithDeviceLocked(int userId) { 10077 if (!mOwners.hasDeviceOwner()) { 10078 return false; 10079 } 10080 if (userId == mOwners.getDeviceOwnerUserId()) { 10081 // The user that the DO is installed on is always affiliated with the device. 10082 return true; 10083 } 10084 if (userId == UserHandle.USER_SYSTEM) { 10085 // The system user is always affiliated in a DO device, even if the DO is set on a 10086 // different user. This could be the case if the DO is set in the primary user 10087 // of a split user device. 10088 return true; 10089 } 10090 final ComponentName profileOwner = getProfileOwner(userId); 10091 if (profileOwner == null) { 10092 return false; 10093 } 10094 final Set<String> userAffiliationIds = getUserData(userId).mAffiliationIds; 10095 final Set<String> deviceAffiliationIds = 10096 getUserData(UserHandle.USER_SYSTEM).mAffiliationIds; 10097 for (String id : userAffiliationIds) { 10098 if (deviceAffiliationIds.contains(id)) { 10099 return true; 10100 } 10101 } 10102 return false; 10103 } 10104 10105 private boolean areAllUsersAffiliatedWithDeviceLocked() { 10106 final long ident = mInjector.binderClearCallingIdentity(); 10107 try { 10108 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 10109 for (int i = 0; i < userInfos.size(); i++) { 10110 int userId = userInfos.get(i).id; 10111 if (!isUserAffiliatedWithDeviceLocked(userId)) { 10112 Slog.d(LOG_TAG, "User id " + userId + " not affiliated."); 10113 return false; 10114 } 10115 } 10116 } finally { 10117 mInjector.binderRestoreCallingIdentity(ident); 10118 } 10119 10120 return true; 10121 } 10122 10123 @Override 10124 public void setSecurityLoggingEnabled(ComponentName admin, boolean enabled) { 10125 if (!mHasFeature) { 10126 return; 10127 } 10128 Preconditions.checkNotNull(admin); 10129 10130 synchronized (this) { 10131 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10132 if (enabled == mInjector.securityLogGetLoggingEnabledProperty()) { 10133 return; 10134 } 10135 mInjector.securityLogSetLoggingEnabledProperty(enabled); 10136 if (enabled) { 10137 mSecurityLogMonitor.start(); 10138 maybePauseDeviceWideLoggingLocked(); 10139 } else { 10140 mSecurityLogMonitor.stop(); 10141 } 10142 } 10143 } 10144 10145 @Override 10146 public boolean isSecurityLoggingEnabled(ComponentName admin) { 10147 if (!mHasFeature) { 10148 return false; 10149 } 10150 10151 synchronized (this) { 10152 if (!isCallerWithSystemUid()) { 10153 Preconditions.checkNotNull(admin); 10154 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10155 } 10156 return mInjector.securityLogGetLoggingEnabledProperty(); 10157 } 10158 } 10159 10160 private synchronized void recordSecurityLogRetrievalTime() { 10161 final long currentTime = System.currentTimeMillis(); 10162 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10163 if (currentTime > policyData.mLastSecurityLogRetrievalTime) { 10164 policyData.mLastSecurityLogRetrievalTime = currentTime; 10165 saveSettingsLocked(UserHandle.USER_SYSTEM); 10166 } 10167 } 10168 10169 @Override 10170 public ParceledListSlice<SecurityEvent> retrievePreRebootSecurityLogs(ComponentName admin) { 10171 if (!mHasFeature) { 10172 return null; 10173 } 10174 10175 Preconditions.checkNotNull(admin); 10176 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10177 10178 if (!mContext.getResources().getBoolean(R.bool.config_supportPreRebootSecurityLogs) 10179 || !mInjector.securityLogGetLoggingEnabledProperty()) { 10180 return null; 10181 } 10182 10183 recordSecurityLogRetrievalTime(); 10184 10185 ArrayList<SecurityEvent> output = new ArrayList<SecurityEvent>(); 10186 try { 10187 SecurityLog.readPreviousEvents(output); 10188 return new ParceledListSlice<SecurityEvent>(output); 10189 } catch (IOException e) { 10190 Slog.w(LOG_TAG, "Fail to read previous events" , e); 10191 return new ParceledListSlice<SecurityEvent>(Collections.<SecurityEvent>emptyList()); 10192 } 10193 } 10194 10195 @Override 10196 public ParceledListSlice<SecurityEvent> retrieveSecurityLogs(ComponentName admin) { 10197 if (!mHasFeature) { 10198 return null; 10199 } 10200 10201 Preconditions.checkNotNull(admin); 10202 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10203 10204 if (!mInjector.securityLogGetLoggingEnabledProperty()) { 10205 return null; 10206 } 10207 10208 recordSecurityLogRetrievalTime(); 10209 10210 List<SecurityEvent> logs = mSecurityLogMonitor.retrieveLogs(); 10211 return logs != null ? new ParceledListSlice<SecurityEvent>(logs) : null; 10212 } 10213 10214 private void enforceCanManageDeviceAdmin() { 10215 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_DEVICE_ADMINS, 10216 null); 10217 } 10218 10219 private void enforceCanManageProfileAndDeviceOwners() { 10220 mContext.enforceCallingOrSelfPermission( 10221 android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS, null); 10222 } 10223 10224 private void enforceCallerSystemUserHandle() { 10225 final int callingUid = mInjector.binderGetCallingUid(); 10226 final int userId = UserHandle.getUserId(callingUid); 10227 if (userId != UserHandle.USER_SYSTEM) { 10228 throw new SecurityException("Caller has to be in user 0"); 10229 } 10230 } 10231 10232 @Override 10233 public boolean isUninstallInQueue(final String packageName) { 10234 enforceCanManageDeviceAdmin(); 10235 final int userId = mInjector.userHandleGetCallingUserId(); 10236 Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10237 synchronized (this) { 10238 return mPackagesToRemove.contains(packageUserPair); 10239 } 10240 } 10241 10242 @Override 10243 public void uninstallPackageWithActiveAdmins(final String packageName) { 10244 enforceCanManageDeviceAdmin(); 10245 Preconditions.checkArgument(!TextUtils.isEmpty(packageName)); 10246 10247 final int userId = mInjector.userHandleGetCallingUserId(); 10248 10249 enforceUserUnlocked(userId); 10250 10251 final ComponentName profileOwner = getProfileOwner(userId); 10252 if (profileOwner != null && packageName.equals(profileOwner.getPackageName())) { 10253 throw new IllegalArgumentException("Cannot uninstall a package with a profile owner"); 10254 } 10255 10256 final ComponentName deviceOwner = getDeviceOwnerComponent(/* callingUserOnly= */ false); 10257 if (getDeviceOwnerUserId() == userId && deviceOwner != null 10258 && packageName.equals(deviceOwner.getPackageName())) { 10259 throw new IllegalArgumentException("Cannot uninstall a package with a device owner"); 10260 } 10261 10262 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10263 synchronized (this) { 10264 mPackagesToRemove.add(packageUserPair); 10265 } 10266 10267 // All active admins on the user. 10268 final List<ComponentName> allActiveAdmins = getActiveAdmins(userId); 10269 10270 // Active admins in the target package. 10271 final List<ComponentName> packageActiveAdmins = new ArrayList<>(); 10272 if (allActiveAdmins != null) { 10273 for (ComponentName activeAdmin : allActiveAdmins) { 10274 if (packageName.equals(activeAdmin.getPackageName())) { 10275 packageActiveAdmins.add(activeAdmin); 10276 removeActiveAdmin(activeAdmin, userId); 10277 } 10278 } 10279 } 10280 if (packageActiveAdmins.size() == 0) { 10281 startUninstallIntent(packageName, userId); 10282 } else { 10283 mHandler.postDelayed(new Runnable() { 10284 @Override 10285 public void run() { 10286 for (ComponentName activeAdmin : packageActiveAdmins) { 10287 removeAdminArtifacts(activeAdmin, userId); 10288 } 10289 startUninstallIntent(packageName, userId); 10290 } 10291 }, DEVICE_ADMIN_DEACTIVATE_TIMEOUT); // Start uninstall after timeout anyway. 10292 } 10293 } 10294 10295 @Override 10296 public boolean isDeviceProvisioned() { 10297 synchronized (this) { 10298 return getUserDataUnchecked(UserHandle.USER_SYSTEM).mUserSetupComplete; 10299 } 10300 } 10301 10302 private void removePackageIfRequired(final String packageName, final int userId) { 10303 if (!packageHasActiveAdmins(packageName, userId)) { 10304 // Will not do anything if uninstall was not requested or was already started. 10305 startUninstallIntent(packageName, userId); 10306 } 10307 } 10308 10309 private void startUninstallIntent(final String packageName, final int userId) { 10310 final Pair<String, Integer> packageUserPair = new Pair<>(packageName, userId); 10311 synchronized (this) { 10312 if (!mPackagesToRemove.contains(packageUserPair)) { 10313 // Do nothing if uninstall was not requested or was already started. 10314 return; 10315 } 10316 mPackagesToRemove.remove(packageUserPair); 10317 } 10318 try { 10319 if (mInjector.getIPackageManager().getPackageInfo(packageName, 0, userId) == null) { 10320 // Package does not exist. Nothing to do. 10321 return; 10322 } 10323 } catch (RemoteException re) { 10324 Log.e(LOG_TAG, "Failure talking to PackageManager while getting package info"); 10325 } 10326 10327 try { // force stop the package before uninstalling 10328 mInjector.getIActivityManager().forceStopPackage(packageName, userId); 10329 } catch (RemoteException re) { 10330 Log.e(LOG_TAG, "Failure talking to ActivityManager while force stopping package"); 10331 } 10332 final Uri packageURI = Uri.parse("package:" + packageName); 10333 final Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI); 10334 uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 10335 mContext.startActivityAsUser(uninstallIntent, UserHandle.of(userId)); 10336 } 10337 10338 /** 10339 * Removes the admin from the policy. Ideally called after the admin's 10340 * {@link DeviceAdminReceiver#onDisabled(Context, Intent)} has been successfully completed. 10341 * 10342 * @param adminReceiver The admin to remove 10343 * @param userHandle The user for which this admin has to be removed. 10344 */ 10345 private void removeAdminArtifacts(final ComponentName adminReceiver, final int userHandle) { 10346 synchronized (this) { 10347 final ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 10348 if (admin == null) { 10349 return; 10350 } 10351 final DevicePolicyData policy = getUserData(userHandle); 10352 final boolean doProxyCleanup = admin.info.usesPolicy( 10353 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 10354 policy.mAdminList.remove(admin); 10355 policy.mAdminMap.remove(adminReceiver); 10356 validatePasswordOwnerLocked(policy); 10357 if (doProxyCleanup) { 10358 resetGlobalProxyLocked(policy); 10359 } 10360 saveSettingsLocked(userHandle); 10361 updateMaximumTimeToLockLocked(userHandle); 10362 policy.mRemovingAdmins.remove(adminReceiver); 10363 10364 Slog.i(LOG_TAG, "Device admin " + adminReceiver + " removed from user " + userHandle); 10365 } 10366 // The removed admin might have disabled camera, so update user 10367 // restrictions. 10368 pushUserRestrictions(userHandle); 10369 } 10370 10371 @Override 10372 public void setDeviceProvisioningConfigApplied() { 10373 enforceManageUsers(); 10374 synchronized (this) { 10375 DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 10376 policy.mDeviceProvisioningConfigApplied = true; 10377 saveSettingsLocked(UserHandle.USER_SYSTEM); 10378 } 10379 } 10380 10381 @Override 10382 public boolean isDeviceProvisioningConfigApplied() { 10383 enforceManageUsers(); 10384 synchronized (this) { 10385 final DevicePolicyData policy = getUserData(UserHandle.USER_SYSTEM); 10386 return policy.mDeviceProvisioningConfigApplied; 10387 } 10388 } 10389 10390 /** 10391 * Force update internal persistent state from Settings.Secure.USER_SETUP_COMPLETE. 10392 * 10393 * It's added for testing only. Please use this API carefully if it's used by other system app 10394 * and bare in mind Settings.Secure.USER_SETUP_COMPLETE can be modified by user and other system 10395 * apps. 10396 */ 10397 @Override 10398 public void forceUpdateUserSetupComplete() { 10399 enforceCanManageProfileAndDeviceOwners(); 10400 enforceCallerSystemUserHandle(); 10401 // no effect if it's called from user build 10402 if (!mInjector.isBuildDebuggable()) { 10403 return; 10404 } 10405 final int userId = UserHandle.USER_SYSTEM; 10406 boolean isUserCompleted = mInjector.settingsSecureGetIntForUser( 10407 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) != 0; 10408 DevicePolicyData policy = getUserData(userId); 10409 policy.mUserSetupComplete = isUserCompleted; 10410 synchronized (this) { 10411 saveSettingsLocked(userId); 10412 } 10413 } 10414 10415 // TODO(b/22388012): When backup is available for secondary users and profiles, consider 10416 // whether there are any privacy/security implications of enabling the backup service here 10417 // if there are other users or profiles unmanaged or managed by a different entity (i.e. not 10418 // affiliated). 10419 @Override 10420 public void setBackupServiceEnabled(ComponentName admin, boolean enabled) { 10421 if (!mHasFeature) { 10422 return; 10423 } 10424 Preconditions.checkNotNull(admin); 10425 synchronized (this) { 10426 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10427 } 10428 10429 final long ident = mInjector.binderClearCallingIdentity(); 10430 try { 10431 IBackupManager ibm = mInjector.getIBackupManager(); 10432 if (ibm != null) { 10433 ibm.setBackupServiceActive(UserHandle.USER_SYSTEM, enabled); 10434 } 10435 } catch (RemoteException e) { 10436 throw new IllegalStateException( 10437 "Failed " + (enabled ? "" : "de") + "activating backup service.", e); 10438 } finally { 10439 mInjector.binderRestoreCallingIdentity(ident); 10440 } 10441 } 10442 10443 @Override 10444 public boolean isBackupServiceEnabled(ComponentName admin) { 10445 Preconditions.checkNotNull(admin); 10446 if (!mHasFeature) { 10447 return true; 10448 } 10449 synchronized (this) { 10450 try { 10451 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10452 IBackupManager ibm = mInjector.getIBackupManager(); 10453 return ibm != null && ibm.isBackupServiceActive(UserHandle.USER_SYSTEM); 10454 } catch (RemoteException e) { 10455 throw new IllegalStateException("Failed requesting backup service state.", e); 10456 } 10457 } 10458 } 10459 10460 @Override 10461 public boolean bindDeviceAdminServiceAsUser( 10462 @NonNull ComponentName admin, @NonNull IApplicationThread caller, 10463 @Nullable IBinder activtiyToken, @NonNull Intent serviceIntent, 10464 @NonNull IServiceConnection connection, int flags, @UserIdInt int targetUserId) { 10465 if (!mHasFeature) { 10466 return false; 10467 } 10468 Preconditions.checkNotNull(admin); 10469 Preconditions.checkNotNull(caller); 10470 Preconditions.checkNotNull(serviceIntent); 10471 Preconditions.checkArgument( 10472 serviceIntent.getComponent() != null || serviceIntent.getPackage() != null, 10473 "Service intent must be explicit (with a package name or component): " 10474 + serviceIntent); 10475 Preconditions.checkNotNull(connection); 10476 Preconditions.checkArgument(mInjector.userHandleGetCallingUserId() != targetUserId, 10477 "target user id must be different from the calling user id"); 10478 10479 if (!getBindDeviceAdminTargetUsers(admin).contains(UserHandle.of(targetUserId))) { 10480 throw new SecurityException("Not allowed to bind to target user id"); 10481 } 10482 10483 final String targetPackage; 10484 synchronized (this) { 10485 targetPackage = getOwnerPackageNameForUserLocked(targetUserId); 10486 } 10487 10488 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10489 try { 10490 // Validate and sanitize the incoming service intent. 10491 final Intent sanitizedIntent = 10492 createCrossUserServiceIntent(serviceIntent, targetPackage, targetUserId); 10493 if (sanitizedIntent == null) { 10494 // Fail, cannot lookup the target service. 10495 return false; 10496 } 10497 // Ask ActivityManager to bind it. Notice that we are binding the service with the 10498 // caller app instead of DevicePolicyManagerService. 10499 return mInjector.getIActivityManager().bindService( 10500 caller, activtiyToken, serviceIntent, 10501 serviceIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 10502 connection, flags, mContext.getOpPackageName(), 10503 targetUserId) != 0; 10504 } catch (RemoteException ex) { 10505 // Same process, should not happen. 10506 } finally { 10507 mInjector.binderRestoreCallingIdentity(callingIdentity); 10508 } 10509 10510 // Failed to bind. 10511 return false; 10512 } 10513 10514 @Override 10515 public @NonNull List<UserHandle> getBindDeviceAdminTargetUsers(@NonNull ComponentName admin) { 10516 if (!mHasFeature) { 10517 return Collections.emptyList(); 10518 } 10519 Preconditions.checkNotNull(admin); 10520 10521 synchronized (this) { 10522 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10523 10524 final int callingUserId = mInjector.userHandleGetCallingUserId(); 10525 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10526 try { 10527 ArrayList<UserHandle> targetUsers = new ArrayList<>(); 10528 if (!isDeviceOwner(admin, callingUserId)) { 10529 // Profile owners can only bind to the device owner. 10530 if (canUserBindToDeviceOwnerLocked(callingUserId)) { 10531 targetUsers.add(UserHandle.of(mOwners.getDeviceOwnerUserId())); 10532 } 10533 } else { 10534 // Caller is the device owner: Look for profile owners that it can bind to. 10535 final List<UserInfo> userInfos = mUserManager.getUsers(/*excludeDying=*/ true); 10536 for (int i = 0; i < userInfos.size(); i++) { 10537 final int userId = userInfos.get(i).id; 10538 if (userId != callingUserId && canUserBindToDeviceOwnerLocked(userId)) { 10539 targetUsers.add(UserHandle.of(userId)); 10540 } 10541 } 10542 } 10543 10544 return targetUsers; 10545 } finally { 10546 mInjector.binderRestoreCallingIdentity(callingIdentity); 10547 } 10548 } 10549 } 10550 10551 private boolean canUserBindToDeviceOwnerLocked(int userId) { 10552 // There has to be a device owner, under another user id. 10553 if (!mOwners.hasDeviceOwner() || userId == mOwners.getDeviceOwnerUserId()) { 10554 return false; 10555 } 10556 10557 // The user must have a profile owner that belongs to the same package as the device owner. 10558 if (!mOwners.hasProfileOwner(userId) || !TextUtils.equals( 10559 mOwners.getDeviceOwnerPackageName(), mOwners.getProfileOwnerPackage(userId))) { 10560 return false; 10561 } 10562 10563 // The user must be affiliated. 10564 return isUserAffiliatedWithDeviceLocked(userId); 10565 } 10566 10567 /** 10568 * Return true if a given user has any accounts that'll prevent installing a device or profile 10569 * owner {@code owner}. 10570 * - If the user has no accounts, then return false. 10571 * - Otherwise, if the owner is unknown (== null), or is not test-only, then return true. 10572 * - Otherwise, if there's any account that does not have ..._ALLOWED, or does have 10573 * ..._DISALLOWED, return true. 10574 * - Otherwise return false. 10575 * 10576 * If the caller is *not* ADB, it also returns true. The returned value shouldn't be used 10577 * when the caller is not ADB. 10578 * 10579 * DO NOT CALL IT WITH THE DPMS LOCK HELD. 10580 */ 10581 private boolean hasIncompatibleAccountsOrNonAdbNoLock( 10582 int userId, @Nullable ComponentName owner) { 10583 if (!isAdb()) { 10584 return true; 10585 } 10586 wtfIfInLock(); 10587 10588 final long token = mInjector.binderClearCallingIdentity(); 10589 try { 10590 final AccountManager am = AccountManager.get(mContext); 10591 final Account accounts[] = am.getAccountsAsUser(userId); 10592 if (accounts.length == 0) { 10593 return false; 10594 } 10595 synchronized (this) { 10596 if (owner == null || !isAdminTestOnlyLocked(owner, userId)) { 10597 Log.w(LOG_TAG, 10598 "Non test-only owner can't be installed with existing accounts."); 10599 return true; 10600 } 10601 } 10602 10603 final String[] feature_allow = 10604 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_ALLOWED }; 10605 final String[] feature_disallow = 10606 { DevicePolicyManager.ACCOUNT_FEATURE_DEVICE_OR_PROFILE_OWNER_DISALLOWED }; 10607 10608 boolean compatible = true; 10609 for (Account account : accounts) { 10610 if (hasAccountFeatures(am, account, feature_disallow)) { 10611 Log.e(LOG_TAG, account + " has " + feature_disallow[0]); 10612 compatible = false; 10613 break; 10614 } 10615 if (!hasAccountFeatures(am, account, feature_allow)) { 10616 Log.e(LOG_TAG, account + " doesn't have " + feature_allow[0]); 10617 compatible = false; 10618 break; 10619 } 10620 } 10621 if (compatible) { 10622 Log.w(LOG_TAG, "All accounts are compatible"); 10623 } else { 10624 Log.e(LOG_TAG, "Found incompatible accounts"); 10625 } 10626 return !compatible; 10627 } finally { 10628 mInjector.binderRestoreCallingIdentity(token); 10629 } 10630 } 10631 10632 private boolean hasAccountFeatures(AccountManager am, Account account, String[] features) { 10633 try { 10634 return am.hasFeatures(account, features, null, null).getResult(); 10635 } catch (Exception e) { 10636 Log.w(LOG_TAG, "Failed to get account feature", e); 10637 return false; 10638 } 10639 } 10640 10641 private boolean isAdb() { 10642 final int callingUid = mInjector.binderGetCallingUid(); 10643 return callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID; 10644 } 10645 10646 @Override 10647 public synchronized void setNetworkLoggingEnabled(ComponentName admin, boolean enabled) { 10648 if (!mHasFeature) { 10649 return; 10650 } 10651 Preconditions.checkNotNull(admin); 10652 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 10653 10654 if (enabled == isNetworkLoggingEnabledInternalLocked()) { 10655 // already in the requested state 10656 return; 10657 } 10658 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10659 deviceOwner.isNetworkLoggingEnabled = enabled; 10660 if (!enabled) { 10661 deviceOwner.numNetworkLoggingNotifications = 0; 10662 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10663 } 10664 saveSettingsLocked(mInjector.userHandleGetCallingUserId()); 10665 10666 setNetworkLoggingActiveInternal(enabled); 10667 } 10668 10669 private synchronized void setNetworkLoggingActiveInternal(boolean active) { 10670 final long callingIdentity = mInjector.binderClearCallingIdentity(); 10671 try { 10672 if (active) { 10673 mNetworkLogger = new NetworkLogger(this, mInjector.getPackageManagerInternal()); 10674 if (!mNetworkLogger.startNetworkLogging()) { 10675 mNetworkLogger = null; 10676 Slog.wtf(LOG_TAG, "Network logging could not be started due to the logging" 10677 + " service not being available yet."); 10678 } 10679 maybePauseDeviceWideLoggingLocked(); 10680 sendNetworkLoggingNotificationLocked(); 10681 } else { 10682 if (mNetworkLogger != null && !mNetworkLogger.stopNetworkLogging()) { 10683 Slog.wtf(LOG_TAG, "Network logging could not be stopped due to the logging" 10684 + " service not being available yet."); 10685 } 10686 mNetworkLogger = null; 10687 mInjector.getNotificationManager().cancel(SystemMessage.NOTE_NETWORK_LOGGING); 10688 } 10689 } finally { 10690 mInjector.binderRestoreCallingIdentity(callingIdentity); 10691 } 10692 } 10693 10694 /** Pauses security and network logging if there are unaffiliated users on the device */ 10695 private void maybePauseDeviceWideLoggingLocked() { 10696 if (!areAllUsersAffiliatedWithDeviceLocked()) { 10697 Slog.i(LOG_TAG, "There are unaffiliated users, security and network logging will be " 10698 + "paused if enabled."); 10699 mSecurityLogMonitor.pause(); 10700 if (mNetworkLogger != null) { 10701 mNetworkLogger.pause(); 10702 } 10703 } 10704 } 10705 10706 /** Resumes security and network logging (if they are enabled) if all users are affiliated */ 10707 private void maybeResumeDeviceWideLoggingLocked() { 10708 if (areAllUsersAffiliatedWithDeviceLocked()) { 10709 final long ident = mInjector.binderClearCallingIdentity(); 10710 try { 10711 mSecurityLogMonitor.resume(); 10712 if (mNetworkLogger != null) { 10713 mNetworkLogger.resume(); 10714 } 10715 } finally { 10716 mInjector.binderRestoreCallingIdentity(ident); 10717 } 10718 } 10719 } 10720 10721 /** Deletes any security and network logs that might have been collected so far */ 10722 private void discardDeviceWideLogsLocked() { 10723 mSecurityLogMonitor.discardLogs(); 10724 if (mNetworkLogger != null) { 10725 mNetworkLogger.discardLogs(); 10726 } 10727 // TODO: We should discard pre-boot security logs here too, as otherwise those 10728 // logs (which might contain data from the user just removed) will be 10729 // available after next boot. 10730 } 10731 10732 @Override 10733 public boolean isNetworkLoggingEnabled(ComponentName admin) { 10734 if (!mHasFeature) { 10735 return false; 10736 } 10737 synchronized (this) { 10738 enforceDeviceOwnerOrManageUsers(); 10739 return isNetworkLoggingEnabledInternalLocked(); 10740 } 10741 } 10742 10743 private boolean isNetworkLoggingEnabledInternalLocked() { 10744 ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10745 return (deviceOwner != null) && deviceOwner.isNetworkLoggingEnabled; 10746 } 10747 10748 /* 10749 * A maximum of 1200 events are returned, and the total marshalled size is in the order of 10750 * 100kB, so returning a List instead of ParceledListSlice is acceptable. 10751 * Ideally this would be done with ParceledList, however it only supports homogeneous types. 10752 * 10753 * @see NetworkLoggingHandler#MAX_EVENTS_PER_BATCH 10754 */ 10755 @Override 10756 public List<NetworkEvent> retrieveNetworkLogs(ComponentName admin, long batchToken) { 10757 if (!mHasFeature) { 10758 return null; 10759 } 10760 Preconditions.checkNotNull(admin); 10761 ensureDeviceOwnerAndAllUsersAffiliated(admin); 10762 10763 synchronized (this) { 10764 if (mNetworkLogger == null 10765 || !isNetworkLoggingEnabledInternalLocked()) { 10766 return null; 10767 } 10768 10769 final long currentTime = System.currentTimeMillis(); 10770 DevicePolicyData policyData = getUserData(UserHandle.USER_SYSTEM); 10771 if (currentTime > policyData.mLastNetworkLogsRetrievalTime) { 10772 policyData.mLastNetworkLogsRetrievalTime = currentTime; 10773 saveSettingsLocked(UserHandle.USER_SYSTEM); 10774 } 10775 return mNetworkLogger.retrieveLogs(batchToken); 10776 } 10777 } 10778 10779 private void sendNetworkLoggingNotificationLocked() { 10780 final ActiveAdmin deviceOwner = getDeviceOwnerAdminLocked(); 10781 if (deviceOwner == null || !deviceOwner.isNetworkLoggingEnabled) { 10782 return; 10783 } 10784 if (deviceOwner.numNetworkLoggingNotifications >= 10785 ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10786 return; 10787 } 10788 final long now = System.currentTimeMillis(); 10789 if (now - deviceOwner.lastNetworkLoggingNotificationTimeMs < MS_PER_DAY) { 10790 return; 10791 } 10792 deviceOwner.numNetworkLoggingNotifications++; 10793 if (deviceOwner.numNetworkLoggingNotifications 10794 >= ActiveAdmin.DEF_MAXIMUM_NETWORK_LOGGING_NOTIFICATIONS_SHOWN) { 10795 deviceOwner.lastNetworkLoggingNotificationTimeMs = 0; 10796 } else { 10797 deviceOwner.lastNetworkLoggingNotificationTimeMs = now; 10798 } 10799 final Intent intent = new Intent(DevicePolicyManager.ACTION_SHOW_DEVICE_MONITORING_DIALOG); 10800 intent.setPackage("com.android.systemui"); 10801 final PendingIntent pendingIntent = PendingIntent.getBroadcastAsUser(mContext, 0, intent, 0, 10802 UserHandle.CURRENT); 10803 Notification notification = 10804 new Notification.Builder(mContext, SystemNotificationChannels.DEVICE_ADMIN) 10805 .setSmallIcon(R.drawable.ic_info_outline) 10806 .setContentTitle(mContext.getString(R.string.network_logging_notification_title)) 10807 .setContentText(mContext.getString(R.string.network_logging_notification_text)) 10808 .setTicker(mContext.getString(R.string.network_logging_notification_title)) 10809 .setShowWhen(true) 10810 .setContentIntent(pendingIntent) 10811 .setStyle(new Notification.BigTextStyle() 10812 .bigText(mContext.getString(R.string.network_logging_notification_text))) 10813 .build(); 10814 mInjector.getNotificationManager().notify(SystemMessage.NOTE_NETWORK_LOGGING, notification); 10815 saveSettingsLocked(mOwners.getDeviceOwnerUserId()); 10816 } 10817 10818 /** 10819 * Return the package name of owner in a given user. 10820 */ 10821 private String getOwnerPackageNameForUserLocked(int userId) { 10822 return mOwners.getDeviceOwnerUserId() == userId 10823 ? mOwners.getDeviceOwnerPackageName() 10824 : mOwners.getProfileOwnerPackage(userId); 10825 } 10826 10827 /** 10828 * @param rawIntent Original service intent specified by caller. It must be explicit. 10829 * @param expectedPackageName The expected package name of the resolved service. 10830 * @return Intent that have component explicitly set. {@code null} if no service is resolved 10831 * with the given intent. 10832 * @throws SecurityException if the intent is resolved to an invalid service. 10833 */ 10834 private Intent createCrossUserServiceIntent( 10835 @NonNull Intent rawIntent, @NonNull String expectedPackageName, 10836 @UserIdInt int targetUserId) throws RemoteException, SecurityException { 10837 ResolveInfo info = mIPackageManager.resolveService( 10838 rawIntent, 10839 rawIntent.resolveTypeIfNeeded(mContext.getContentResolver()), 10840 0, // flags 10841 targetUserId); 10842 if (info == null || info.serviceInfo == null) { 10843 Log.e(LOG_TAG, "Fail to look up the service: " + rawIntent 10844 + " or user " + targetUserId + " is not running"); 10845 return null; 10846 } 10847 if (!expectedPackageName.equals(info.serviceInfo.packageName)) { 10848 throw new SecurityException("Only allow to bind service in " + expectedPackageName); 10849 } 10850 // STOPSHIP(b/37624960): Remove info.serviceInfo.exported before release. 10851 if (info.serviceInfo.exported && !BIND_DEVICE_ADMIN.equals(info.serviceInfo.permission)) { 10852 throw new SecurityException( 10853 "Service must be protected by BIND_DEVICE_ADMIN permission"); 10854 } 10855 // It is the system server to bind the service, it would be extremely dangerous if it 10856 // can be exploited to bind any service. Set the component explicitly to make sure we 10857 // do not bind anything accidentally. 10858 rawIntent.setComponent(info.serviceInfo.getComponentName()); 10859 return rawIntent; 10860 } 10861 10862 @Override 10863 public long getLastSecurityLogRetrievalTime() { 10864 enforceDeviceOwnerOrManageUsers(); 10865 return getUserData(UserHandle.USER_SYSTEM).mLastSecurityLogRetrievalTime; 10866 } 10867 10868 @Override 10869 public long getLastBugReportRequestTime() { 10870 enforceDeviceOwnerOrManageUsers(); 10871 return getUserData(UserHandle.USER_SYSTEM).mLastBugReportRequestTime; 10872 } 10873 10874 @Override 10875 public long getLastNetworkLogRetrievalTime() { 10876 enforceDeviceOwnerOrManageUsers(); 10877 return getUserData(UserHandle.USER_SYSTEM).mLastNetworkLogsRetrievalTime; 10878 } 10879 10880 @Override 10881 public boolean setResetPasswordToken(ComponentName admin, byte[] token) { 10882 if (!mHasFeature) { 10883 return false; 10884 } 10885 if (token == null || token.length < 32) { 10886 throw new IllegalArgumentException("token must be at least 32-byte long"); 10887 } 10888 synchronized (this) { 10889 final int userHandle = mInjector.userHandleGetCallingUserId(); 10890 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10891 10892 DevicePolicyData policy = getUserData(userHandle); 10893 long ident = mInjector.binderClearCallingIdentity(); 10894 try { 10895 if (policy.mPasswordTokenHandle != 0) { 10896 mLockPatternUtils.removeEscrowToken(policy.mPasswordTokenHandle, userHandle); 10897 } 10898 10899 policy.mPasswordTokenHandle = mLockPatternUtils.addEscrowToken(token, userHandle); 10900 saveSettingsLocked(userHandle); 10901 return policy.mPasswordTokenHandle != 0; 10902 } finally { 10903 mInjector.binderRestoreCallingIdentity(ident); 10904 } 10905 } 10906 } 10907 10908 @Override 10909 public boolean clearResetPasswordToken(ComponentName admin) { 10910 if (!mHasFeature) { 10911 return false; 10912 } 10913 synchronized (this) { 10914 final int userHandle = mInjector.userHandleGetCallingUserId(); 10915 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10916 10917 DevicePolicyData policy = getUserData(userHandle); 10918 if (policy.mPasswordTokenHandle != 0) { 10919 long ident = mInjector.binderClearCallingIdentity(); 10920 try { 10921 boolean result = mLockPatternUtils.removeEscrowToken( 10922 policy.mPasswordTokenHandle, userHandle); 10923 policy.mPasswordTokenHandle = 0; 10924 saveSettingsLocked(userHandle); 10925 return result; 10926 } finally { 10927 mInjector.binderRestoreCallingIdentity(ident); 10928 } 10929 } 10930 } 10931 return false; 10932 } 10933 10934 @Override 10935 public boolean isResetPasswordTokenActive(ComponentName admin) { 10936 synchronized (this) { 10937 final int userHandle = mInjector.userHandleGetCallingUserId(); 10938 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10939 10940 DevicePolicyData policy = getUserData(userHandle); 10941 if (policy.mPasswordTokenHandle != 0) { 10942 long ident = mInjector.binderClearCallingIdentity(); 10943 try { 10944 return mLockPatternUtils.isEscrowTokenActive(policy.mPasswordTokenHandle, 10945 userHandle); 10946 } finally { 10947 mInjector.binderRestoreCallingIdentity(ident); 10948 } 10949 } 10950 } 10951 return false; 10952 } 10953 10954 @Override 10955 public boolean resetPasswordWithToken(ComponentName admin, String passwordOrNull, byte[] token, 10956 int flags) { 10957 Preconditions.checkNotNull(token); 10958 synchronized (this) { 10959 final int userHandle = mInjector.userHandleGetCallingUserId(); 10960 getActiveAdminForCallerLocked(admin, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 10961 10962 DevicePolicyData policy = getUserData(userHandle); 10963 if (policy.mPasswordTokenHandle != 0) { 10964 final String password = passwordOrNull != null ? passwordOrNull : ""; 10965 return resetPasswordInternal(password, policy.mPasswordTokenHandle, token, 10966 flags, mInjector.binderGetCallingUid(), userHandle); 10967 } else { 10968 Slog.w(LOG_TAG, "No saved token handle"); 10969 } 10970 } 10971 return false; 10972 } 10973 10974 @Override 10975 public boolean isCurrentInputMethodSetByOwner() { 10976 enforceProfileOwnerOrSystemUser(); 10977 return getUserData(mInjector.userHandleGetCallingUserId()).mCurrentInputMethodSet; 10978 } 10979 10980 @Override 10981 public StringParceledListSlice getOwnerInstalledCaCerts(@NonNull UserHandle user) { 10982 final int userId = user.getIdentifier(); 10983 enforceProfileOwnerOrFullCrossUsersPermission(userId); 10984 synchronized (this) { 10985 return new StringParceledListSlice( 10986 new ArrayList<>(getUserData(userId).mOwnerInstalledCaCerts)); 10987 } 10988 } 10989} 10990