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