TrustManagerService.java revision 7861c663fd64af33ec2a4c5ad653c806dc8bd994
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 DevicePolicyReceiver mDevicePolicyReceiver = new DevicePolicyReceiver(); 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 mDevicePolicyReceiver.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); 152 } 153 } 154 155 public void updateTrust(int userId) { 156 dispatchOnTrustManagedChanged(aggregateIsTrustManaged(userId), userId); 157 dispatchOnTrustChanged(aggregateIsTrusted(userId), userId); 158 } 159 160 protected 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 int disabledFeatures = lockPatternUtils.getDevicePolicyManager() 172 .getKeyguardDisabledFeatures(null, userInfo.id); 173 final boolean disableTrustAgents = 174 (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0; 175 176 List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id); 177 if (disableTrustAgents || enabledAgents == null) { 178 continue; 179 } 180 List<ResolveInfo> resolveInfos = pm.queryIntentServicesAsUser(TRUST_AGENT_INTENT, 181 PackageManager.GET_META_DATA, userInfo.id); 182 for (ResolveInfo resolveInfo : resolveInfos) { 183 if (resolveInfo.serviceInfo == null) continue; 184 185 String packageName = resolveInfo.serviceInfo.packageName; 186 if (pm.checkPermission(PERMISSION_PROVIDE_AGENT, packageName) 187 != PackageManager.PERMISSION_GRANTED) { 188 Log.w(TAG, "Skipping agent because package " + packageName 189 + " does not have permission " + PERMISSION_PROVIDE_AGENT + "."); 190 continue; 191 } 192 193 ComponentName name = getComponentName(resolveInfo); 194 if (!enabledAgents.contains(name)) continue; 195 196 AgentInfo agentInfo = new AgentInfo(); 197 agentInfo.component = name; 198 agentInfo.userId = userInfo.id; 199 if (!mActiveAgents.contains(agentInfo)) { 200 agentInfo.label = resolveInfo.loadLabel(pm); 201 agentInfo.icon = resolveInfo.loadIcon(pm); 202 agentInfo.settings = getSettingsComponentName(pm, resolveInfo); 203 agentInfo.agent = new TrustAgentWrapper(mContext, this, 204 new Intent().setComponent(name), userInfo.getUserHandle()); 205 mActiveAgents.add(agentInfo); 206 } else { 207 obsoleteAgents.remove(agentInfo); 208 } 209 } 210 } 211 212 boolean trustMayHaveChanged = false; 213 for (int i = 0; i < obsoleteAgents.size(); i++) { 214 AgentInfo info = obsoleteAgents.valueAt(i); 215 if (info.agent.isManagingTrust()) { 216 trustMayHaveChanged = true; 217 } 218 info.agent.unbind(); 219 mActiveAgents.remove(info); 220 } 221 222 if (trustMayHaveChanged) { 223 updateTrustAll(); 224 } 225 } 226 227 private void removeAgentsOfPackage(String packageName) { 228 boolean trustMayHaveChanged = false; 229 for (int i = mActiveAgents.size() - 1; i >= 0; i--) { 230 AgentInfo info = mActiveAgents.valueAt(i); 231 if (packageName.equals(info.component.getPackageName())) { 232 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString()); 233 if (info.agent.isManagingTrust()) { 234 trustMayHaveChanged = true; 235 } 236 info.agent.unbind(); 237 mActiveAgents.removeAt(i); 238 } 239 } 240 if (trustMayHaveChanged) { 241 updateTrustAll(); 242 } 243 } 244 245 public void resetAgent(ComponentName name, int userId) { 246 boolean trustMayHaveChanged = false; 247 for (int i = mActiveAgents.size() - 1; i >= 0; i--) { 248 AgentInfo info = mActiveAgents.valueAt(i); 249 if (name.equals(info.component) && userId == info.userId) { 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 updateTrust(userId); 260 } 261 refreshAgentList(); 262 } 263 264 private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) { 265 if (resolveInfo == null || resolveInfo.serviceInfo == null 266 || resolveInfo.serviceInfo.metaData == null) return null; 267 String cn = null; 268 XmlResourceParser parser = null; 269 Exception caughtException = null; 270 try { 271 parser = resolveInfo.serviceInfo.loadXmlMetaData(pm, 272 TrustAgentService.TRUST_AGENT_META_DATA); 273 if (parser == null) { 274 Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data"); 275 return null; 276 } 277 Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo); 278 AttributeSet attrs = Xml.asAttributeSet(parser); 279 int type; 280 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 281 && type != XmlPullParser.START_TAG) { 282 // Drain preamble. 283 } 284 String nodeName = parser.getName(); 285 if (!"trust-agent".equals(nodeName)) { 286 Slog.w(TAG, "Meta-data does not start with trust-agent tag"); 287 return null; 288 } 289 TypedArray sa = res 290 .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent); 291 cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity); 292 sa.recycle(); 293 } catch (PackageManager.NameNotFoundException e) { 294 caughtException = e; 295 } catch (IOException e) { 296 caughtException = e; 297 } catch (XmlPullParserException e) { 298 caughtException = e; 299 } finally { 300 if (parser != null) parser.close(); 301 } 302 if (caughtException != null) { 303 Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException); 304 return null; 305 } 306 if (cn == null) { 307 return null; 308 } 309 if (cn.indexOf('/') < 0) { 310 cn = resolveInfo.serviceInfo.packageName + "/" + cn; 311 } 312 return ComponentName.unflattenFromString(cn); 313 } 314 315 private ComponentName getComponentName(ResolveInfo resolveInfo) { 316 if (resolveInfo == null || resolveInfo.serviceInfo == null) return null; 317 return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name); 318 } 319 320 // Agent dispatch and aggregation 321 322 private boolean aggregateIsTrusted(int userId) { 323 if (!mUserHasAuthenticatedSinceBoot.get(userId)) { 324 return false; 325 } 326 for (int i = 0; i < mActiveAgents.size(); i++) { 327 AgentInfo info = mActiveAgents.valueAt(i); 328 if (info.userId == userId) { 329 if (info.agent.isTrusted()) { 330 return true; 331 } 332 } 333 } 334 return false; 335 } 336 337 private boolean aggregateIsTrustManaged(int userId) { 338 if (!mUserHasAuthenticatedSinceBoot.get(userId)) { 339 return false; 340 } 341 for (int i = 0; i < mActiveAgents.size(); i++) { 342 AgentInfo info = mActiveAgents.valueAt(i); 343 if (info.userId == userId) { 344 if (info.agent.isManagingTrust()) { 345 return true; 346 } 347 } 348 } 349 return false; 350 } 351 352 private void dispatchUnlockAttempt(boolean successful, int userId) { 353 for (int i = 0; i < mActiveAgents.size(); i++) { 354 AgentInfo info = mActiveAgents.valueAt(i); 355 if (info.userId == userId) { 356 info.agent.onUnlockAttempt(successful); 357 } 358 } 359 360 if (successful && !mUserHasAuthenticatedSinceBoot.get(userId)) { 361 mUserHasAuthenticatedSinceBoot.put(userId, true); 362 updateTrust(userId); 363 } 364 } 365 366 367 private void requireCredentialEntry(int userId) { 368 if (userId == UserHandle.USER_ALL) { 369 mUserHasAuthenticatedSinceBoot.clear(); 370 updateTrustAll(); 371 } else { 372 mUserHasAuthenticatedSinceBoot.put(userId, false); 373 updateTrust(userId); 374 } 375 } 376 377 // Listeners 378 379 private void addListener(ITrustListener listener) { 380 for (int i = 0; i < mTrustListeners.size(); i++) { 381 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) { 382 return; 383 } 384 } 385 mTrustListeners.add(listener); 386 } 387 388 private void removeListener(ITrustListener listener) { 389 for (int i = 0; i < mTrustListeners.size(); i++) { 390 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) { 391 mTrustListeners.remove(i); 392 return; 393 } 394 } 395 } 396 397 private void dispatchOnTrustChanged(boolean enabled, int userId) { 398 for (int i = 0; i < mTrustListeners.size(); i++) { 399 try { 400 mTrustListeners.get(i).onTrustChanged(enabled, userId); 401 } catch (DeadObjectException e) { 402 Slog.d(TAG, "Removing dead TrustListener."); 403 mTrustListeners.remove(i); 404 i--; 405 } catch (RemoteException e) { 406 Slog.e(TAG, "Exception while notifying TrustListener.", e); 407 } 408 } 409 } 410 411 private void dispatchOnTrustManagedChanged(boolean managed, int userId) { 412 for (int i = 0; i < mTrustListeners.size(); i++) { 413 try { 414 mTrustListeners.get(i).onTrustManagedChanged(managed, userId); 415 } catch (DeadObjectException e) { 416 Slog.d(TAG, "Removing dead TrustListener."); 417 mTrustListeners.remove(i); 418 i--; 419 } catch (RemoteException e) { 420 Slog.e(TAG, "Exception while notifying TrustListener.", e); 421 } 422 } 423 } 424 425 // Plumbing 426 427 private final IBinder mService = new ITrustManager.Stub() { 428 @Override 429 public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException { 430 enforceReportPermission(); 431 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId) 432 .sendToTarget(); 433 } 434 435 @Override 436 public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException { 437 enforceReportPermission(); 438 // coalesce refresh messages. 439 mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED); 440 mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED); 441 } 442 443 @Override 444 public void reportRequireCredentialEntry(int userId) throws RemoteException { 445 enforceReportPermission(); 446 if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_OWNER) { 447 mHandler.obtainMessage(MSG_REQUIRE_CREDENTIAL_ENTRY, userId, 0).sendToTarget(); 448 } else { 449 throw new IllegalArgumentException( 450 "userId must be an explicit user id or USER_ALL"); 451 } 452 } 453 454 @Override 455 public void registerTrustListener(ITrustListener trustListener) throws RemoteException { 456 enforceListenerPermission(); 457 mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget(); 458 } 459 460 @Override 461 public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException { 462 enforceListenerPermission(); 463 mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget(); 464 } 465 466 private void enforceReportPermission() { 467 mContext.enforceCallingOrSelfPermission( 468 Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, "reporting trust events"); 469 } 470 471 private void enforceListenerPermission() { 472 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER, 473 "register trust listener"); 474 } 475 476 @Override 477 protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) { 478 mContext.enforceCallingPermission(Manifest.permission.DUMP, 479 "dumping TrustManagerService"); 480 final UserInfo currentUser; 481 final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */); 482 try { 483 currentUser = ActivityManagerNative.getDefault().getCurrentUser(); 484 } catch (RemoteException e) { 485 throw new RuntimeException(e); 486 } 487 mHandler.runWithScissors(new Runnable() { 488 @Override 489 public void run() { 490 fout.println("Trust manager state:"); 491 for (UserInfo user : userInfos) { 492 dumpUser(fout, user, user.id == currentUser.id); 493 } 494 } 495 }, 1500); 496 } 497 498 private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) { 499 fout.printf(" User \"%s\" (id=%d, flags=%#x)", 500 user.name, user.id, user.flags); 501 if (isCurrent) { 502 fout.print(" (current)"); 503 } 504 fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id))); 505 fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id))); 506 fout.println(); 507 fout.println(" Enabled agents:"); 508 boolean duplicateSimpleNames = false; 509 ArraySet<String> simpleNames = new ArraySet<String>(); 510 for (AgentInfo info : mActiveAgents) { 511 if (info.userId != user.id) { continue; } 512 boolean trusted = info.agent.isTrusted(); 513 fout.print(" "); fout.println(info.component.flattenToShortString()); 514 fout.print(" bound=" + dumpBool(info.agent.isBound())); 515 fout.print(", connected=" + dumpBool(info.agent.isConnected())); 516 fout.print(", managingTrust=" + dumpBool(info.agent.isManagingTrust())); 517 fout.print(", trusted=" + dumpBool(trusted)); 518 fout.println(); 519 if (trusted) { 520 fout.println(" message=\"" + info.agent.getMessage() + "\""); 521 } 522 if (!info.agent.isConnected()) { 523 String restartTime = TrustArchive.formatDuration( 524 info.agent.getScheduledRestartUptimeMillis() 525 - SystemClock.uptimeMillis()); 526 fout.println(" restartScheduledAt=" + restartTime); 527 } 528 if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) { 529 duplicateSimpleNames = true; 530 } 531 } 532 fout.println(" Events:"); 533 mArchive.dump(fout, 50, user.id, " " /* linePrefix */, duplicateSimpleNames); 534 fout.println(); 535 } 536 537 private String dumpBool(boolean b) { 538 return b ? "1" : "0"; 539 } 540 }; 541 542 private final Handler mHandler = new Handler() { 543 @Override 544 public void handleMessage(Message msg) { 545 switch (msg.what) { 546 case MSG_REGISTER_LISTENER: 547 addListener((ITrustListener) msg.obj); 548 break; 549 case MSG_UNREGISTER_LISTENER: 550 removeListener((ITrustListener) msg.obj); 551 break; 552 case MSG_DISPATCH_UNLOCK_ATTEMPT: 553 dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2); 554 break; 555 case MSG_ENABLED_AGENTS_CHANGED: 556 refreshAgentList(); 557 break; 558 case MSG_REQUIRE_CREDENTIAL_ENTRY: 559 requireCredentialEntry(msg.arg1); 560 break; 561 } 562 } 563 }; 564 565 private final PackageMonitor mPackageMonitor = new PackageMonitor() { 566 @Override 567 public void onSomePackagesChanged() { 568 refreshAgentList(); 569 } 570 571 @Override 572 public boolean onPackageChanged(String packageName, int uid, String[] components) { 573 // We're interested in all changes, even if just some components get enabled / disabled. 574 return true; 575 } 576 577 @Override 578 public void onPackageDisappeared(String packageName, int reason) { 579 removeAgentsOfPackage(packageName); 580 } 581 }; 582 583 private class DevicePolicyReceiver extends BroadcastReceiver { 584 585 @Override 586 public void onReceive(Context context, Intent intent) { 587 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals( 588 intent.getAction())) { 589 refreshAgentList(); 590 } 591 } 592 593 public void register(Context context) { 594 context.registerReceiverAsUser(this, 595 UserHandle.ALL, 596 new IntentFilter( 597 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED), 598 null /* permission */, 599 null /* scheduler */); 600 } 601 } 602} 603