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