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