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