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