DevicePolicyManagerService.java revision 85516d028b2dcc7ebc09f4a68085836aa26191d5
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<String> mLockTaskPackages = new ArrayList<String>(); 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.mLockTaskPackages.size(); i++) { 1018 String component = policy.mLockTaskPackages.get(i); 1019 out.startTag(null, LOCK_TASK_COMPONENTS_XML); 1020 out.attribute(null, "name", component); 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.mLockTaskPackages.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.mLockTaskPackages.add(parser.getAttributeValue(null, "name")); 1135 XmlUtils.skipCurrentTag(parser); 1136 } else { 1137 Slog.w(LOG_TAG, "Unknown tag: " + tag); 1138 XmlUtils.skipCurrentTag(parser); 1139 } 1140 } 1141 } catch (NullPointerException e) { 1142 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1143 } catch (NumberFormatException e) { 1144 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1145 } catch (XmlPullParserException e) { 1146 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1147 } catch (FileNotFoundException e) { 1148 // Don't be noisy, this is normal if we haven't defined any policies. 1149 } catch (IOException e) { 1150 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1151 } catch (IndexOutOfBoundsException e) { 1152 Slog.w(LOG_TAG, "failed parsing " + file + " " + e); 1153 } 1154 try { 1155 if (stream != null) { 1156 stream.close(); 1157 } 1158 } catch (IOException e) { 1159 // Ignore 1160 } 1161 1162 // Validate that what we stored for the password quality matches 1163 // sufficiently what is currently set. Note that this is only 1164 // a sanity check in case the two get out of sync; this should 1165 // never normally happen. 1166 LockPatternUtils utils = new LockPatternUtils(mContext); 1167 if (utils.getActivePasswordQuality() < policy.mActivePasswordQuality) { 1168 Slog.w(LOG_TAG, "Active password quality 0x" 1169 + Integer.toHexString(policy.mActivePasswordQuality) 1170 + " does not match actual quality 0x" 1171 + Integer.toHexString(utils.getActivePasswordQuality())); 1172 policy.mActivePasswordQuality = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 1173 policy.mActivePasswordLength = 0; 1174 policy.mActivePasswordUpperCase = 0; 1175 policy.mActivePasswordLowerCase = 0; 1176 policy.mActivePasswordLetters = 0; 1177 policy.mActivePasswordNumeric = 0; 1178 policy.mActivePasswordSymbols = 0; 1179 policy.mActivePasswordNonLetter = 0; 1180 } 1181 1182 validatePasswordOwnerLocked(policy); 1183 syncDeviceCapabilitiesLocked(policy); 1184 updateMaximumTimeToLockLocked(policy); 1185 } 1186 1187 static void validateQualityConstant(int quality) { 1188 switch (quality) { 1189 case DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED: 1190 case DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK: 1191 case DevicePolicyManager.PASSWORD_QUALITY_SOMETHING: 1192 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC: 1193 case DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX: 1194 case DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC: 1195 case DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC: 1196 case DevicePolicyManager.PASSWORD_QUALITY_COMPLEX: 1197 return; 1198 } 1199 throw new IllegalArgumentException("Invalid quality constant: 0x" 1200 + Integer.toHexString(quality)); 1201 } 1202 1203 void validatePasswordOwnerLocked(DevicePolicyData policy) { 1204 if (policy.mPasswordOwner >= 0) { 1205 boolean haveOwner = false; 1206 for (int i = policy.mAdminList.size() - 1; i >= 0; i--) { 1207 if (policy.mAdminList.get(i).getUid() == policy.mPasswordOwner) { 1208 haveOwner = true; 1209 break; 1210 } 1211 } 1212 if (!haveOwner) { 1213 Slog.w(LOG_TAG, "Previous password owner " + policy.mPasswordOwner 1214 + " no longer active; disabling"); 1215 policy.mPasswordOwner = -1; 1216 } 1217 } 1218 } 1219 1220 /** 1221 * Pushes down policy information to the system for any policies related to general device 1222 * capabilities that need to be enforced by lower level services (e.g. Camera services). 1223 */ 1224 void syncDeviceCapabilitiesLocked(DevicePolicyData policy) { 1225 // Ensure the status of the camera is synced down to the system. Interested native services 1226 // should monitor this value and act accordingly. 1227 boolean systemState = SystemProperties.getBoolean(SYSTEM_PROP_DISABLE_CAMERA, false); 1228 boolean cameraDisabled = getCameraDisabled(null, policy.mUserHandle); 1229 if (cameraDisabled != systemState) { 1230 long token = Binder.clearCallingIdentity(); 1231 try { 1232 String value = cameraDisabled ? "1" : "0"; 1233 if (DBG) Slog.v(LOG_TAG, "Change in camera state [" 1234 + SYSTEM_PROP_DISABLE_CAMERA + "] = " + value); 1235 SystemProperties.set(SYSTEM_PROP_DISABLE_CAMERA, value); 1236 } finally { 1237 Binder.restoreCallingIdentity(token); 1238 } 1239 } 1240 } 1241 1242 public void systemReady() { 1243 if (!mHasFeature) { 1244 return; 1245 } 1246 synchronized (this) { 1247 loadSettingsLocked(getUserData(UserHandle.USER_OWNER), UserHandle.USER_OWNER); 1248 loadDeviceOwner(); 1249 } 1250 cleanUpOldUsers(); 1251 mAppOpsService = IAppOpsService.Stub.asInterface( 1252 ServiceManager.getService(Context.APP_OPS_SERVICE)); 1253 if (mDeviceOwner != null) { 1254 if (mDeviceOwner.hasDeviceOwner()) { 1255 try { 1256 mAppOpsService.setDeviceOwner(mDeviceOwner.getDeviceOwnerPackageName()); 1257 } catch (RemoteException e) { 1258 Log.w(LOG_TAG, "Unable to notify AppOpsService of DeviceOwner", e); 1259 } 1260 } 1261 for (Integer i : mDeviceOwner.getProfileOwnerKeys()) { 1262 try { 1263 mAppOpsService.setProfileOwner(mDeviceOwner.getProfileOwnerPackageName(i), i); 1264 } catch (RemoteException e) { 1265 Log.w(LOG_TAG, "Unable to notify AppOpsService of ProfileOwner", e); 1266 } 1267 } 1268 } 1269 } 1270 1271 private void cleanUpOldUsers() { 1272 // This is needed in case the broadcast {@link Intent.ACTION_USER_REMOVED} was not handled 1273 // before reboot 1274 Set<Integer> usersWithProfileOwners; 1275 Set<Integer> usersWithData; 1276 synchronized(this) { 1277 usersWithProfileOwners = mDeviceOwner != null 1278 ? mDeviceOwner.getProfileOwnerKeys() : new HashSet<Integer>(); 1279 usersWithData = new HashSet<Integer>(); 1280 for (int i = 0; i < mUserData.size(); i++) { 1281 usersWithData.add(mUserData.keyAt(i)); 1282 } 1283 } 1284 List<UserInfo> allUsers = mUserManager.getUsers(); 1285 1286 Set<Integer> deletedUsers = new HashSet<Integer>(); 1287 deletedUsers.addAll(usersWithProfileOwners); 1288 deletedUsers.addAll(usersWithData); 1289 for (UserInfo userInfo : allUsers) { 1290 deletedUsers.remove(userInfo.id); 1291 } 1292 for (Integer userId : deletedUsers) { 1293 removeUserData(userId); 1294 } 1295 } 1296 1297 private void handlePasswordExpirationNotification(int userHandle) { 1298 synchronized (this) { 1299 final long now = System.currentTimeMillis(); 1300 1301 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1302 for (UserInfo ui : profiles) { 1303 int profileUserHandle = ui.getUserHandle().getIdentifier(); 1304 final DevicePolicyData policy = getUserData(profileUserHandle); 1305 final int count = policy.mAdminList.size(); 1306 if (count > 0) { 1307 for (int i = 0; i < count; i++) { 1308 final ActiveAdmin admin = policy.mAdminList.get(i); 1309 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD) 1310 && admin.passwordExpirationTimeout > 0L 1311 && now >= admin.passwordExpirationDate - EXPIRATION_GRACE_PERIOD_MS 1312 && admin.passwordExpirationDate > 0L) { 1313 sendAdminCommandLocked(admin, 1314 DeviceAdminReceiver.ACTION_PASSWORD_EXPIRING); 1315 } 1316 } 1317 } 1318 } 1319 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle)); 1320 } 1321 } 1322 1323 private void manageMonitoringCertificateNotification(Intent intent) { 1324 final NotificationManager notificationManager = getNotificationManager(); 1325 1326 final boolean hasCert = !(new TrustedCertificateStore().userAliases().isEmpty()); 1327 if (! hasCert) { 1328 if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) { 1329 for (UserInfo user : mUserManager.getUsers()) { 1330 notificationManager.cancelAsUser( 1331 null, MONITORING_CERT_NOTIFICATION_ID, user.getUserHandle()); 1332 } 1333 } 1334 return; 1335 } 1336 final boolean isManaged = getDeviceOwner() != null; 1337 int smallIconId; 1338 String contentText; 1339 if (isManaged) { 1340 contentText = mContext.getString(R.string.ssl_ca_cert_noti_managed, 1341 getDeviceOwnerName()); 1342 smallIconId = R.drawable.stat_sys_certificate_info; 1343 } else { 1344 contentText = mContext.getString(R.string.ssl_ca_cert_noti_by_unknown); 1345 smallIconId = android.R.drawable.stat_sys_warning; 1346 } 1347 1348 Intent dialogIntent = new Intent(Settings.ACTION_MONITORING_CERT_INFO); 1349 dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 1350 dialogIntent.setPackage("com.android.settings"); 1351 // Notification will be sent individually to all users. The activity should start as 1352 // whichever user is current when it starts. 1353 PendingIntent notifyIntent = PendingIntent.getActivityAsUser(mContext, 0, dialogIntent, 1354 PendingIntent.FLAG_UPDATE_CURRENT, null, UserHandle.CURRENT); 1355 1356 Notification noti = new Notification.Builder(mContext) 1357 .setSmallIcon(smallIconId) 1358 .setContentTitle(mContext.getString(R.string.ssl_ca_cert_warning)) 1359 .setContentText(contentText) 1360 .setContentIntent(notifyIntent) 1361 .setPriority(Notification.PRIORITY_HIGH) 1362 .setShowWhen(false) 1363 .build(); 1364 1365 // If this is a boot intent, this will fire for each user. But if this is a storage changed 1366 // intent, it will fire once, so we need to notify all users. 1367 if (intent.getAction().equals(KeyChain.ACTION_STORAGE_CHANGED)) { 1368 for (UserInfo user : mUserManager.getUsers()) { 1369 notificationManager.notifyAsUser( 1370 null, MONITORING_CERT_NOTIFICATION_ID, noti, user.getUserHandle()); 1371 } 1372 } else { 1373 notificationManager.notifyAsUser( 1374 null, MONITORING_CERT_NOTIFICATION_ID, noti, UserHandle.CURRENT); 1375 } 1376 } 1377 1378 /** 1379 * @param adminReceiver The admin to add 1380 * @param refreshing true = update an active admin, no error 1381 */ 1382 public void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle) { 1383 if (!mHasFeature) { 1384 return; 1385 } 1386 setActiveAdmin(adminReceiver, refreshing, userHandle, null); 1387 } 1388 1389 private void setActiveAdmin(ComponentName adminReceiver, boolean refreshing, int userHandle, 1390 Bundle onEnableData) { 1391 mContext.enforceCallingOrSelfPermission( 1392 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 1393 enforceCrossUserPermission(userHandle); 1394 1395 DevicePolicyData policy = getUserData(userHandle); 1396 DeviceAdminInfo info = findAdmin(adminReceiver, userHandle); 1397 if (info == null) { 1398 throw new IllegalArgumentException("Bad admin: " + adminReceiver); 1399 } 1400 synchronized (this) { 1401 long ident = Binder.clearCallingIdentity(); 1402 try { 1403 if (!refreshing 1404 && getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null) { 1405 throw new IllegalArgumentException("Admin is already added"); 1406 } 1407 ActiveAdmin newAdmin = new ActiveAdmin(info); 1408 policy.mAdminMap.put(adminReceiver, newAdmin); 1409 int replaceIndex = -1; 1410 if (refreshing) { 1411 final int N = policy.mAdminList.size(); 1412 for (int i=0; i < N; i++) { 1413 ActiveAdmin oldAdmin = policy.mAdminList.get(i); 1414 if (oldAdmin.info.getComponent().equals(adminReceiver)) { 1415 replaceIndex = i; 1416 break; 1417 } 1418 } 1419 } 1420 if (replaceIndex == -1) { 1421 policy.mAdminList.add(newAdmin); 1422 enableIfNecessary(info.getPackageName(), userHandle); 1423 } else { 1424 policy.mAdminList.set(replaceIndex, newAdmin); 1425 } 1426 saveSettingsLocked(userHandle); 1427 sendAdminCommandLocked(newAdmin, DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED, 1428 onEnableData, null); 1429 } finally { 1430 Binder.restoreCallingIdentity(ident); 1431 } 1432 } 1433 } 1434 1435 public boolean isAdminActive(ComponentName adminReceiver, int userHandle) { 1436 if (!mHasFeature) { 1437 return false; 1438 } 1439 enforceCrossUserPermission(userHandle); 1440 synchronized (this) { 1441 return getActiveAdminUncheckedLocked(adminReceiver, userHandle) != null; 1442 } 1443 } 1444 1445 public boolean hasGrantedPolicy(ComponentName adminReceiver, int policyId, int userHandle) { 1446 if (!mHasFeature) { 1447 return false; 1448 } 1449 enforceCrossUserPermission(userHandle); 1450 synchronized (this) { 1451 ActiveAdmin administrator = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 1452 if (administrator == null) { 1453 throw new SecurityException("No active admin " + adminReceiver); 1454 } 1455 return administrator.info.usesPolicy(policyId); 1456 } 1457 } 1458 1459 @SuppressWarnings("unchecked") 1460 public List<ComponentName> getActiveAdmins(int userHandle) { 1461 if (!mHasFeature) { 1462 return Collections.EMPTY_LIST; 1463 } 1464 1465 enforceCrossUserPermission(userHandle); 1466 synchronized (this) { 1467 DevicePolicyData policy = getUserData(userHandle); 1468 final int N = policy.mAdminList.size(); 1469 if (N <= 0) { 1470 return null; 1471 } 1472 ArrayList<ComponentName> res = new ArrayList<ComponentName>(N); 1473 for (int i=0; i<N; i++) { 1474 res.add(policy.mAdminList.get(i).info.getComponent()); 1475 } 1476 return res; 1477 } 1478 } 1479 1480 public boolean packageHasActiveAdmins(String packageName, int userHandle) { 1481 if (!mHasFeature) { 1482 return false; 1483 } 1484 enforceCrossUserPermission(userHandle); 1485 synchronized (this) { 1486 DevicePolicyData policy = getUserData(userHandle); 1487 final int N = policy.mAdminList.size(); 1488 for (int i=0; i<N; i++) { 1489 if (policy.mAdminList.get(i).info.getPackageName().equals(packageName)) { 1490 return true; 1491 } 1492 } 1493 return false; 1494 } 1495 } 1496 1497 public void removeActiveAdmin(ComponentName adminReceiver, int userHandle) { 1498 if (!mHasFeature) { 1499 return; 1500 } 1501 enforceCrossUserPermission(userHandle); 1502 synchronized (this) { 1503 ActiveAdmin admin = getActiveAdminUncheckedLocked(adminReceiver, userHandle); 1504 if (admin == null) { 1505 return; 1506 } 1507 if (admin.getUid() != Binder.getCallingUid()) { 1508 // If trying to remove device owner, refuse when the caller is not the owner. 1509 if (isDeviceOwner(adminReceiver.getPackageName())) { 1510 return; 1511 } 1512 mContext.enforceCallingOrSelfPermission( 1513 android.Manifest.permission.MANAGE_DEVICE_ADMINS, null); 1514 } 1515 long ident = Binder.clearCallingIdentity(); 1516 try { 1517 removeActiveAdminLocked(adminReceiver, userHandle); 1518 } finally { 1519 Binder.restoreCallingIdentity(ident); 1520 } 1521 } 1522 } 1523 1524 public void setPasswordQuality(ComponentName who, int quality, int userHandle) { 1525 if (!mHasFeature) { 1526 return; 1527 } 1528 validateQualityConstant(quality); 1529 enforceCrossUserPermission(userHandle); 1530 1531 synchronized (this) { 1532 if (who == null) { 1533 throw new NullPointerException("ComponentName is null"); 1534 } 1535 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1536 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1537 if (ap.passwordQuality != quality) { 1538 ap.passwordQuality = quality; 1539 saveSettingsLocked(userHandle); 1540 } 1541 } 1542 } 1543 1544 public int getPasswordQuality(ComponentName who, int userHandle) { 1545 if (!mHasFeature) { 1546 return DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 1547 } 1548 enforceCrossUserPermission(userHandle); 1549 synchronized (this) { 1550 int mode = DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED; 1551 1552 if (who != null) { 1553 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1554 return admin != null ? admin.passwordQuality : mode; 1555 } 1556 1557 // Return strictest policy for this user and profiles that are visible from this user. 1558 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1559 for (UserInfo userInfo : profiles) { 1560 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1561 final int N = policy.mAdminList.size(); 1562 for (int i=0; i<N; i++) { 1563 ActiveAdmin admin = policy.mAdminList.get(i); 1564 if (mode < admin.passwordQuality) { 1565 mode = admin.passwordQuality; 1566 } 1567 } 1568 } 1569 return mode; 1570 } 1571 } 1572 1573 public void setPasswordMinimumLength(ComponentName who, int length, int userHandle) { 1574 if (!mHasFeature) { 1575 return; 1576 } 1577 enforceCrossUserPermission(userHandle); 1578 synchronized (this) { 1579 if (who == null) { 1580 throw new NullPointerException("ComponentName is null"); 1581 } 1582 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1583 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1584 if (ap.minimumPasswordLength != length) { 1585 ap.minimumPasswordLength = length; 1586 saveSettingsLocked(userHandle); 1587 } 1588 } 1589 } 1590 1591 public int getPasswordMinimumLength(ComponentName who, int userHandle) { 1592 if (!mHasFeature) { 1593 return 0; 1594 } 1595 enforceCrossUserPermission(userHandle); 1596 synchronized (this) { 1597 int length = 0; 1598 1599 if (who != null) { 1600 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1601 return admin != null ? admin.minimumPasswordLength : length; 1602 } 1603 1604 // Return strictest policy for this user and profiles that are visible from this user. 1605 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1606 for (UserInfo userInfo : profiles) { 1607 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1608 final int N = policy.mAdminList.size(); 1609 for (int i=0; i<N; i++) { 1610 ActiveAdmin admin = policy.mAdminList.get(i); 1611 if (length < admin.minimumPasswordLength) { 1612 length = admin.minimumPasswordLength; 1613 } 1614 } 1615 } 1616 return length; 1617 } 1618 } 1619 1620 public void setPasswordHistoryLength(ComponentName who, int length, int userHandle) { 1621 if (!mHasFeature) { 1622 return; 1623 } 1624 enforceCrossUserPermission(userHandle); 1625 synchronized (this) { 1626 if (who == null) { 1627 throw new NullPointerException("ComponentName is null"); 1628 } 1629 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1630 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1631 if (ap.passwordHistoryLength != length) { 1632 ap.passwordHistoryLength = length; 1633 saveSettingsLocked(userHandle); 1634 } 1635 } 1636 } 1637 1638 public int getPasswordHistoryLength(ComponentName who, int userHandle) { 1639 if (!mHasFeature) { 1640 return 0; 1641 } 1642 enforceCrossUserPermission(userHandle); 1643 synchronized (this) { 1644 int length = 0; 1645 1646 if (who != null) { 1647 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1648 return admin != null ? admin.passwordHistoryLength : length; 1649 } 1650 1651 // Return strictest policy for this user and profiles that are visible from this user. 1652 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1653 for (UserInfo userInfo : profiles) { 1654 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1655 final int N = policy.mAdminList.size(); 1656 for (int i = 0; i < N; i++) { 1657 ActiveAdmin admin = policy.mAdminList.get(i); 1658 if (length < admin.passwordHistoryLength) { 1659 length = admin.passwordHistoryLength; 1660 } 1661 } 1662 } 1663 return length; 1664 } 1665 } 1666 1667 public void setPasswordExpirationTimeout(ComponentName who, long timeout, int userHandle) { 1668 if (!mHasFeature) { 1669 return; 1670 } 1671 enforceCrossUserPermission(userHandle); 1672 synchronized (this) { 1673 if (who == null) { 1674 throw new NullPointerException("ComponentName is null"); 1675 } 1676 if (timeout < 0) { 1677 throw new IllegalArgumentException("Timeout must be >= 0 ms"); 1678 } 1679 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1680 DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD); 1681 // Calling this API automatically bumps the expiration date 1682 final long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 1683 ap.passwordExpirationDate = expiration; 1684 ap.passwordExpirationTimeout = timeout; 1685 if (timeout > 0L) { 1686 Slog.w(LOG_TAG, "setPasswordExpiration(): password will expire on " 1687 + DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT) 1688 .format(new Date(expiration))); 1689 } 1690 saveSettingsLocked(userHandle); 1691 // in case this is the first one 1692 setExpirationAlarmCheckLocked(mContext, getUserData(userHandle)); 1693 } 1694 } 1695 1696 /** 1697 * Return a single admin's expiration cycle time, or the min of all cycle times. 1698 * Returns 0 if not configured. 1699 */ 1700 public long getPasswordExpirationTimeout(ComponentName who, int userHandle) { 1701 if (!mHasFeature) { 1702 return 0L; 1703 } 1704 enforceCrossUserPermission(userHandle); 1705 synchronized (this) { 1706 long timeout = 0L; 1707 1708 if (who != null) { 1709 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1710 return admin != null ? admin.passwordExpirationTimeout : timeout; 1711 } 1712 1713 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1714 for (UserInfo userInfo : profiles) { 1715 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1716 final int N = policy.mAdminList.size(); 1717 for (int i = 0; i < N; i++) { 1718 ActiveAdmin admin = policy.mAdminList.get(i); 1719 if (timeout == 0L || (admin.passwordExpirationTimeout != 0L 1720 && timeout > admin.passwordExpirationTimeout)) { 1721 timeout = admin.passwordExpirationTimeout; 1722 } 1723 } 1724 } 1725 return timeout; 1726 } 1727 } 1728 1729 /** 1730 * Return a single admin's expiration date/time, or the min (soonest) for all admins. 1731 * Returns 0 if not configured. 1732 */ 1733 private long getPasswordExpirationLocked(ComponentName who, int userHandle) { 1734 long timeout = 0L; 1735 1736 if (who != null) { 1737 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1738 return admin != null ? admin.passwordExpirationDate : timeout; 1739 } 1740 1741 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1742 for (UserInfo userInfo : profiles) { 1743 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1744 final int N = policy.mAdminList.size(); 1745 for (int i = 0; i < N; i++) { 1746 ActiveAdmin admin = policy.mAdminList.get(i); 1747 if (timeout == 0L || (admin.passwordExpirationDate != 0 1748 && timeout > admin.passwordExpirationDate)) { 1749 timeout = admin.passwordExpirationDate; 1750 } 1751 } 1752 } 1753 return timeout; 1754 } 1755 1756 public long getPasswordExpiration(ComponentName who, int userHandle) { 1757 if (!mHasFeature) { 1758 return 0L; 1759 } 1760 enforceCrossUserPermission(userHandle); 1761 synchronized (this) { 1762 return getPasswordExpirationLocked(who, userHandle); 1763 } 1764 } 1765 1766 public void setPasswordMinimumUpperCase(ComponentName who, int length, int userHandle) { 1767 if (!mHasFeature) { 1768 return; 1769 } 1770 enforceCrossUserPermission(userHandle); 1771 synchronized (this) { 1772 if (who == null) { 1773 throw new NullPointerException("ComponentName is null"); 1774 } 1775 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1776 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1777 if (ap.minimumPasswordUpperCase != length) { 1778 ap.minimumPasswordUpperCase = length; 1779 saveSettingsLocked(userHandle); 1780 } 1781 } 1782 } 1783 1784 public int getPasswordMinimumUpperCase(ComponentName who, int userHandle) { 1785 if (!mHasFeature) { 1786 return 0; 1787 } 1788 enforceCrossUserPermission(userHandle); 1789 synchronized (this) { 1790 int length = 0; 1791 1792 if (who != null) { 1793 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1794 return admin != null ? admin.minimumPasswordUpperCase : length; 1795 } 1796 1797 // Return strictest policy for this user and profiles that are visible from this user. 1798 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1799 for (UserInfo userInfo : profiles) { 1800 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1801 final int N = policy.mAdminList.size(); 1802 for (int i=0; i<N; i++) { 1803 ActiveAdmin admin = policy.mAdminList.get(i); 1804 if (length < admin.minimumPasswordUpperCase) { 1805 length = admin.minimumPasswordUpperCase; 1806 } 1807 } 1808 } 1809 return length; 1810 } 1811 } 1812 1813 public void setPasswordMinimumLowerCase(ComponentName who, int length, int userHandle) { 1814 enforceCrossUserPermission(userHandle); 1815 synchronized (this) { 1816 if (who == null) { 1817 throw new NullPointerException("ComponentName is null"); 1818 } 1819 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1820 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1821 if (ap.minimumPasswordLowerCase != length) { 1822 ap.minimumPasswordLowerCase = length; 1823 saveSettingsLocked(userHandle); 1824 } 1825 } 1826 } 1827 1828 public int getPasswordMinimumLowerCase(ComponentName who, int userHandle) { 1829 if (!mHasFeature) { 1830 return 0; 1831 } 1832 enforceCrossUserPermission(userHandle); 1833 synchronized (this) { 1834 int length = 0; 1835 1836 if (who != null) { 1837 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1838 return admin != null ? admin.minimumPasswordLowerCase : length; 1839 } 1840 1841 // Return strictest policy for this user and profiles that are visible from this user. 1842 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1843 for (UserInfo userInfo : profiles) { 1844 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1845 final int N = policy.mAdminList.size(); 1846 for (int i=0; i<N; i++) { 1847 ActiveAdmin admin = policy.mAdminList.get(i); 1848 if (length < admin.minimumPasswordLowerCase) { 1849 length = admin.minimumPasswordLowerCase; 1850 } 1851 } 1852 } 1853 return length; 1854 } 1855 } 1856 1857 public void setPasswordMinimumLetters(ComponentName who, int length, int userHandle) { 1858 if (!mHasFeature) { 1859 return; 1860 } 1861 enforceCrossUserPermission(userHandle); 1862 synchronized (this) { 1863 if (who == null) { 1864 throw new NullPointerException("ComponentName is null"); 1865 } 1866 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1867 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1868 if (ap.minimumPasswordLetters != length) { 1869 ap.minimumPasswordLetters = length; 1870 saveSettingsLocked(userHandle); 1871 } 1872 } 1873 } 1874 1875 public int getPasswordMinimumLetters(ComponentName who, int userHandle) { 1876 if (!mHasFeature) { 1877 return 0; 1878 } 1879 enforceCrossUserPermission(userHandle); 1880 synchronized (this) { 1881 int length = 0; 1882 1883 if (who != null) { 1884 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1885 return admin != null ? admin.minimumPasswordLetters : length; 1886 } 1887 1888 // Return strictest policy for this user and profiles that are visible from this user. 1889 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1890 for (UserInfo userInfo : profiles) { 1891 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1892 final int N = policy.mAdminList.size(); 1893 for (int i=0; i<N; i++) { 1894 ActiveAdmin admin = policy.mAdminList.get(i); 1895 if (length < admin.minimumPasswordLetters) { 1896 length = admin.minimumPasswordLetters; 1897 } 1898 } 1899 } 1900 return length; 1901 } 1902 } 1903 1904 public void setPasswordMinimumNumeric(ComponentName who, int length, int userHandle) { 1905 if (!mHasFeature) { 1906 return; 1907 } 1908 enforceCrossUserPermission(userHandle); 1909 synchronized (this) { 1910 if (who == null) { 1911 throw new NullPointerException("ComponentName is null"); 1912 } 1913 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1914 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1915 if (ap.minimumPasswordNumeric != length) { 1916 ap.minimumPasswordNumeric = length; 1917 saveSettingsLocked(userHandle); 1918 } 1919 } 1920 } 1921 1922 public int getPasswordMinimumNumeric(ComponentName who, int userHandle) { 1923 if (!mHasFeature) { 1924 return 0; 1925 } 1926 enforceCrossUserPermission(userHandle); 1927 synchronized (this) { 1928 int length = 0; 1929 1930 if (who != null) { 1931 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1932 return admin != null ? admin.minimumPasswordNumeric : length; 1933 } 1934 1935 // Return strictest policy for this user and profiles that are visible from this user. 1936 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1937 for (UserInfo userInfo : profiles) { 1938 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1939 final int N = policy.mAdminList.size(); 1940 for (int i = 0; i < N; i++) { 1941 ActiveAdmin admin = policy.mAdminList.get(i); 1942 if (length < admin.minimumPasswordNumeric) { 1943 length = admin.minimumPasswordNumeric; 1944 } 1945 } 1946 } 1947 return length; 1948 } 1949 } 1950 1951 public void setPasswordMinimumSymbols(ComponentName who, int length, int userHandle) { 1952 if (!mHasFeature) { 1953 return; 1954 } 1955 enforceCrossUserPermission(userHandle); 1956 synchronized (this) { 1957 if (who == null) { 1958 throw new NullPointerException("ComponentName is null"); 1959 } 1960 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 1961 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 1962 if (ap.minimumPasswordSymbols != length) { 1963 ap.minimumPasswordSymbols = length; 1964 saveSettingsLocked(userHandle); 1965 } 1966 } 1967 } 1968 1969 public int getPasswordMinimumSymbols(ComponentName who, int userHandle) { 1970 if (!mHasFeature) { 1971 return 0; 1972 } 1973 enforceCrossUserPermission(userHandle); 1974 synchronized (this) { 1975 int length = 0; 1976 1977 if (who != null) { 1978 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 1979 return admin != null ? admin.minimumPasswordSymbols : length; 1980 } 1981 1982 // Return strictest policy for this user and profiles that are visible from this user. 1983 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 1984 for (UserInfo userInfo : profiles) { 1985 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 1986 final int N = policy.mAdminList.size(); 1987 for (int i=0; i<N; i++) { 1988 ActiveAdmin admin = policy.mAdminList.get(i); 1989 if (length < admin.minimumPasswordSymbols) { 1990 length = admin.minimumPasswordSymbols; 1991 } 1992 } 1993 } 1994 return length; 1995 } 1996 } 1997 1998 public void setPasswordMinimumNonLetter(ComponentName who, int length, int userHandle) { 1999 if (!mHasFeature) { 2000 return; 2001 } 2002 enforceCrossUserPermission(userHandle); 2003 synchronized (this) { 2004 if (who == null) { 2005 throw new NullPointerException("ComponentName is null"); 2006 } 2007 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2008 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2009 if (ap.minimumPasswordNonLetter != length) { 2010 ap.minimumPasswordNonLetter = length; 2011 saveSettingsLocked(userHandle); 2012 } 2013 } 2014 } 2015 2016 public int getPasswordMinimumNonLetter(ComponentName who, int userHandle) { 2017 if (!mHasFeature) { 2018 return 0; 2019 } 2020 enforceCrossUserPermission(userHandle); 2021 synchronized (this) { 2022 int length = 0; 2023 2024 if (who != null) { 2025 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2026 return admin != null ? admin.minimumPasswordNonLetter : length; 2027 } 2028 2029 // Return strictest policy for this user and profiles that are visible from this user. 2030 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2031 for (UserInfo userInfo : profiles) { 2032 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 2033 final int N = policy.mAdminList.size(); 2034 for (int i=0; i<N; i++) { 2035 ActiveAdmin admin = policy.mAdminList.get(i); 2036 if (length < admin.minimumPasswordNonLetter) { 2037 length = admin.minimumPasswordNonLetter; 2038 } 2039 } 2040 } 2041 return length; 2042 } 2043 } 2044 2045 public boolean isActivePasswordSufficient(int userHandle) { 2046 if (!mHasFeature) { 2047 return true; 2048 } 2049 enforceCrossUserPermission(userHandle); 2050 2051 synchronized (this) { 2052 2053 // The active password is stored in the user that runs the launcher 2054 // If the user this is called from is part of a profile group, that is the parent 2055 // of the group. 2056 UserInfo parent = getProfileParent(userHandle); 2057 int id = parent == null ? userHandle : parent.id; 2058 DevicePolicyData policy = getUserData(id); 2059 2060 // This API can only be called by an active device admin, 2061 // so try to retrieve it to check that the caller is one. 2062 getActiveAdminForCallerLocked(null, 2063 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD); 2064 if (policy.mActivePasswordQuality < getPasswordQuality(null, userHandle) 2065 || policy.mActivePasswordLength < getPasswordMinimumLength(null, userHandle)) { 2066 return false; 2067 } 2068 if (policy.mActivePasswordQuality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2069 return true; 2070 } 2071 return policy.mActivePasswordUpperCase >= getPasswordMinimumUpperCase(null, userHandle) 2072 && policy.mActivePasswordLowerCase >= getPasswordMinimumLowerCase(null, userHandle) 2073 && policy.mActivePasswordLetters >= getPasswordMinimumLetters(null, userHandle) 2074 && policy.mActivePasswordNumeric >= getPasswordMinimumNumeric(null, userHandle) 2075 && policy.mActivePasswordSymbols >= getPasswordMinimumSymbols(null, userHandle) 2076 && policy.mActivePasswordNonLetter >= getPasswordMinimumNonLetter(null, userHandle); 2077 } 2078 } 2079 2080 public int getCurrentFailedPasswordAttempts(int userHandle) { 2081 synchronized (this) { 2082 // This API can only be called by an active device admin, 2083 // so try to retrieve it to check that the caller is one. 2084 getActiveAdminForCallerLocked(null, 2085 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN); 2086 2087 // The active password is stored in the parent. 2088 DevicePolicyData policy = getUserData(getProfileParent(userHandle).id); 2089 2090 return policy.mFailedPasswordAttempts; 2091 } 2092 } 2093 2094 public void setMaximumFailedPasswordsForWipe(ComponentName who, int num, int userHandle) { 2095 if (!mHasFeature) { 2096 return; 2097 } 2098 enforceCrossUserPermission(userHandle); 2099 synchronized (this) { 2100 if (who == null) { 2101 throw new NullPointerException("ComponentName is null"); 2102 } 2103 // This API can only be called by an active device admin, 2104 // so try to retrieve it to check that the caller is one. 2105 getActiveAdminForCallerLocked(who, 2106 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 2107 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2108 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN); 2109 if (ap.maximumFailedPasswordsForWipe != num) { 2110 ap.maximumFailedPasswordsForWipe = num; 2111 saveSettingsLocked(userHandle); 2112 } 2113 } 2114 } 2115 2116 public int getMaximumFailedPasswordsForWipe(ComponentName who, int userHandle) { 2117 if (!mHasFeature) { 2118 return 0; 2119 } 2120 enforceCrossUserPermission(userHandle); 2121 synchronized (this) { 2122 int count = 0; 2123 2124 if (who != null) { 2125 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2126 return admin != null ? admin.maximumFailedPasswordsForWipe : count; 2127 } 2128 2129 // Return strictest policy for this user and profiles that are visible from this user. 2130 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2131 for (UserInfo userInfo : profiles) { 2132 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 2133 final int N = policy.mAdminList.size(); 2134 for (int i=0; i<N; i++) { 2135 ActiveAdmin admin = policy.mAdminList.get(i); 2136 if (count == 0) { 2137 count = admin.maximumFailedPasswordsForWipe; 2138 } else if (admin.maximumFailedPasswordsForWipe != 0 2139 && count > admin.maximumFailedPasswordsForWipe) { 2140 count = admin.maximumFailedPasswordsForWipe; 2141 } 2142 } 2143 } 2144 return count; 2145 } 2146 } 2147 2148 public boolean resetPassword(String password, int flags, int userHandle) { 2149 if (!mHasFeature) { 2150 return false; 2151 } 2152 enforceCrossUserPermission(userHandle); 2153 enforceNotManagedProfile(userHandle, "reset the password"); 2154 2155 int quality; 2156 synchronized (this) { 2157 // This api can only be called by an active device admin, 2158 // so try to retrieve it to check that the caller is one. 2159 getActiveAdminForCallerLocked(null, 2160 DeviceAdminInfo.USES_POLICY_RESET_PASSWORD); 2161 quality = getPasswordQuality(null, userHandle); 2162 if (quality != DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) { 2163 int realQuality = LockPatternUtils.computePasswordQuality(password); 2164 if (realQuality < quality 2165 && quality != DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2166 Slog.w(LOG_TAG, "resetPassword: password quality 0x" 2167 + Integer.toHexString(realQuality) 2168 + " does not meet required quality 0x" 2169 + Integer.toHexString(quality)); 2170 return false; 2171 } 2172 quality = Math.max(realQuality, quality); 2173 } 2174 int length = getPasswordMinimumLength(null, userHandle); 2175 if (password.length() < length) { 2176 Slog.w(LOG_TAG, "resetPassword: password length " + password.length() 2177 + " does not meet required length " + length); 2178 return false; 2179 } 2180 if (quality == DevicePolicyManager.PASSWORD_QUALITY_COMPLEX) { 2181 int letters = 0; 2182 int uppercase = 0; 2183 int lowercase = 0; 2184 int numbers = 0; 2185 int symbols = 0; 2186 int nonletter = 0; 2187 for (int i = 0; i < password.length(); i++) { 2188 char c = password.charAt(i); 2189 if (c >= 'A' && c <= 'Z') { 2190 letters++; 2191 uppercase++; 2192 } else if (c >= 'a' && c <= 'z') { 2193 letters++; 2194 lowercase++; 2195 } else if (c >= '0' && c <= '9') { 2196 numbers++; 2197 nonletter++; 2198 } else { 2199 symbols++; 2200 nonletter++; 2201 } 2202 } 2203 int neededLetters = getPasswordMinimumLetters(null, userHandle); 2204 if(letters < neededLetters) { 2205 Slog.w(LOG_TAG, "resetPassword: number of letters " + letters 2206 + " does not meet required number of letters " + neededLetters); 2207 return false; 2208 } 2209 int neededNumbers = getPasswordMinimumNumeric(null, userHandle); 2210 if (numbers < neededNumbers) { 2211 Slog.w(LOG_TAG, "resetPassword: number of numerical digits " + numbers 2212 + " does not meet required number of numerical digits " 2213 + neededNumbers); 2214 return false; 2215 } 2216 int neededLowerCase = getPasswordMinimumLowerCase(null, userHandle); 2217 if (lowercase < neededLowerCase) { 2218 Slog.w(LOG_TAG, "resetPassword: number of lowercase letters " + lowercase 2219 + " does not meet required number of lowercase letters " 2220 + neededLowerCase); 2221 return false; 2222 } 2223 int neededUpperCase = getPasswordMinimumUpperCase(null, userHandle); 2224 if (uppercase < neededUpperCase) { 2225 Slog.w(LOG_TAG, "resetPassword: number of uppercase letters " + uppercase 2226 + " does not meet required number of uppercase letters " 2227 + neededUpperCase); 2228 return false; 2229 } 2230 int neededSymbols = getPasswordMinimumSymbols(null, userHandle); 2231 if (symbols < neededSymbols) { 2232 Slog.w(LOG_TAG, "resetPassword: number of special symbols " + symbols 2233 + " does not meet required number of special symbols " + neededSymbols); 2234 return false; 2235 } 2236 int neededNonLetter = getPasswordMinimumNonLetter(null, userHandle); 2237 if (nonletter < neededNonLetter) { 2238 Slog.w(LOG_TAG, "resetPassword: number of non-letter characters " + nonletter 2239 + " does not meet required number of non-letter characters " 2240 + neededNonLetter); 2241 return false; 2242 } 2243 } 2244 } 2245 2246 int callingUid = Binder.getCallingUid(); 2247 DevicePolicyData policy = getUserData(userHandle); 2248 if (policy.mPasswordOwner >= 0 && policy.mPasswordOwner != callingUid) { 2249 Slog.w(LOG_TAG, "resetPassword: already set by another uid and not entered by user"); 2250 return false; 2251 } 2252 2253 // Don't do this with the lock held, because it is going to call 2254 // back in to the service. 2255 long ident = Binder.clearCallingIdentity(); 2256 try { 2257 LockPatternUtils utils = new LockPatternUtils(mContext); 2258 utils.saveLockPassword(password, quality, false, userHandle); 2259 boolean requireEntry = (flags & DevicePolicyManager.RESET_PASSWORD_REQUIRE_ENTRY) != 0; 2260 if (requireEntry) { 2261 utils.requireCredentialEntry(UserHandle.USER_ALL); 2262 } 2263 synchronized (this) { 2264 int newOwner = requireEntry ? callingUid : -1; 2265 if (policy.mPasswordOwner != newOwner) { 2266 policy.mPasswordOwner = newOwner; 2267 saveSettingsLocked(userHandle); 2268 } 2269 } 2270 } finally { 2271 Binder.restoreCallingIdentity(ident); 2272 } 2273 2274 return true; 2275 } 2276 2277 public void setMaximumTimeToLock(ComponentName who, long timeMs, int userHandle) { 2278 if (!mHasFeature) { 2279 return; 2280 } 2281 enforceCrossUserPermission(userHandle); 2282 synchronized (this) { 2283 if (who == null) { 2284 throw new NullPointerException("ComponentName is null"); 2285 } 2286 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2287 DeviceAdminInfo.USES_POLICY_FORCE_LOCK); 2288 if (ap.maximumTimeToUnlock != timeMs) { 2289 ap.maximumTimeToUnlock = timeMs; 2290 saveSettingsLocked(userHandle); 2291 updateMaximumTimeToLockLocked(getUserData(userHandle)); 2292 } 2293 } 2294 } 2295 2296 void updateMaximumTimeToLockLocked(DevicePolicyData policy) { 2297 long timeMs = getMaximumTimeToLock(null, policy.mUserHandle); 2298 if (policy.mLastMaximumTimeToLock == timeMs) { 2299 return; 2300 } 2301 2302 long ident = Binder.clearCallingIdentity(); 2303 try { 2304 if (timeMs <= 0) { 2305 timeMs = Integer.MAX_VALUE; 2306 } else { 2307 // Make sure KEEP_SCREEN_ON is disabled, since that 2308 // would allow bypassing of the maximum time to lock. 2309 Settings.Global.putInt(mContext.getContentResolver(), 2310 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, 0); 2311 } 2312 2313 policy.mLastMaximumTimeToLock = timeMs; 2314 2315 try { 2316 getIPowerManager().setMaximumScreenOffTimeoutFromDeviceAdmin((int)timeMs); 2317 } catch (RemoteException e) { 2318 Slog.w(LOG_TAG, "Failure talking with power manager", e); 2319 } 2320 } finally { 2321 Binder.restoreCallingIdentity(ident); 2322 } 2323 } 2324 2325 public long getMaximumTimeToLock(ComponentName who, int userHandle) { 2326 if (!mHasFeature) { 2327 return 0; 2328 } 2329 enforceCrossUserPermission(userHandle); 2330 synchronized (this) { 2331 long time = 0; 2332 2333 if (who != null) { 2334 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2335 return admin != null ? admin.maximumTimeToUnlock : time; 2336 } 2337 2338 // Return strictest policy for this user and profiles that are visible from this user. 2339 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2340 for (UserInfo userInfo : profiles) { 2341 DevicePolicyData policy = getUserData(userInfo.getUserHandle().getIdentifier()); 2342 final int N = policy.mAdminList.size(); 2343 for (int i=0; i<N; i++) { 2344 ActiveAdmin admin = policy.mAdminList.get(i); 2345 if (time == 0) { 2346 time = admin.maximumTimeToUnlock; 2347 } else if (admin.maximumTimeToUnlock != 0 2348 && time > admin.maximumTimeToUnlock) { 2349 time = admin.maximumTimeToUnlock; 2350 } 2351 } 2352 } 2353 return time; 2354 } 2355 } 2356 2357 public void lockNow() { 2358 if (!mHasFeature) { 2359 return; 2360 } 2361 synchronized (this) { 2362 // This API can only be called by an active device admin, 2363 // so try to retrieve it to check that the caller is one. 2364 getActiveAdminForCallerLocked(null, 2365 DeviceAdminInfo.USES_POLICY_FORCE_LOCK); 2366 lockNowUnchecked(); 2367 } 2368 } 2369 2370 private void lockNowUnchecked() { 2371 long ident = Binder.clearCallingIdentity(); 2372 try { 2373 // Power off the display 2374 getIPowerManager().goToSleep(SystemClock.uptimeMillis(), 2375 PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN, 0); 2376 // Ensure the device is locked 2377 new LockPatternUtils(mContext).requireCredentialEntry(UserHandle.USER_ALL); 2378 getWindowManager().lockNow(null); 2379 } catch (RemoteException e) { 2380 } finally { 2381 Binder.restoreCallingIdentity(ident); 2382 } 2383 } 2384 2385 private boolean isExtStorageEncrypted() { 2386 String state = SystemProperties.get("vold.decrypt"); 2387 return !"".equals(state); 2388 } 2389 2390 public boolean installCaCert(ComponentName who, byte[] certBuffer) throws RemoteException { 2391 if (who == null) { 2392 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 2393 } else { 2394 synchronized (this) { 2395 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 2396 } 2397 } 2398 2399 byte[] pemCert; 2400 try { 2401 X509Certificate cert = parseCert(certBuffer); 2402 pemCert = Credentials.convertToPem(cert); 2403 } catch (CertificateException ce) { 2404 Log.e(LOG_TAG, "Problem converting cert", ce); 2405 return false; 2406 } catch (IOException ioe) { 2407 Log.e(LOG_TAG, "Problem reading cert", ioe); 2408 return false; 2409 } 2410 2411 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 2412 final long id = Binder.clearCallingIdentity(); 2413 try { 2414 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 2415 try { 2416 keyChainConnection.getService().installCaCertificate(pemCert); 2417 return true; 2418 } catch (RemoteException e) { 2419 Log.e(LOG_TAG, "installCaCertsToKeyChain(): ", e); 2420 } finally { 2421 keyChainConnection.close(); 2422 } 2423 } catch (InterruptedException e1) { 2424 Log.w(LOG_TAG, "installCaCertsToKeyChain(): ", e1); 2425 Thread.currentThread().interrupt(); 2426 } finally { 2427 Binder.restoreCallingIdentity(id); 2428 } 2429 return false; 2430 } 2431 2432 private static X509Certificate parseCert(byte[] certBuffer) 2433 throws CertificateException, IOException { 2434 CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); 2435 return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream( 2436 certBuffer)); 2437 } 2438 2439 public void uninstallCaCert(ComponentName who, String alias) { 2440 if (who == null) { 2441 mContext.enforceCallingOrSelfPermission(MANAGE_CA_CERTIFICATES, null); 2442 } else { 2443 synchronized (this) { 2444 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 2445 } 2446 } 2447 2448 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 2449 final long id = Binder.clearCallingIdentity(); 2450 try { 2451 final KeyChainConnection keyChainConnection = KeyChain.bindAsUser(mContext, userHandle); 2452 try { 2453 keyChainConnection.getService().deleteCaCertificate(alias); 2454 } catch (RemoteException e) { 2455 Log.e(LOG_TAG, "from CaCertUninstaller: ", e); 2456 } finally { 2457 keyChainConnection.close(); 2458 } 2459 } catch (InterruptedException ie) { 2460 Log.w(LOG_TAG, "CaCertUninstaller: ", ie); 2461 Thread.currentThread().interrupt(); 2462 } finally { 2463 Binder.restoreCallingIdentity(id); 2464 } 2465 } 2466 2467 void wipeDataLocked(int flags) { 2468 // If the SD card is encrypted and non-removable, we have to force a wipe. 2469 boolean forceExtWipe = !Environment.isExternalStorageRemovable() && isExtStorageEncrypted(); 2470 boolean wipeExtRequested = (flags&DevicePolicyManager.WIPE_EXTERNAL_STORAGE) != 0; 2471 2472 // Note: we can only do the wipe via ExternalStorageFormatter if the volume is not emulated. 2473 if ((forceExtWipe || wipeExtRequested) && !Environment.isExternalStorageEmulated()) { 2474 Intent intent = new Intent(ExternalStorageFormatter.FORMAT_AND_FACTORY_RESET); 2475 intent.putExtra(ExternalStorageFormatter.EXTRA_ALWAYS_RESET, true); 2476 intent.setComponent(ExternalStorageFormatter.COMPONENT_NAME); 2477 mWakeLock.acquire(10000); 2478 mContext.startService(intent); 2479 } else { 2480 try { 2481 RecoverySystem.rebootWipeUserData(mContext); 2482 } catch (IOException e) { 2483 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 2484 } catch (SecurityException e) { 2485 Slog.w(LOG_TAG, "Failed requesting data wipe", e); 2486 } 2487 } 2488 } 2489 2490 public void wipeData(int flags, final int userHandle) { 2491 if (!mHasFeature) { 2492 return; 2493 } 2494 enforceCrossUserPermission(userHandle); 2495 if ((flags & DevicePolicyManager.WIPE_EXTERNAL_STORAGE) != 0) { 2496 enforceNotManagedProfile(userHandle, "wipe external storage"); 2497 } 2498 synchronized (this) { 2499 // This API can only be called by an active device admin, 2500 // so try to retrieve it to check that the caller is one. 2501 getActiveAdminForCallerLocked(null, 2502 DeviceAdminInfo.USES_POLICY_WIPE_DATA); 2503 long ident = Binder.clearCallingIdentity(); 2504 try { 2505 wipeDeviceOrUserLocked(flags, userHandle); 2506 } finally { 2507 Binder.restoreCallingIdentity(ident); 2508 } 2509 } 2510 } 2511 2512 private void wipeDeviceOrUserLocked(int flags, final int userHandle) { 2513 if (userHandle == UserHandle.USER_OWNER) { 2514 wipeDataLocked(flags); 2515 } else { 2516 lockNowUnchecked(); 2517 mHandler.post(new Runnable() { 2518 public void run() { 2519 try { 2520 ActivityManagerNative.getDefault().switchUser(UserHandle.USER_OWNER); 2521 (mUserManager) 2522 .removeUser(userHandle); 2523 } catch (RemoteException re) { 2524 // Shouldn't happen 2525 } 2526 } 2527 }); 2528 } 2529 } 2530 2531 public void getRemoveWarning(ComponentName comp, final RemoteCallback result, int userHandle) { 2532 if (!mHasFeature) { 2533 return; 2534 } 2535 enforceCrossUserPermission(userHandle); 2536 mContext.enforceCallingOrSelfPermission( 2537 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 2538 2539 synchronized (this) { 2540 ActiveAdmin admin = getActiveAdminUncheckedLocked(comp, userHandle); 2541 if (admin == null) { 2542 try { 2543 result.sendResult(null); 2544 } catch (RemoteException e) { 2545 } 2546 return; 2547 } 2548 Intent intent = new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLE_REQUESTED); 2549 intent.setComponent(admin.info.getComponent()); 2550 mContext.sendOrderedBroadcastAsUser(intent, new UserHandle(userHandle), 2551 null, new BroadcastReceiver() { 2552 @Override 2553 public void onReceive(Context context, Intent intent) { 2554 try { 2555 result.sendResult(getResultExtras(false)); 2556 } catch (RemoteException e) { 2557 } 2558 } 2559 }, null, Activity.RESULT_OK, null, null); 2560 } 2561 } 2562 2563 public void setActivePasswordState(int quality, int length, int letters, int uppercase, 2564 int lowercase, int numbers, int symbols, int nonletter, int userHandle) { 2565 if (!mHasFeature) { 2566 return; 2567 } 2568 enforceCrossUserPermission(userHandle); 2569 enforceNotManagedProfile(userHandle, "set the active password"); 2570 2571 mContext.enforceCallingOrSelfPermission( 2572 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 2573 DevicePolicyData p = getUserData(userHandle); 2574 2575 validateQualityConstant(quality); 2576 2577 synchronized (this) { 2578 if (p.mActivePasswordQuality != quality || p.mActivePasswordLength != length 2579 || p.mFailedPasswordAttempts != 0 || p.mActivePasswordLetters != letters 2580 || p.mActivePasswordUpperCase != uppercase 2581 || p.mActivePasswordLowerCase != lowercase 2582 || p.mActivePasswordNumeric != numbers 2583 || p.mActivePasswordSymbols != symbols 2584 || p.mActivePasswordNonLetter != nonletter) { 2585 long ident = Binder.clearCallingIdentity(); 2586 try { 2587 p.mActivePasswordQuality = quality; 2588 p.mActivePasswordLength = length; 2589 p.mActivePasswordLetters = letters; 2590 p.mActivePasswordLowerCase = lowercase; 2591 p.mActivePasswordUpperCase = uppercase; 2592 p.mActivePasswordNumeric = numbers; 2593 p.mActivePasswordSymbols = symbols; 2594 p.mActivePasswordNonLetter = nonletter; 2595 p.mFailedPasswordAttempts = 0; 2596 saveSettingsLocked(userHandle); 2597 updatePasswordExpirationsLocked(userHandle); 2598 setExpirationAlarmCheckLocked(mContext, p); 2599 sendAdminCommandToSelfAndProfilesLocked( 2600 DeviceAdminReceiver.ACTION_PASSWORD_CHANGED, 2601 DeviceAdminInfo.USES_POLICY_LIMIT_PASSWORD, userHandle); 2602 } finally { 2603 Binder.restoreCallingIdentity(ident); 2604 } 2605 } 2606 } 2607 } 2608 2609 /** 2610 * Called any time the device password is updated. Resets all password expiration clocks. 2611 */ 2612 private void updatePasswordExpirationsLocked(int userHandle) { 2613 List<UserInfo> profiles = mUserManager.getProfiles(userHandle); 2614 for (UserInfo userInfo : profiles) { 2615 int profileId = userInfo.getUserHandle().getIdentifier(); 2616 DevicePolicyData policy = getUserData(profileId); 2617 final int N = policy.mAdminList.size(); 2618 if (N > 0) { 2619 for (int i=0; i<N; i++) { 2620 ActiveAdmin admin = policy.mAdminList.get(i); 2621 if (admin.info.usesPolicy(DeviceAdminInfo.USES_POLICY_EXPIRE_PASSWORD)) { 2622 long timeout = admin.passwordExpirationTimeout; 2623 long expiration = timeout > 0L ? (timeout + System.currentTimeMillis()) : 0L; 2624 admin.passwordExpirationDate = expiration; 2625 } 2626 } 2627 } 2628 saveSettingsLocked(profileId); 2629 } 2630 } 2631 2632 public void reportFailedPasswordAttempt(int userHandle) { 2633 enforceCrossUserPermission(userHandle); 2634 enforceNotManagedProfile(userHandle, "report failed password attempt"); 2635 mContext.enforceCallingOrSelfPermission( 2636 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 2637 2638 synchronized (this) { 2639 DevicePolicyData policy = getUserData(userHandle); 2640 long ident = Binder.clearCallingIdentity(); 2641 try { 2642 policy.mFailedPasswordAttempts++; 2643 saveSettingsLocked(userHandle); 2644 if (mHasFeature) { 2645 int max = getMaximumFailedPasswordsForWipe(null, userHandle); 2646 if (max > 0 && policy.mFailedPasswordAttempts >= max) { 2647 wipeDeviceOrUserLocked(0, userHandle); 2648 } 2649 sendAdminCommandToSelfAndProfilesLocked( 2650 DeviceAdminReceiver.ACTION_PASSWORD_FAILED, 2651 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 2652 } 2653 } finally { 2654 Binder.restoreCallingIdentity(ident); 2655 } 2656 } 2657 } 2658 2659 public void reportSuccessfulPasswordAttempt(int userHandle) { 2660 enforceCrossUserPermission(userHandle); 2661 mContext.enforceCallingOrSelfPermission( 2662 android.Manifest.permission.BIND_DEVICE_ADMIN, null); 2663 2664 synchronized (this) { 2665 DevicePolicyData policy = getUserData(userHandle); 2666 if (policy.mFailedPasswordAttempts != 0 || policy.mPasswordOwner >= 0) { 2667 long ident = Binder.clearCallingIdentity(); 2668 try { 2669 policy.mFailedPasswordAttempts = 0; 2670 policy.mPasswordOwner = -1; 2671 saveSettingsLocked(userHandle); 2672 if (mHasFeature) { 2673 sendAdminCommandToSelfAndProfilesLocked( 2674 DeviceAdminReceiver.ACTION_PASSWORD_SUCCEEDED, 2675 DeviceAdminInfo.USES_POLICY_WATCH_LOGIN, userHandle); 2676 } 2677 } finally { 2678 Binder.restoreCallingIdentity(ident); 2679 } 2680 } 2681 } 2682 } 2683 2684 public ComponentName setGlobalProxy(ComponentName who, String proxySpec, 2685 String exclusionList, int userHandle) { 2686 if (!mHasFeature) { 2687 return null; 2688 } 2689 enforceCrossUserPermission(userHandle); 2690 synchronized(this) { 2691 if (who == null) { 2692 throw new NullPointerException("ComponentName is null"); 2693 } 2694 2695 // Only check if owner has set global proxy. We don't allow other users to set it. 2696 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 2697 ActiveAdmin admin = getActiveAdminForCallerLocked(who, 2698 DeviceAdminInfo.USES_POLICY_SETS_GLOBAL_PROXY); 2699 2700 // Scan through active admins and find if anyone has already 2701 // set the global proxy. 2702 Set<ComponentName> compSet = policy.mAdminMap.keySet(); 2703 for (ComponentName component : compSet) { 2704 ActiveAdmin ap = policy.mAdminMap.get(component); 2705 if ((ap.specifiesGlobalProxy) && (!component.equals(who))) { 2706 // Another admin already sets the global proxy 2707 // Return it to the caller. 2708 return component; 2709 } 2710 } 2711 2712 // If the user is not the owner, don't set the global proxy. Fail silently. 2713 if (UserHandle.getCallingUserId() != UserHandle.USER_OWNER) { 2714 Slog.w(LOG_TAG, "Only the owner is allowed to set the global proxy. User " 2715 + userHandle + " is not permitted."); 2716 return null; 2717 } 2718 if (proxySpec == null) { 2719 admin.specifiesGlobalProxy = false; 2720 admin.globalProxySpec = null; 2721 admin.globalProxyExclusionList = null; 2722 } else { 2723 2724 admin.specifiesGlobalProxy = true; 2725 admin.globalProxySpec = proxySpec; 2726 admin.globalProxyExclusionList = exclusionList; 2727 } 2728 2729 // Reset the global proxy accordingly 2730 // Do this using system permissions, as apps cannot write to secure settings 2731 long origId = Binder.clearCallingIdentity(); 2732 try { 2733 resetGlobalProxyLocked(policy); 2734 } finally { 2735 Binder.restoreCallingIdentity(origId); 2736 } 2737 return null; 2738 } 2739 } 2740 2741 public ComponentName getGlobalProxyAdmin(int userHandle) { 2742 if (!mHasFeature) { 2743 return null; 2744 } 2745 enforceCrossUserPermission(userHandle); 2746 synchronized(this) { 2747 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 2748 // Scan through active admins and find if anyone has already 2749 // set the global proxy. 2750 final int N = policy.mAdminList.size(); 2751 for (int i = 0; i < N; i++) { 2752 ActiveAdmin ap = policy.mAdminList.get(i); 2753 if (ap.specifiesGlobalProxy) { 2754 // Device admin sets the global proxy 2755 // Return it to the caller. 2756 return ap.info.getComponent(); 2757 } 2758 } 2759 } 2760 // No device admin sets the global proxy. 2761 return null; 2762 } 2763 2764 public void setRecommendedGlobalProxy(ComponentName who, ProxyInfo proxyInfo) { 2765 synchronized (this) { 2766 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 2767 } 2768 long token = Binder.clearCallingIdentity(); 2769 try { 2770 ConnectivityManager connectivityManager = (ConnectivityManager) 2771 mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 2772 connectivityManager.setGlobalProxy(proxyInfo); 2773 } finally { 2774 Binder.restoreCallingIdentity(token); 2775 } 2776 } 2777 2778 private void resetGlobalProxyLocked(DevicePolicyData policy) { 2779 final int N = policy.mAdminList.size(); 2780 for (int i = 0; i < N; i++) { 2781 ActiveAdmin ap = policy.mAdminList.get(i); 2782 if (ap.specifiesGlobalProxy) { 2783 saveGlobalProxyLocked(ap.globalProxySpec, ap.globalProxyExclusionList); 2784 return; 2785 } 2786 } 2787 // No device admins defining global proxies - reset global proxy settings to none 2788 saveGlobalProxyLocked(null, null); 2789 } 2790 2791 private void saveGlobalProxyLocked(String proxySpec, String exclusionList) { 2792 if (exclusionList == null) { 2793 exclusionList = ""; 2794 } 2795 if (proxySpec == null) { 2796 proxySpec = ""; 2797 } 2798 // Remove white spaces 2799 proxySpec = proxySpec.trim(); 2800 String data[] = proxySpec.split(":"); 2801 int proxyPort = 8080; 2802 if (data.length > 1) { 2803 try { 2804 proxyPort = Integer.parseInt(data[1]); 2805 } catch (NumberFormatException e) {} 2806 } 2807 exclusionList = exclusionList.trim(); 2808 ContentResolver res = mContext.getContentResolver(); 2809 2810 ProxyInfo proxyProperties = new ProxyInfo(data[0], proxyPort, exclusionList); 2811 if (!proxyProperties.isValid()) { 2812 Slog.e(LOG_TAG, "Invalid proxy properties, ignoring: " + proxyProperties.toString()); 2813 return; 2814 } 2815 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, data[0]); 2816 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, proxyPort); 2817 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST, 2818 exclusionList); 2819 } 2820 2821 /** 2822 * Set the storage encryption request for a single admin. Returns the new total request 2823 * status (for all admins). 2824 */ 2825 public int setStorageEncryption(ComponentName who, boolean encrypt, int userHandle) { 2826 if (!mHasFeature) { 2827 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 2828 } 2829 enforceCrossUserPermission(userHandle); 2830 synchronized (this) { 2831 // Check for permissions 2832 if (who == null) { 2833 throw new NullPointerException("ComponentName is null"); 2834 } 2835 // Only owner can set storage encryption 2836 if (userHandle != UserHandle.USER_OWNER 2837 || UserHandle.getCallingUserId() != UserHandle.USER_OWNER) { 2838 Slog.w(LOG_TAG, "Only owner is allowed to set storage encryption. User " 2839 + UserHandle.getCallingUserId() + " is not permitted."); 2840 return 0; 2841 } 2842 2843 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2844 DeviceAdminInfo.USES_ENCRYPTED_STORAGE); 2845 2846 // Quick exit: If the filesystem does not support encryption, we can exit early. 2847 if (!isEncryptionSupported()) { 2848 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 2849 } 2850 2851 // (1) Record the value for the admin so it's sticky 2852 if (ap.encryptionRequested != encrypt) { 2853 ap.encryptionRequested = encrypt; 2854 saveSettingsLocked(userHandle); 2855 } 2856 2857 DevicePolicyData policy = getUserData(UserHandle.USER_OWNER); 2858 // (2) Compute "max" for all admins 2859 boolean newRequested = false; 2860 final int N = policy.mAdminList.size(); 2861 for (int i = 0; i < N; i++) { 2862 newRequested |= policy.mAdminList.get(i).encryptionRequested; 2863 } 2864 2865 // Notify OS of new request 2866 setEncryptionRequested(newRequested); 2867 2868 // Return the new global request status 2869 return newRequested 2870 ? DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE 2871 : DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 2872 } 2873 } 2874 2875 /** 2876 * Get the current storage encryption request status for a given admin, or aggregate of all 2877 * active admins. 2878 */ 2879 public boolean getStorageEncryption(ComponentName who, int userHandle) { 2880 if (!mHasFeature) { 2881 return false; 2882 } 2883 enforceCrossUserPermission(userHandle); 2884 synchronized (this) { 2885 // Check for permissions if a particular caller is specified 2886 if (who != null) { 2887 // When checking for a single caller, status is based on caller's request 2888 ActiveAdmin ap = getActiveAdminUncheckedLocked(who, userHandle); 2889 return ap != null ? ap.encryptionRequested : false; 2890 } 2891 2892 // If no particular caller is specified, return the aggregate set of requests. 2893 // This is short circuited by returning true on the first hit. 2894 DevicePolicyData policy = getUserData(userHandle); 2895 final int N = policy.mAdminList.size(); 2896 for (int i = 0; i < N; i++) { 2897 if (policy.mAdminList.get(i).encryptionRequested) { 2898 return true; 2899 } 2900 } 2901 return false; 2902 } 2903 } 2904 2905 /** 2906 * Get the current encryption status of the device. 2907 */ 2908 public int getStorageEncryptionStatus(int userHandle) { 2909 if (!mHasFeature) { 2910 // Ok to return current status. 2911 } 2912 enforceCrossUserPermission(userHandle); 2913 return getEncryptionStatus(); 2914 } 2915 2916 /** 2917 * Hook to low-levels: This should report if the filesystem supports encrypted storage. 2918 */ 2919 private boolean isEncryptionSupported() { 2920 // Note, this can be implemented as 2921 // return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 2922 // But is provided as a separate internal method if there's a faster way to do a 2923 // simple check for supported-or-not. 2924 return getEncryptionStatus() != DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 2925 } 2926 2927 /** 2928 * Hook to low-levels: Reporting the current status of encryption. 2929 * @return A value such as {@link DevicePolicyManager#ENCRYPTION_STATUS_UNSUPPORTED} or 2930 * {@link DevicePolicyManager#ENCRYPTION_STATUS_INACTIVE} or 2931 * {@link DevicePolicyManager#ENCRYPTION_STATUS_ACTIVE}. 2932 */ 2933 private int getEncryptionStatus() { 2934 String status = SystemProperties.get("ro.crypto.state", "unsupported"); 2935 if ("encrypted".equalsIgnoreCase(status)) { 2936 return DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE; 2937 } else if ("unencrypted".equalsIgnoreCase(status)) { 2938 return DevicePolicyManager.ENCRYPTION_STATUS_INACTIVE; 2939 } else { 2940 return DevicePolicyManager.ENCRYPTION_STATUS_UNSUPPORTED; 2941 } 2942 } 2943 2944 /** 2945 * Hook to low-levels: If needed, record the new admin setting for encryption. 2946 */ 2947 private void setEncryptionRequested(boolean encrypt) { 2948 } 2949 2950 /** 2951 * The system property used to share the state of the camera. The native camera service 2952 * is expected to read this property and act accordingly. 2953 */ 2954 public static final String SYSTEM_PROP_DISABLE_CAMERA = "sys.secpolicy.camera.disabled"; 2955 2956 /** 2957 * Disables all device cameras according to the specified admin. 2958 */ 2959 public void setCameraDisabled(ComponentName who, boolean disabled, int userHandle) { 2960 if (!mHasFeature) { 2961 return; 2962 } 2963 enforceCrossUserPermission(userHandle); 2964 enforceNotManagedProfile(userHandle, "enable/disable cameras"); 2965 synchronized (this) { 2966 if (who == null) { 2967 throw new NullPointerException("ComponentName is null"); 2968 } 2969 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 2970 DeviceAdminInfo.USES_POLICY_DISABLE_CAMERA); 2971 if (ap.disableCamera != disabled) { 2972 ap.disableCamera = disabled; 2973 saveSettingsLocked(userHandle); 2974 } 2975 syncDeviceCapabilitiesLocked(getUserData(userHandle)); 2976 } 2977 } 2978 2979 /** 2980 * Gets whether or not all device cameras are disabled for a given admin, or disabled for any 2981 * active admins. 2982 */ 2983 public boolean getCameraDisabled(ComponentName who, int userHandle) { 2984 if (!mHasFeature) { 2985 return false; 2986 } 2987 synchronized (this) { 2988 if (who != null) { 2989 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 2990 return (admin != null) ? admin.disableCamera : false; 2991 } 2992 2993 DevicePolicyData policy = getUserData(userHandle); 2994 // Determine whether or not the device camera is disabled for any active admins. 2995 final int N = policy.mAdminList.size(); 2996 for (int i = 0; i < N; i++) { 2997 ActiveAdmin admin = policy.mAdminList.get(i); 2998 if (admin.disableCamera) { 2999 return true; 3000 } 3001 } 3002 return false; 3003 } 3004 } 3005 3006 /** 3007 * Selectively disable keyguard features. 3008 */ 3009 public void setKeyguardDisabledFeatures(ComponentName who, int which, int userHandle) { 3010 if (!mHasFeature) { 3011 return; 3012 } 3013 enforceCrossUserPermission(userHandle); 3014 enforceNotManagedProfile(userHandle, "disable keyguard features"); 3015 synchronized (this) { 3016 if (who == null) { 3017 throw new NullPointerException("ComponentName is null"); 3018 } 3019 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3020 DeviceAdminInfo.USES_POLICY_DISABLE_KEYGUARD_FEATURES); 3021 if (ap.disabledKeyguardFeatures != which) { 3022 ap.disabledKeyguardFeatures = which; 3023 saveSettingsLocked(userHandle); 3024 } 3025 syncDeviceCapabilitiesLocked(getUserData(userHandle)); 3026 } 3027 } 3028 3029 /** 3030 * Gets the disabled state for features in keyguard for the given admin, 3031 * or the aggregate of all active admins if who is null. 3032 */ 3033 public int getKeyguardDisabledFeatures(ComponentName who, int userHandle) { 3034 if (!mHasFeature) { 3035 return 0; 3036 } 3037 enforceCrossUserPermission(userHandle); 3038 synchronized (this) { 3039 if (who != null) { 3040 ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userHandle); 3041 return (admin != null) ? admin.disabledKeyguardFeatures : 0; 3042 } 3043 3044 // Determine which keyguard features are disabled for any active admins. 3045 DevicePolicyData policy = getUserData(userHandle); 3046 final int N = policy.mAdminList.size(); 3047 int which = 0; 3048 for (int i = 0; i < N; i++) { 3049 ActiveAdmin admin = policy.mAdminList.get(i); 3050 which |= admin.disabledKeyguardFeatures; 3051 } 3052 return which; 3053 } 3054 } 3055 3056 @Override 3057 public boolean setDeviceOwner(String packageName, String ownerName) { 3058 if (!mHasFeature) { 3059 return false; 3060 } 3061 if (packageName == null 3062 || !DeviceOwner.isInstalled(packageName, mContext.getPackageManager())) { 3063 throw new IllegalArgumentException("Invalid package name " + packageName 3064 + " for device owner"); 3065 } 3066 synchronized (this) { 3067 if (isDeviceProvisioned()) { 3068 throw new IllegalStateException( 3069 "Trying to set device owner but device is already provisioned."); 3070 } 3071 3072 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) { 3073 throw new IllegalStateException( 3074 "Trying to set device owner but device owner is already set."); 3075 } 3076 3077 long token = Binder.clearCallingIdentity(); 3078 try { 3079 mAppOpsService.setDeviceOwner(packageName); 3080 } catch (RemoteException e) { 3081 Log.w(LOG_TAG, "Unable to notify AppOpsService of DeviceOwner", e); 3082 } finally { 3083 Binder.restoreCallingIdentity(token); 3084 } 3085 if (mDeviceOwner == null) { 3086 // Device owner is not set and does not exist, set it. 3087 mDeviceOwner = DeviceOwner.createWithDeviceOwner(packageName, ownerName); 3088 mDeviceOwner.writeOwnerFile(); 3089 return true; 3090 } else { 3091 // Device owner is not set but a profile owner exists, update Device owner state. 3092 mDeviceOwner.setDeviceOwner(packageName, ownerName); 3093 mDeviceOwner.writeOwnerFile(); 3094 return true; 3095 } 3096 } 3097 } 3098 3099 @Override 3100 public boolean isDeviceOwner(String packageName) { 3101 if (!mHasFeature) { 3102 return false; 3103 } 3104 synchronized (this) { 3105 return mDeviceOwner != null 3106 && mDeviceOwner.hasDeviceOwner() 3107 && mDeviceOwner.getDeviceOwnerPackageName().equals(packageName); 3108 } 3109 } 3110 3111 @Override 3112 public String getDeviceOwner() { 3113 if (!mHasFeature) { 3114 return null; 3115 } 3116 synchronized (this) { 3117 if (mDeviceOwner != null && mDeviceOwner.hasDeviceOwner()) { 3118 return mDeviceOwner.getDeviceOwnerPackageName(); 3119 } 3120 } 3121 return null; 3122 } 3123 3124 @Override 3125 public String getDeviceOwnerName() { 3126 if (!mHasFeature) { 3127 return null; 3128 } 3129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 3130 synchronized (this) { 3131 if (mDeviceOwner != null) { 3132 return mDeviceOwner.getDeviceOwnerName(); 3133 } 3134 } 3135 return null; 3136 } 3137 3138 @Override 3139 public void clearDeviceOwner(String packageName) { 3140 if (packageName == null) { 3141 throw new NullPointerException("packageName is null"); 3142 } 3143 try { 3144 int uid = mContext.getPackageManager().getPackageUid(packageName, 0); 3145 if (uid != Binder.getCallingUid()) { 3146 throw new SecurityException("Invalid packageName"); 3147 } 3148 } catch (NameNotFoundException e) { 3149 throw new SecurityException(e); 3150 } 3151 if (!isDeviceOwner(packageName)) { 3152 throw new SecurityException("clearDeviceOwner can only be called by the device owner"); 3153 } 3154 synchronized (this) { 3155 long ident = Binder.clearCallingIdentity(); 3156 try { 3157 mUserManager.setUserRestrictions(new Bundle(), 3158 new UserHandle(UserHandle.USER_OWNER)); 3159 if (mDeviceOwner != null) { 3160 mDeviceOwner.clearDeviceOwner(); 3161 mDeviceOwner.writeOwnerFile(); 3162 } 3163 } finally { 3164 Binder.restoreCallingIdentity(ident); 3165 } 3166 } 3167 } 3168 3169 @Override 3170 public boolean setProfileOwner(String packageName, String ownerName, int userHandle) { 3171 if (!mHasFeature) { 3172 return false; 3173 } 3174 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 3175 3176 if (mUserManager.getUserInfo(userHandle) == null) { 3177 // User doesn't exist. 3178 throw new IllegalArgumentException( 3179 "Attempted to set profile owner for invalid userId: " + userHandle); 3180 } 3181 3182 if (packageName == null 3183 || !DeviceOwner.isInstalledForUser(packageName, userHandle)) { 3184 throw new IllegalArgumentException("Package name " + packageName 3185 + " not installed for userId:" + userHandle); 3186 } 3187 synchronized (this) { 3188 if (isUserSetupComplete(userHandle)) { 3189 throw new IllegalStateException( 3190 "Trying to set profile owner but user is already set-up."); 3191 } 3192 long token = Binder.clearCallingIdentity(); 3193 try { 3194 mAppOpsService.setProfileOwner(packageName, userHandle); 3195 } catch (RemoteException e) { 3196 Log.w(LOG_TAG, "Unable to notify AppOpsService of ProfileOwner", e); 3197 } finally { 3198 Binder.restoreCallingIdentity(token); 3199 } 3200 if (mDeviceOwner == null) { 3201 // Device owner state does not exist, create it. 3202 mDeviceOwner = DeviceOwner.createWithProfileOwner(packageName, ownerName, 3203 userHandle); 3204 mDeviceOwner.writeOwnerFile(); 3205 return true; 3206 } else { 3207 // Device owner already exists, update it. 3208 mDeviceOwner.setProfileOwner(packageName, ownerName, userHandle); 3209 mDeviceOwner.writeOwnerFile(); 3210 return true; 3211 } 3212 } 3213 } 3214 3215 @Override 3216 public void setProfileEnabled(ComponentName who) { 3217 if (!mHasFeature) { 3218 return; 3219 } 3220 synchronized (this) { 3221 // Check for permissions 3222 if (who == null) { 3223 throw new NullPointerException("ComponentName is null"); 3224 } 3225 // Check if this is the profile owner who is calling 3226 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3227 int userId = UserHandle.getCallingUserId(); 3228 3229 long id = Binder.clearCallingIdentity(); 3230 try { 3231 mUserManager.setUserEnabled(userId); 3232 Intent intent = new Intent(Intent.ACTION_MANAGED_PROFILE_ADDED); 3233 intent.putExtra(Intent.EXTRA_USER, new UserHandle(UserHandle.getCallingUserId())); 3234 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | 3235 Intent.FLAG_RECEIVER_FOREGROUND); 3236 // TODO This should send to parent of profile (which is always owner at the moment). 3237 mContext.sendBroadcastAsUser(intent, UserHandle.OWNER); 3238 } finally { 3239 restoreCallingIdentity(id); 3240 } 3241 } 3242 } 3243 3244 @Override 3245 public void setProfileName(ComponentName who, String profileName) { 3246 int userId = UserHandle.getCallingUserId(); 3247 3248 if (who == null) { 3249 throw new NullPointerException("ComponentName is null"); 3250 } 3251 3252 // Check if this is the profile owner (includes device owner). 3253 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3254 3255 long id = Binder.clearCallingIdentity(); 3256 try { 3257 mUserManager.setUserName(userId, profileName); 3258 } finally { 3259 restoreCallingIdentity(id); 3260 } 3261 } 3262 3263 @Override 3264 public String getProfileOwner(int userHandle) { 3265 if (!mHasFeature) { 3266 return null; 3267 } 3268 3269 synchronized (this) { 3270 if (mDeviceOwner != null) { 3271 return mDeviceOwner.getProfileOwnerPackageName(userHandle); 3272 } 3273 } 3274 return null; 3275 } 3276 3277 @Override 3278 public String getProfileOwnerName(int userHandle) { 3279 if (!mHasFeature) { 3280 return null; 3281 } 3282 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 3283 3284 synchronized (this) { 3285 if (mDeviceOwner != null) { 3286 return mDeviceOwner.getProfileOwnerName(userHandle); 3287 } 3288 } 3289 return null; 3290 } 3291 3292 private boolean isDeviceProvisioned() { 3293 return Settings.Global.getInt(mContext.getContentResolver(), 3294 Settings.Global.DEVICE_PROVISIONED, 0) > 0; 3295 } 3296 3297 private boolean isUserSetupComplete(int userId) { 3298 return Settings.Secure.getIntForUser(mContext.getContentResolver(), 3299 Settings.Secure.USER_SETUP_COMPLETE, 0, userId) > 0; 3300 } 3301 3302 private void enforceCrossUserPermission(int userHandle) { 3303 if (userHandle < 0) { 3304 throw new IllegalArgumentException("Invalid userId " + userHandle); 3305 } 3306 final int callingUid = Binder.getCallingUid(); 3307 if (userHandle == UserHandle.getUserId(callingUid)) return; 3308 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3309 mContext.enforceCallingOrSelfPermission( 3310 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, "Must be system or have" 3311 + " INTERACT_ACROSS_USERS_FULL permission"); 3312 } 3313 } 3314 3315 private void enforceNotManagedProfile(int userHandle, String message) { 3316 if(isManagedProfile(userHandle)) { 3317 throw new SecurityException("You can not " + message + " for a managed profile. "); 3318 } 3319 } 3320 3321 private UserInfo getProfileParent(int userHandle) { 3322 long ident = Binder.clearCallingIdentity(); 3323 try { 3324 return mUserManager.getProfileParent(userHandle); 3325 } finally { 3326 Binder.restoreCallingIdentity(ident); 3327 } 3328 } 3329 3330 private boolean isManagedProfile(int userHandle) { 3331 long ident = Binder.clearCallingIdentity(); 3332 try { 3333 return mUserManager.getUserInfo(userHandle).isManagedProfile(); 3334 } finally { 3335 Binder.restoreCallingIdentity(ident); 3336 } 3337 } 3338 3339 private void enableIfNecessary(String packageName, int userId) { 3340 try { 3341 IPackageManager ipm = AppGlobals.getPackageManager(); 3342 ApplicationInfo ai = ipm.getApplicationInfo(packageName, 3343 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS, 3344 userId); 3345 if (ai.enabledSetting 3346 == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) { 3347 ipm.setApplicationEnabledSetting(packageName, 3348 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3349 PackageManager.DONT_KILL_APP, userId, "DevicePolicyManager"); 3350 } 3351 } catch (RemoteException e) { 3352 } 3353 } 3354 3355 @Override 3356 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3357 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 3358 != PackageManager.PERMISSION_GRANTED) { 3359 3360 pw.println("Permission Denial: can't dump DevicePolicyManagerService from from pid=" 3361 + Binder.getCallingPid() 3362 + ", uid=" + Binder.getCallingUid()); 3363 return; 3364 } 3365 3366 final Printer p = new PrintWriterPrinter(pw); 3367 3368 synchronized (this) { 3369 p.println("Current Device Policy Manager state:"); 3370 3371 int userCount = mUserData.size(); 3372 for (int u = 0; u < userCount; u++) { 3373 DevicePolicyData policy = getUserData(mUserData.keyAt(u)); 3374 p.println(" Enabled Device Admins (User " + policy.mUserHandle + "):"); 3375 final int N = policy.mAdminList.size(); 3376 for (int i=0; i<N; i++) { 3377 ActiveAdmin ap = policy.mAdminList.get(i); 3378 if (ap != null) { 3379 pw.print(" "); pw.print(ap.info.getComponent().flattenToShortString()); 3380 pw.println(":"); 3381 ap.dump(" ", pw); 3382 } 3383 } 3384 3385 pw.println(" "); 3386 pw.print(" mPasswordOwner="); pw.println(policy.mPasswordOwner); 3387 } 3388 } 3389 } 3390 3391 @Override 3392 public void addPersistentPreferredActivity(ComponentName who, IntentFilter filter, 3393 ComponentName activity) { 3394 synchronized (this) { 3395 if (who == null) { 3396 throw new NullPointerException("ComponentName is null"); 3397 } 3398 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3399 3400 IPackageManager pm = AppGlobals.getPackageManager(); 3401 long id = Binder.clearCallingIdentity(); 3402 try { 3403 pm.addPersistentPreferredActivity(filter, activity, UserHandle.getCallingUserId()); 3404 } catch (RemoteException re) { 3405 // Shouldn't happen 3406 } finally { 3407 restoreCallingIdentity(id); 3408 } 3409 } 3410 } 3411 3412 @Override 3413 public void clearPackagePersistentPreferredActivities(ComponentName who, String packageName) { 3414 synchronized (this) { 3415 if (who == null) { 3416 throw new NullPointerException("ComponentName is null"); 3417 } 3418 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3419 3420 IPackageManager pm = AppGlobals.getPackageManager(); 3421 long id = Binder.clearCallingIdentity(); 3422 try { 3423 pm.clearPackagePersistentPreferredActivities(packageName, UserHandle.getCallingUserId()); 3424 } catch (RemoteException re) { 3425 // Shouldn't happen 3426 } finally { 3427 restoreCallingIdentity(id); 3428 } 3429 } 3430 } 3431 3432 @Override 3433 public void setApplicationRestrictions(ComponentName who, String packageName, Bundle settings) { 3434 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3435 3436 synchronized (this) { 3437 if (who == null) { 3438 throw new NullPointerException("ComponentName is null"); 3439 } 3440 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3441 3442 long id = Binder.clearCallingIdentity(); 3443 try { 3444 mUserManager.setApplicationRestrictions(packageName, settings, userHandle); 3445 } finally { 3446 restoreCallingIdentity(id); 3447 } 3448 } 3449 } 3450 3451 @Override 3452 public void setRestrictionsProvider(ComponentName who, ComponentName permissionProvider) { 3453 synchronized (this) { 3454 if (who == null) { 3455 throw new NullPointerException("ComponentName is null"); 3456 } 3457 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3458 3459 int userHandle = UserHandle.getCallingUserId(); 3460 DevicePolicyData userData = getUserData(userHandle); 3461 userData.mRestrictionsProvider = permissionProvider; 3462 saveSettingsLocked(userHandle); 3463 } 3464 } 3465 3466 @Override 3467 public ComponentName getRestrictionsProvider(int userHandle) { 3468 synchronized (this) { 3469 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3470 throw new SecurityException("Only the system can query the permission provider"); 3471 } 3472 DevicePolicyData userData = getUserData(userHandle); 3473 return userData != null ? userData.mRestrictionsProvider : null; 3474 } 3475 } 3476 3477 public void addCrossProfileIntentFilter(ComponentName who, IntentFilter filter, int flags) { 3478 int callingUserId = UserHandle.getCallingUserId(); 3479 synchronized (this) { 3480 if (who == null) { 3481 throw new NullPointerException("ComponentName is null"); 3482 } 3483 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3484 3485 IPackageManager pm = AppGlobals.getPackageManager(); 3486 long id = Binder.clearCallingIdentity(); 3487 try { 3488 if ((flags & DevicePolicyManager.FLAG_PARENT_CAN_ACCESS_MANAGED) != 0) { 3489 pm.addCrossProfileIntentFilter(filter, callingUserId, UserHandle.USER_OWNER, 3490 PackageManager.SET_BY_PROFILE_OWNER); 3491 } 3492 if ((flags & DevicePolicyManager.FLAG_MANAGED_CAN_ACCESS_PARENT) != 0) { 3493 pm.addCrossProfileIntentFilter(filter, UserHandle.USER_OWNER, callingUserId, 3494 PackageManager.SET_BY_PROFILE_OWNER); 3495 } 3496 } catch (RemoteException re) { 3497 // Shouldn't happen 3498 } finally { 3499 restoreCallingIdentity(id); 3500 } 3501 } 3502 } 3503 3504 public void clearCrossProfileIntentFilters(ComponentName who) { 3505 int callingUserId = UserHandle.getCallingUserId(); 3506 synchronized (this) { 3507 if (who == null) { 3508 throw new NullPointerException("ComponentName is null"); 3509 } 3510 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3511 IPackageManager pm = AppGlobals.getPackageManager(); 3512 long id = Binder.clearCallingIdentity(); 3513 try { 3514 pm.clearCrossProfileIntentFilters(callingUserId); 3515 // If we want to support multiple managed profiles, we will have to only remove 3516 // those that have callingUserId as their target. 3517 pm.clearCrossProfileIntentFilters(UserHandle.USER_OWNER); 3518 } catch (RemoteException re) { 3519 // Shouldn't happen 3520 } finally { 3521 restoreCallingIdentity(id); 3522 } 3523 } 3524 } 3525 3526 @Override 3527 public UserHandle createUser(ComponentName who, String name) { 3528 synchronized (this) { 3529 if (who == null) { 3530 throw new NullPointerException("ComponentName is null"); 3531 } 3532 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 3533 3534 long id = Binder.clearCallingIdentity(); 3535 try { 3536 UserInfo userInfo = mUserManager.createUser(name, 0 /* flags */); 3537 if (userInfo != null) { 3538 return userInfo.getUserHandle(); 3539 } 3540 return null; 3541 } finally { 3542 restoreCallingIdentity(id); 3543 } 3544 } 3545 } 3546 3547 @Override 3548 public UserHandle createAndInitializeUser(ComponentName who, String name, 3549 String ownerName, ComponentName profileOwnerComponent, Bundle adminExtras) { 3550 UserHandle user = createUser(who, name); 3551 long id = Binder.clearCallingIdentity(); 3552 try { 3553 String profileOwnerPkg = profileOwnerComponent.getPackageName(); 3554 final IPackageManager ipm = AppGlobals.getPackageManager(); 3555 IActivityManager activityManager = ActivityManagerNative.getDefault(); 3556 3557 try { 3558 // Install the profile owner if not present. 3559 if (!ipm.isPackageAvailable(profileOwnerPkg, user.getIdentifier())) { 3560 ipm.installExistingPackageAsUser(profileOwnerPkg, user.getIdentifier()); 3561 } 3562 3563 // Start user in background. 3564 activityManager.startUserInBackground(user.getIdentifier()); 3565 } catch (RemoteException e) { 3566 Slog.e(LOG_TAG, "Failed to make remote calls for configureUser", e); 3567 } 3568 3569 setActiveAdmin(profileOwnerComponent, true, user.getIdentifier(), adminExtras); 3570 setProfileOwner(profileOwnerPkg, ownerName, user.getIdentifier()); 3571 return user; 3572 } finally { 3573 restoreCallingIdentity(id); 3574 } 3575 } 3576 3577 @Override 3578 public boolean removeUser(ComponentName who, UserHandle userHandle) { 3579 synchronized (this) { 3580 if (who == null) { 3581 throw new NullPointerException("ComponentName is null"); 3582 } 3583 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 3584 3585 long id = Binder.clearCallingIdentity(); 3586 try { 3587 return mUserManager.removeUser(userHandle.getIdentifier()); 3588 } finally { 3589 restoreCallingIdentity(id); 3590 } 3591 } 3592 } 3593 3594 @Override 3595 public Bundle getApplicationRestrictions(ComponentName who, String packageName) { 3596 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3597 3598 synchronized (this) { 3599 if (who == null) { 3600 throw new NullPointerException("ComponentName is null"); 3601 } 3602 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3603 3604 long id = Binder.clearCallingIdentity(); 3605 try { 3606 return mUserManager.getApplicationRestrictions(packageName, userHandle); 3607 } finally { 3608 restoreCallingIdentity(id); 3609 } 3610 } 3611 } 3612 3613 @Override 3614 public void setUserRestriction(ComponentName who, String key, boolean enabled) { 3615 final UserHandle userHandle = new UserHandle(UserHandle.getCallingUserId()); 3616 3617 synchronized (this) { 3618 if (who == null) { 3619 throw new NullPointerException("ComponentName is null"); 3620 } 3621 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3622 3623 long id = Binder.clearCallingIdentity(); 3624 try { 3625 mUserManager.setUserRestriction(key, enabled, userHandle); 3626 } finally { 3627 restoreCallingIdentity(id); 3628 } 3629 } 3630 } 3631 3632 @Override 3633 public boolean setApplicationBlocked(ComponentName who, String packageName, 3634 boolean blocked) { 3635 int callingUserId = UserHandle.getCallingUserId(); 3636 synchronized (this) { 3637 if (who == null) { 3638 throw new NullPointerException("ComponentName is null"); 3639 } 3640 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3641 3642 long id = Binder.clearCallingIdentity(); 3643 try { 3644 IPackageManager pm = AppGlobals.getPackageManager(); 3645 return pm.setApplicationBlockedSettingAsUser(packageName, blocked, callingUserId); 3646 } catch (RemoteException re) { 3647 // shouldn't happen 3648 Slog.e(LOG_TAG, "Failed to setApplicationBlockedSetting", re); 3649 } finally { 3650 restoreCallingIdentity(id); 3651 } 3652 return false; 3653 } 3654 } 3655 3656 @Override 3657 public int setApplicationsBlocked(ComponentName who, Intent intent, boolean blocked) { 3658 int callingUserId = UserHandle.getCallingUserId(); 3659 synchronized (this) { 3660 if (who == null) { 3661 throw new NullPointerException("ComponentName is null"); 3662 } 3663 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3664 3665 long id = Binder.clearCallingIdentity(); 3666 try { 3667 IPackageManager pm = AppGlobals.getPackageManager(); 3668 List<ResolveInfo> activitiesToEnable = pm.queryIntentActivities(intent, 3669 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 3670 PackageManager.GET_DISABLED_COMPONENTS 3671 | PackageManager.GET_UNINSTALLED_PACKAGES, 3672 callingUserId); 3673 3674 if (DBG) Slog.d(LOG_TAG, "Enabling activities: " + activitiesToEnable); 3675 int numberOfAppsUnblocked = 0; 3676 if (activitiesToEnable != null) { 3677 for (ResolveInfo info : activitiesToEnable) { 3678 if (info.activityInfo != null) { 3679 numberOfAppsUnblocked++; 3680 pm.setApplicationBlockedSettingAsUser(info.activityInfo.packageName, 3681 blocked, callingUserId); 3682 } 3683 } 3684 } 3685 return numberOfAppsUnblocked; 3686 } catch (RemoteException re) { 3687 // shouldn't happen 3688 Slog.e(LOG_TAG, "Failed to setApplicationsBlockedSettingsWithIntent", re); 3689 } finally { 3690 restoreCallingIdentity(id); 3691 } 3692 return 0; 3693 } 3694 } 3695 3696 @Override 3697 public boolean isApplicationBlocked(ComponentName who, String packageName) { 3698 int callingUserId = UserHandle.getCallingUserId(); 3699 synchronized (this) { 3700 if (who == null) { 3701 throw new NullPointerException("ComponentName is null"); 3702 } 3703 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3704 3705 long id = Binder.clearCallingIdentity(); 3706 try { 3707 IPackageManager pm = AppGlobals.getPackageManager(); 3708 return pm.getApplicationBlockedSettingAsUser(packageName, callingUserId); 3709 } catch (RemoteException re) { 3710 // shouldn't happen 3711 Slog.e(LOG_TAG, "Failed to getApplicationBlockedSettingAsUser", re); 3712 } finally { 3713 restoreCallingIdentity(id); 3714 } 3715 return false; 3716 } 3717 } 3718 3719 @Override 3720 public void setAccountManagementDisabled(ComponentName who, String accountType, 3721 boolean disabled) { 3722 if (!mHasFeature) { 3723 return; 3724 } 3725 synchronized (this) { 3726 if (who == null) { 3727 throw new NullPointerException("ComponentName is null"); 3728 } 3729 ActiveAdmin ap = getActiveAdminForCallerLocked(who, 3730 DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3731 if (disabled) { 3732 ap.accountTypesWithManagementDisabled.add(accountType); 3733 } else { 3734 ap.accountTypesWithManagementDisabled.remove(accountType); 3735 } 3736 saveSettingsLocked(UserHandle.getCallingUserId()); 3737 } 3738 } 3739 3740 @Override 3741 public String[] getAccountTypesWithManagementDisabled() { 3742 if (!mHasFeature) { 3743 return null; 3744 } 3745 synchronized (this) { 3746 DevicePolicyData policy = getUserData(UserHandle.getCallingUserId()); 3747 final int N = policy.mAdminList.size(); 3748 HashSet<String> resultSet = new HashSet<String>(); 3749 for (int i = 0; i < N; i++) { 3750 ActiveAdmin admin = policy.mAdminList.get(i); 3751 resultSet.addAll(admin.accountTypesWithManagementDisabled); 3752 } 3753 return resultSet.toArray(new String[resultSet.size()]); 3754 } 3755 } 3756 3757 @Override 3758 public void setBlockUninstall(ComponentName who, String packageName, boolean blockUninstall) { 3759 final int userId = UserHandle.getCallingUserId(); 3760 3761 synchronized (this) { 3762 if (who == null) { 3763 throw new NullPointerException("ComponentName is null"); 3764 } 3765 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3766 3767 long id = Binder.clearCallingIdentity(); 3768 try { 3769 IPackageManager pm = AppGlobals.getPackageManager(); 3770 pm.setBlockUninstallForUser(packageName, blockUninstall, userId); 3771 } catch (RemoteException re) { 3772 // Shouldn't happen. 3773 Slog.e(LOG_TAG, "Failed to setBlockUninstallForUser", re); 3774 } finally { 3775 restoreCallingIdentity(id); 3776 } 3777 } 3778 } 3779 3780 @Override 3781 public boolean getBlockUninstall(ComponentName who, String packageName) { 3782 final int userId = UserHandle.getCallingUserId(); 3783 3784 synchronized (this) { 3785 if (who == null) { 3786 throw new NullPointerException("ComponentName is null"); 3787 } 3788 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3789 3790 long id = Binder.clearCallingIdentity(); 3791 try { 3792 IPackageManager pm = AppGlobals.getPackageManager(); 3793 return pm.getBlockUninstallForUser(packageName, userId); 3794 } catch (RemoteException re) { 3795 // Shouldn't happen. 3796 Slog.e(LOG_TAG, "Failed to getBlockUninstallForUser", re); 3797 } finally { 3798 restoreCallingIdentity(id); 3799 } 3800 } 3801 return false; 3802 } 3803 3804 /** 3805 * Sets which packages may enter lock task mode. 3806 * 3807 * This function can only be called by the device owner. 3808 * @param components The list of components allowed to enter lock task mode. 3809 */ 3810 public void setLockTaskPackages(String[] packages) throws SecurityException { 3811 // Get the package names of the caller. 3812 int uid = Binder.getCallingUid(); 3813 String[] packageNames = mContext.getPackageManager().getPackagesForUid(uid); 3814 3815 synchronized (this) { 3816 // Check whether any of the package name is the device owner. 3817 for (int i=0; i<packageNames.length; i++) { 3818 String packageName = packageNames[i]; 3819 int userHandle = UserHandle.getUserId(uid); 3820 if (isDeviceOwner(packageName)) { 3821 3822 // If a package name is the device owner, 3823 // we update the component list. 3824 DevicePolicyData policy = getUserData(userHandle); 3825 policy.mLockTaskPackages.clear(); 3826 if (packages != null) { 3827 for (int j = 0; j < packages.length; j++) { 3828 String pkg = packages[j]; 3829 policy.mLockTaskPackages.add(pkg); 3830 } 3831 } 3832 3833 // Store the settings persistently. 3834 saveSettingsLocked(userHandle); 3835 return; 3836 } 3837 } 3838 } 3839 throw new SecurityException(); 3840 } 3841 3842 /** 3843 * This function returns the list of components allowed to start the task lock mode. 3844 */ 3845 public String[] getLockTaskPackages() { 3846 synchronized (this) { 3847 int userHandle = UserHandle.USER_OWNER; 3848 DevicePolicyData policy = getUserData(userHandle); 3849 return policy.mLockTaskPackages.toArray(new String[0]); 3850 } 3851 } 3852 3853 /** 3854 * This function lets the caller know whether the given package is allowed to start the 3855 * lock task mode. 3856 * @param pkg The package to check 3857 */ 3858 public boolean isLockTaskPermitted(String pkg) { 3859 // Get current user's devicepolicy 3860 int uid = Binder.getCallingUid(); 3861 int userHandle = UserHandle.getUserId(uid); 3862 DevicePolicyData policy = getUserData(userHandle); 3863 synchronized (this) { 3864 for (int i = 0; i < policy.mLockTaskPackages.size(); i++) { 3865 String lockTaskPackage = policy.mLockTaskPackages.get(i); 3866 3867 // If the given package equals one of the packages stored our list, 3868 // we allow this package to start lock task mode. 3869 if (lockTaskPackage.equals(pkg)) { 3870 return true; 3871 } 3872 } 3873 } 3874 return false; 3875 } 3876 3877 @Override 3878 public void notifyLockTaskModeChanged(boolean isEnabled, String pkg, int userHandle) { 3879 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 3880 throw new SecurityException("notifyLockTaskModeChanged can only be called by system"); 3881 } 3882 synchronized (this) { 3883 final DevicePolicyData policy = getUserData(userHandle); 3884 Bundle adminExtras = new Bundle(); 3885 adminExtras.putBoolean(DeviceAdminReceiver.EXTRA_LOCK_TASK_ENTERING, isEnabled); 3886 adminExtras.putString(DeviceAdminReceiver.EXTRA_LOCK_TASK_PACKAGE, pkg); 3887 for (ActiveAdmin admin : policy.mAdminList) { 3888 boolean ownsDevice = isDeviceOwner(admin.info.getPackageName()); 3889 boolean ownsProfile = (getProfileOwner(userHandle) != null 3890 && getProfileOwner(userHandle).equals(admin.info.getPackageName())); 3891 if (ownsDevice || ownsProfile) { 3892 sendAdminCommandLocked(admin, DeviceAdminReceiver.ACTION_LOCK_TASK_CHANGED, 3893 adminExtras, null); 3894 } 3895 } 3896 } 3897 } 3898 3899 @Override 3900 public void setGlobalSetting(ComponentName who, String setting, String value) { 3901 final ContentResolver contentResolver = mContext.getContentResolver(); 3902 3903 synchronized (this) { 3904 if (who == null) { 3905 throw new NullPointerException("ComponentName is null"); 3906 } 3907 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER); 3908 3909 long id = Binder.clearCallingIdentity(); 3910 try { 3911 Settings.Global.putString(contentResolver, setting, value); 3912 } finally { 3913 restoreCallingIdentity(id); 3914 } 3915 } 3916 } 3917 3918 @Override 3919 public void setSecureSetting(ComponentName who, String setting, String value) { 3920 int callingUserId = UserHandle.getCallingUserId(); 3921 final ContentResolver contentResolver = mContext.getContentResolver(); 3922 3923 synchronized (this) { 3924 if (who == null) { 3925 throw new NullPointerException("ComponentName is null"); 3926 } 3927 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3928 3929 long id = Binder.clearCallingIdentity(); 3930 try { 3931 Settings.Secure.putStringForUser(contentResolver, setting, value, callingUserId); 3932 } finally { 3933 restoreCallingIdentity(id); 3934 } 3935 } 3936 } 3937 3938 @Override 3939 public void setMasterVolumeMuted(ComponentName who, boolean on) { 3940 final ContentResolver contentResolver = mContext.getContentResolver(); 3941 3942 synchronized (this) { 3943 if (who == null) { 3944 throw new NullPointerException("ComponentName is null"); 3945 } 3946 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3947 3948 IAudioService iAudioService = IAudioService.Stub.asInterface( 3949 ServiceManager.getService(Context.AUDIO_SERVICE)); 3950 try{ 3951 iAudioService.setMasterMute(on, 0, who.getPackageName(), null); 3952 } catch (RemoteException re) { 3953 Slog.e(LOG_TAG, "Failed to setMasterMute", re); 3954 } 3955 } 3956 } 3957 3958 @Override 3959 public boolean isMasterVolumeMuted(ComponentName who) { 3960 final ContentResolver contentResolver = mContext.getContentResolver(); 3961 3962 synchronized (this) { 3963 if (who == null) { 3964 throw new NullPointerException("ComponentName is null"); 3965 } 3966 getActiveAdminForCallerLocked(who, DeviceAdminInfo.USES_POLICY_PROFILE_OWNER); 3967 3968 AudioManager audioManager = 3969 (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 3970 return audioManager.isMasterMute(); 3971 } 3972 } 3973} 3974