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