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