TrustManagerService.java revision 4b9e324b6f59f49a8ca4bc4cd8b38a5ea005a6b2
1/* 2 * Copyright (C) 2014 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.trust; 18 19import com.android.internal.content.PackageMonitor; 20import com.android.internal.widget.LockPatternUtils; 21import com.android.server.SystemService; 22 23import org.xmlpull.v1.XmlPullParser; 24import org.xmlpull.v1.XmlPullParserException; 25 26import android.Manifest; 27import android.app.ActivityManagerNative; 28import android.app.admin.DevicePolicyManager; 29import android.app.trust.ITrustListener; 30import android.app.trust.ITrustManager; 31import android.content.BroadcastReceiver; 32import android.content.ComponentName; 33import android.content.Context; 34import android.content.Intent; 35import android.content.IntentFilter; 36import android.content.pm.PackageManager; 37import android.content.pm.ResolveInfo; 38import android.content.pm.UserInfo; 39import android.content.res.Resources; 40import android.content.res.TypedArray; 41import android.content.res.XmlResourceParser; 42import android.graphics.drawable.Drawable; 43import android.os.DeadObjectException; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Message; 47import android.os.RemoteException; 48import android.os.SystemClock; 49import android.os.UserHandle; 50import android.os.UserManager; 51import android.service.trust.TrustAgentService; 52import android.util.ArraySet; 53import android.util.AttributeSet; 54import android.util.Log; 55import android.util.Slog; 56import android.util.SparseBooleanArray; 57import android.util.Xml; 58 59import java.io.FileDescriptor; 60import java.io.IOException; 61import java.io.PrintWriter; 62import java.util.ArrayList; 63import java.util.List; 64 65/** 66 * Manages trust agents and trust listeners. 67 * 68 * It is responsible for binding to the enabled {@link android.service.trust.TrustAgentService}s 69 * of each user and notifies them about events that are relevant to them. 70 * It start and stops them based on the value of 71 * {@link com.android.internal.widget.LockPatternUtils#getEnabledTrustAgents(int)}. 72 * 73 * It also keeps a set of {@link android.app.trust.ITrustListener}s that are notified whenever the 74 * trust state changes for any user. 75 * 76 * Trust state and the setting of enabled agents is kept per user and each user has its own 77 * instance of a {@link android.service.trust.TrustAgentService}. 78 */ 79public class TrustManagerService extends SystemService { 80 81 private static final boolean DEBUG = false; 82 private static final String TAG = "TrustManagerService"; 83 84 private static final Intent TRUST_AGENT_INTENT = 85 new Intent(TrustAgentService.SERVICE_INTERFACE); 86 private static final String PERMISSION_PROVIDE_AGENT = Manifest.permission.PROVIDE_TRUST_AGENT; 87 88 private static final int MSG_REGISTER_LISTENER = 1; 89 private static final int MSG_UNREGISTER_LISTENER = 2; 90 private static final int MSG_DISPATCH_UNLOCK_ATTEMPT = 3; 91 private static final int MSG_ENABLED_AGENTS_CHANGED = 4; 92 private static final int MSG_REQUIRE_CREDENTIAL_ENTRY = 5; 93 94 private final ArraySet<AgentInfo> mActiveAgents = new ArraySet<AgentInfo>(); 95 private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<ITrustListener>(); 96 private final Receiver mReceiver = new Receiver(); 97 private final SparseBooleanArray mUserHasAuthenticatedSinceBoot = new SparseBooleanArray(); 98 /* package */ final TrustArchive mArchive = new TrustArchive(); 99 private final Context mContext; 100 101 private UserManager mUserManager; 102 103 public TrustManagerService(Context context) { 104 super(context); 105 mContext = context; 106 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 107 } 108 109 @Override 110 public void onStart() { 111 publishBinderService(Context.TRUST_SERVICE, mService); 112 } 113 114 @Override 115 public void onBootPhase(int phase) { 116 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY && !isSafeMode()) { 117 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true); 118 mReceiver.register(mContext); 119 refreshAgentList(); 120 } 121 } 122 123 // Agent management 124 125 private static final class AgentInfo { 126 CharSequence label; 127 Drawable icon; 128 ComponentName component; // service that implements ITrustAgent 129 ComponentName settings; // setting to launch to modify agent. 130 TrustAgentWrapper agent; 131 int userId; 132 133 @Override 134 public boolean equals(Object other) { 135 if (!(other instanceof AgentInfo)) { 136 return false; 137 } 138 AgentInfo o = (AgentInfo) other; 139 return component.equals(o.component) && userId == o.userId; 140 } 141 142 @Override 143 public int hashCode() { 144 return component.hashCode() * 31 + userId; 145 } 146 } 147 148 private void updateTrustAll() { 149 List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */); 150 for (UserInfo userInfo : userInfos) { 151 updateTrust(userInfo.id, false); 152 } 153 } 154 155 public void updateTrust(int userId, boolean initiatedByUser) { 156 dispatchOnTrustManagedChanged(aggregateIsTrustManaged(userId), userId); 157 dispatchOnTrustChanged(aggregateIsTrusted(userId), userId, initiatedByUser); 158 } 159 160 void refreshAgentList() { 161 if (DEBUG) Slog.d(TAG, "refreshAgentList()"); 162 PackageManager pm = mContext.getPackageManager(); 163 164 List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */); 165 LockPatternUtils lockPatternUtils = new LockPatternUtils(mContext); 166 167 ArraySet<AgentInfo> obsoleteAgents = new ArraySet<>(); 168 obsoleteAgents.addAll(mActiveAgents); 169 170 for (UserInfo userInfo : userInfos) { 171 if (lockPatternUtils.getKeyguardStoredPasswordQuality() 172 == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) continue; 173 DevicePolicyManager dpm = lockPatternUtils.getDevicePolicyManager(); 174 int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, userInfo.id); 175 final boolean disableTrustAgents = 176 (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 177 178 List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id); 179 if (enabledAgents == null) { 180 continue; 181 } 182 List<ResolveInfo> resolveInfos = pm.queryIntentServicesAsUser(TRUST_AGENT_INTENT, 183 PackageManager.GET_META_DATA, userInfo.id); 184 for (ResolveInfo resolveInfo : resolveInfos) { 185 if (resolveInfo.serviceInfo == null) continue; 186 187 String packageName = resolveInfo.serviceInfo.packageName; 188 if (pm.checkPermission(PERMISSION_PROVIDE_AGENT, packageName) 189 != PackageManager.PERMISSION_GRANTED) { 190 Log.w(TAG, "Skipping agent because package " + packageName 191 + " does not have permission " + PERMISSION_PROVIDE_AGENT + "."); 192 continue; 193 } 194 195 ComponentName name = getComponentName(resolveInfo); 196 if (!enabledAgents.contains(name)) continue; 197 198 if (disableTrustAgents) { 199 List<String> features = 200 dpm.getTrustAgentFeaturesEnabled(null /* admin */, name); 201 // Disable agent if no features are enabled. 202 if (features == null || features.isEmpty()) continue; 203 } 204 205 AgentInfo agentInfo = new AgentInfo(); 206 agentInfo.component = name; 207 agentInfo.userId = userInfo.id; 208 if (!mActiveAgents.contains(agentInfo)) { 209 agentInfo.label = resolveInfo.loadLabel(pm); 210 agentInfo.icon = resolveInfo.loadIcon(pm); 211 agentInfo.settings = getSettingsComponentName(pm, resolveInfo); 212 agentInfo.agent = new TrustAgentWrapper(mContext, this, 213 new Intent().setComponent(name), userInfo.getUserHandle()); 214 mActiveAgents.add(agentInfo); 215 } else { 216 obsoleteAgents.remove(agentInfo); 217 } 218 } 219 } 220 221 boolean trustMayHaveChanged = false; 222 for (int i = 0; i < obsoleteAgents.size(); i++) { 223 AgentInfo info = obsoleteAgents.valueAt(i); 224 if (info.agent.isManagingTrust()) { 225 trustMayHaveChanged = true; 226 } 227 info.agent.unbind(); 228 mActiveAgents.remove(info); 229 } 230 231 if (trustMayHaveChanged) { 232 updateTrustAll(); 233 } 234 } 235 236 void updateDevicePolicyFeatures(int userId) { 237 for (int i = 0; i < mActiveAgents.size(); i++) { 238 AgentInfo info = mActiveAgents.valueAt(i); 239 if (info.agent.isConnected()) { 240 info.agent.updateDevicePolicyFeatures(); 241 } 242 } 243 } 244 245 private void removeAgentsOfPackage(String packageName) { 246 boolean trustMayHaveChanged = false; 247 for (int i = mActiveAgents.size() - 1; i >= 0; i--) { 248 AgentInfo info = mActiveAgents.valueAt(i); 249 if (packageName.equals(info.component.getPackageName())) { 250 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString()); 251 if (info.agent.isManagingTrust()) { 252 trustMayHaveChanged = true; 253 } 254 info.agent.unbind(); 255 mActiveAgents.removeAt(i); 256 } 257 } 258 if (trustMayHaveChanged) { 259 updateTrustAll(); 260 } 261 } 262 263 public void resetAgent(ComponentName name, int userId) { 264 boolean trustMayHaveChanged = false; 265 for (int i = mActiveAgents.size() - 1; i >= 0; i--) { 266 AgentInfo info = mActiveAgents.valueAt(i); 267 if (name.equals(info.component) && userId == info.userId) { 268 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString()); 269 if (info.agent.isManagingTrust()) { 270 trustMayHaveChanged = true; 271 } 272 info.agent.unbind(); 273 mActiveAgents.removeAt(i); 274 } 275 } 276 if (trustMayHaveChanged) { 277 updateTrust(userId, false); 278 } 279 refreshAgentList(); 280 } 281 282 private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) { 283 if (resolveInfo == null || resolveInfo.serviceInfo == null 284 || resolveInfo.serviceInfo.metaData == null) return null; 285 String cn = null; 286 XmlResourceParser parser = null; 287 Exception caughtException = null; 288 try { 289 parser = resolveInfo.serviceInfo.loadXmlMetaData(pm, 290 TrustAgentService.TRUST_AGENT_META_DATA); 291 if (parser == null) { 292 Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data"); 293 return null; 294 } 295 Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo); 296 AttributeSet attrs = Xml.asAttributeSet(parser); 297 int type; 298 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 299 && type != XmlPullParser.START_TAG) { 300 // Drain preamble. 301 } 302 String nodeName = parser.getName(); 303 if (!"trust-agent".equals(nodeName)) { 304 Slog.w(TAG, "Meta-data does not start with trust-agent tag"); 305 return null; 306 } 307 TypedArray sa = res 308 .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent); 309 cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity); 310 sa.recycle(); 311 } catch (PackageManager.NameNotFoundException e) { 312 caughtException = e; 313 } catch (IOException e) { 314 caughtException = e; 315 } catch (XmlPullParserException e) { 316 caughtException = e; 317 } finally { 318 if (parser != null) parser.close(); 319 } 320 if (caughtException != null) { 321 Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException); 322 return null; 323 } 324 if (cn == null) { 325 return null; 326 } 327 if (cn.indexOf('/') < 0) { 328 cn = resolveInfo.serviceInfo.packageName + "/" + cn; 329 } 330 return ComponentName.unflattenFromString(cn); 331 } 332 333 private ComponentName getComponentName(ResolveInfo resolveInfo) { 334 if (resolveInfo == null || resolveInfo.serviceInfo == null) return null; 335 return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name); 336 } 337 338 // Agent dispatch and aggregation 339 340 private boolean aggregateIsTrusted(int userId) { 341 if (!mUserHasAuthenticatedSinceBoot.get(userId)) { 342 return false; 343 } 344 for (int i = 0; i < mActiveAgents.size(); i++) { 345 AgentInfo info = mActiveAgents.valueAt(i); 346 if (info.userId == userId) { 347 if (info.agent.isTrusted()) { 348 return true; 349 } 350 } 351 } 352 return false; 353 } 354 355 private boolean aggregateIsTrustManaged(int userId) { 356 if (!mUserHasAuthenticatedSinceBoot.get(userId)) { 357 return false; 358 } 359 for (int i = 0; i < mActiveAgents.size(); i++) { 360 AgentInfo info = mActiveAgents.valueAt(i); 361 if (info.userId == userId) { 362 if (info.agent.isManagingTrust()) { 363 return true; 364 } 365 } 366 } 367 return false; 368 } 369 370 private void dispatchUnlockAttempt(boolean successful, int userId) { 371 for (int i = 0; i < mActiveAgents.size(); i++) { 372 AgentInfo info = mActiveAgents.valueAt(i); 373 if (info.userId == userId) { 374 info.agent.onUnlockAttempt(successful); 375 } 376 } 377 378 if (successful) { 379 updateUserHasAuthenticated(userId); 380 } 381 } 382 383 private void updateUserHasAuthenticated(int userId) { 384 if (!mUserHasAuthenticatedSinceBoot.get(userId)) { 385 mUserHasAuthenticatedSinceBoot.put(userId, true); 386 updateTrust(userId, false); 387 } 388 } 389 390 391 private void requireCredentialEntry(int userId) { 392 if (userId == UserHandle.USER_ALL) { 393 mUserHasAuthenticatedSinceBoot.clear(); 394 updateTrustAll(); 395 } else { 396 mUserHasAuthenticatedSinceBoot.put(userId, false); 397 updateTrust(userId, false); 398 } 399 } 400 401 // Listeners 402 403 private void addListener(ITrustListener listener) { 404 for (int i = 0; i < mTrustListeners.size(); i++) { 405 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) { 406 return; 407 } 408 } 409 mTrustListeners.add(listener); 410 } 411 412 private void removeListener(ITrustListener listener) { 413 for (int i = 0; i < mTrustListeners.size(); i++) { 414 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) { 415 mTrustListeners.remove(i); 416 return; 417 } 418 } 419 } 420 421 private void dispatchOnTrustChanged(boolean enabled, int userId, boolean initiatedByUser) { 422 if (!enabled) initiatedByUser = false; 423 for (int i = 0; i < mTrustListeners.size(); i++) { 424 try { 425 mTrustListeners.get(i).onTrustChanged(enabled, userId, initiatedByUser); 426 } catch (DeadObjectException e) { 427 Slog.d(TAG, "Removing dead TrustListener."); 428 mTrustListeners.remove(i); 429 i--; 430 } catch (RemoteException e) { 431 Slog.e(TAG, "Exception while notifying TrustListener.", e); 432 } 433 } 434 } 435 436 private void dispatchOnTrustManagedChanged(boolean managed, int userId) { 437 for (int i = 0; i < mTrustListeners.size(); i++) { 438 try { 439 mTrustListeners.get(i).onTrustManagedChanged(managed, userId); 440 } catch (DeadObjectException e) { 441 Slog.d(TAG, "Removing dead TrustListener."); 442 mTrustListeners.remove(i); 443 i--; 444 } catch (RemoteException e) { 445 Slog.e(TAG, "Exception while notifying TrustListener.", e); 446 } 447 } 448 } 449 450 // Plumbing 451 452 private final IBinder mService = new ITrustManager.Stub() { 453 @Override 454 public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException { 455 enforceReportPermission(); 456 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId) 457 .sendToTarget(); 458 } 459 460 @Override 461 public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException { 462 enforceReportPermission(); 463 // coalesce refresh messages. 464 mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED); 465 mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED); 466 } 467 468 @Override 469 public void reportRequireCredentialEntry(int userId) throws RemoteException { 470 enforceReportPermission(); 471 if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_OWNER) { 472 mHandler.obtainMessage(MSG_REQUIRE_CREDENTIAL_ENTRY, userId, 0).sendToTarget(); 473 } else { 474 throw new IllegalArgumentException( 475 "userId must be an explicit user id or USER_ALL"); 476 } 477 } 478 479 @Override 480 public void registerTrustListener(ITrustListener trustListener) throws RemoteException { 481 enforceListenerPermission(); 482 mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget(); 483 } 484 485 @Override 486 public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException { 487 enforceListenerPermission(); 488 mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget(); 489 } 490 491 private void enforceReportPermission() { 492 mContext.enforceCallingOrSelfPermission( 493 Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, "reporting trust events"); 494 } 495 496 private void enforceListenerPermission() { 497 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER, 498 "register trust listener"); 499 } 500 501 @Override 502 protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) { 503 mContext.enforceCallingPermission(Manifest.permission.DUMP, 504 "dumping TrustManagerService"); 505 final UserInfo currentUser; 506 final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */); 507 try { 508 currentUser = ActivityManagerNative.getDefault().getCurrentUser(); 509 } catch (RemoteException e) { 510 throw new RuntimeException(e); 511 } 512 mHandler.runWithScissors(new Runnable() { 513 @Override 514 public void run() { 515 fout.println("Trust manager state:"); 516 for (UserInfo user : userInfos) { 517 dumpUser(fout, user, user.id == currentUser.id); 518 } 519 } 520 }, 1500); 521 } 522 523 private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) { 524 fout.printf(" User \"%s\" (id=%d, flags=%#x)", 525 user.name, user.id, user.flags); 526 if (isCurrent) { 527 fout.print(" (current)"); 528 } 529 fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id))); 530 fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id))); 531 fout.println(); 532 fout.println(" Enabled agents:"); 533 boolean duplicateSimpleNames = false; 534 ArraySet<String> simpleNames = new ArraySet<String>(); 535 for (AgentInfo info : mActiveAgents) { 536 if (info.userId != user.id) { continue; } 537 boolean trusted = info.agent.isTrusted(); 538 fout.print(" "); fout.println(info.component.flattenToShortString()); 539 fout.print(" bound=" + dumpBool(info.agent.isBound())); 540 fout.print(", connected=" + dumpBool(info.agent.isConnected())); 541 fout.print(", managingTrust=" + dumpBool(info.agent.isManagingTrust())); 542 fout.print(", trusted=" + dumpBool(trusted)); 543 fout.println(); 544 if (trusted) { 545 fout.println(" message=\"" + info.agent.getMessage() + "\""); 546 } 547 if (!info.agent.isConnected()) { 548 String restartTime = TrustArchive.formatDuration( 549 info.agent.getScheduledRestartUptimeMillis() 550 - SystemClock.uptimeMillis()); 551 fout.println(" restartScheduledAt=" + restartTime); 552 } 553 if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) { 554 duplicateSimpleNames = true; 555 } 556 } 557 fout.println(" Events:"); 558 mArchive.dump(fout, 50, user.id, " " /* linePrefix */, duplicateSimpleNames); 559 fout.println(); 560 } 561 562 private String dumpBool(boolean b) { 563 return b ? "1" : "0"; 564 } 565 }; 566 567 private final Handler mHandler = new Handler() { 568 @Override 569 public void handleMessage(Message msg) { 570 switch (msg.what) { 571 case MSG_REGISTER_LISTENER: 572 addListener((ITrustListener) msg.obj); 573 break; 574 case MSG_UNREGISTER_LISTENER: 575 removeListener((ITrustListener) msg.obj); 576 break; 577 case MSG_DISPATCH_UNLOCK_ATTEMPT: 578 dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2); 579 break; 580 case MSG_ENABLED_AGENTS_CHANGED: 581 refreshAgentList(); 582 break; 583 case MSG_REQUIRE_CREDENTIAL_ENTRY: 584 requireCredentialEntry(msg.arg1); 585 break; 586 } 587 } 588 }; 589 590 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 591 @Override 592 public void onSomePackagesChanged() { 593 refreshAgentList(); 594 } 595 596 @Override 597 public boolean onPackageChanged(String packageName, int uid, String[] components) { 598 // We're interested in all changes, even if just some components get enabled / disabled. 599 return true; 600 } 601 602 @Override 603 public void onPackageDisappeared(String packageName, int reason) { 604 removeAgentsOfPackage(packageName); 605 } 606 }; 607 608 private class Receiver extends BroadcastReceiver { 609 610 @Override 611 public void onReceive(Context context, Intent intent) { 612 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals( 613 intent.getAction())) { 614 refreshAgentList(); 615 updateDevicePolicyFeatures(getSendingUserId()); 616 } else if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())) { 617 updateUserHasAuthenticated(getSendingUserId()); 618 } 619 } 620 621 public void register(Context context) { 622 IntentFilter filter = new IntentFilter(); 623 filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED); 624 filter.addAction(Intent.ACTION_USER_PRESENT); 625 context.registerReceiverAsUser(this, 626 UserHandle.ALL, 627 filter, 628 null /* permission */, 629 null /* scheduler */); 630 } 631 } 632} 633