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