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