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