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