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