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