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