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