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