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