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