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