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