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