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