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