blob: 490536e6e8c334d84fa6fbf18b1802c4207bcc7b [file] [log] [blame]
Adrian Roos82142c22014-03-27 14:56:59 +01001/*
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;
Adrian Roos7a4f3d42014-05-02 12:12:20 +020027import android.app.ActivityManagerNative;
Adrian Roosca36b952014-05-16 18:52:29 +020028import android.app.admin.DevicePolicyManager;
Adrian Roos82142c22014-03-27 14:56:59 +010029import android.app.trust.ITrustListener;
30import android.app.trust.ITrustManager;
Adrian Roosca36b952014-05-16 18:52:29 +020031import android.content.BroadcastReceiver;
Adrian Roos82142c22014-03-27 14:56:59 +010032import android.content.ComponentName;
33import android.content.Context;
34import android.content.Intent;
Adrian Roosca36b952014-05-16 18:52:29 +020035import android.content.IntentFilter;
Adrian Roos82142c22014-03-27 14:56:59 +010036import 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;
Adrian Roosa4ba56b2014-05-20 12:56:25 +020043import android.os.DeadObjectException;
Adrian Roos82142c22014-03-27 14:56:59 +010044import android.os.Handler;
45import android.os.IBinder;
46import android.os.Message;
47import android.os.RemoteException;
Adrian Roosc5f95ce2014-07-24 16:00:46 +020048import android.os.SystemClock;
Adrian Roos82142c22014-03-27 14:56:59 +010049import android.os.UserHandle;
50import android.os.UserManager;
51import android.service.trust.TrustAgentService;
52import android.util.ArraySet;
53import android.util.AttributeSet;
Adrian Roos18ea8932014-05-28 14:53:06 +020054import android.util.Log;
Adrian Roos82142c22014-03-27 14:56:59 +010055import android.util.Slog;
Adrian Roos7046bfd2014-05-16 21:20:54 +020056import android.util.SparseBooleanArray;
Adrian Roos82142c22014-03-27 14:56:59 +010057import android.util.Xml;
58
Adrian Roos7a4f3d42014-05-02 12:12:20 +020059import java.io.FileDescriptor;
Adrian Roos82142c22014-03-27 14:56:59 +010060import java.io.IOException;
Adrian Roos7a4f3d42014-05-02 12:12:20 +020061import java.io.PrintWriter;
Adrian Roos82142c22014-03-27 14:56:59 +010062import 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);
Adrian Roos18ea8932014-05-28 14:53:06 +020086 private static final String PERMISSION_PROVIDE_AGENT = Manifest.permission.PROVIDE_TRUST_AGENT;
Adrian Roos82142c22014-03-27 14:56:59 +010087
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;
Adrian Roos2c12cfa2014-06-25 23:28:53 +020092 private static final int MSG_REQUIRE_CREDENTIAL_ENTRY = 5;
Adrian Roos82142c22014-03-27 14:56:59 +010093
94 private final ArraySet<AgentInfo> mActiveAgents = new ArraySet<AgentInfo>();
95 private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<ITrustListener>();
Adrian Roos9dbe1902014-08-13 18:25:52 +020096 private final Receiver mReceiver = new Receiver();
Adrian Roos7046bfd2014-05-16 21:20:54 +020097 private final SparseBooleanArray mUserHasAuthenticatedSinceBoot = new SparseBooleanArray();
Adrian Roos7a4f3d42014-05-02 12:12:20 +020098 /* package */ final TrustArchive mArchive = new TrustArchive();
Adrian Roos82142c22014-03-27 14:56:59 +010099 private final Context mContext;
100
101 private UserManager mUserManager;
102
Adrian Roos82142c22014-03-27 14:56:59 +0100103 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()) {
Adrian Roos82142c22014-03-27 14:56:59 +0100117 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Adrian Roos9dbe1902014-08-13 18:25:52 +0200118 mReceiver.register(mContext);
Adrian Roos82142c22014-03-27 14:56:59 +0100119 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) {
Adrian Roos3c9a3502014-08-06 19:09:45 +0200151 updateTrust(userInfo.id, false);
Adrian Roos82142c22014-03-27 14:56:59 +0100152 }
153 }
154
Adrian Roos3c9a3502014-08-06 19:09:45 +0200155 public void updateTrust(int userId, boolean initiatedByUser) {
Adrian Roos7861c662014-07-25 15:37:28 +0200156 dispatchOnTrustManagedChanged(aggregateIsTrustManaged(userId), userId);
Adrian Roos3c9a3502014-08-06 19:09:45 +0200157 dispatchOnTrustChanged(aggregateIsTrusted(userId), userId, initiatedByUser);
Adrian Roos82142c22014-03-27 14:56:59 +0100158 }
159
Adrian Roos8f211582014-07-29 15:09:57 +0200160 void refreshAgentList() {
Adrian Roos82142c22014-03-27 14:56:59 +0100161 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
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200167 ArraySet<AgentInfo> obsoleteAgents = new ArraySet<>();
168 obsoleteAgents.addAll(mActiveAgents);
Adrian Roos82142c22014-03-27 14:56:59 +0100169
170 for (UserInfo userInfo : userInfos) {
Adrian Roos8f211582014-07-29 15:09:57 +0200171 DevicePolicyManager dpm = lockPatternUtils.getDevicePolicyManager();
172 int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, userInfo.id);
Jim Miller604e7552014-07-18 19:00:02 -0700173 final boolean disableTrustAgents =
Adrian Roosca36b952014-05-16 18:52:29 +0200174 (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
175
Adrian Roos82142c22014-03-27 14:56:59 +0100176 List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id);
Adrian Roos8f211582014-07-29 15:09:57 +0200177 if (enabledAgents == null) {
Adrian Roos82142c22014-03-27 14:56:59 +0100178 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;
Adrian Roos18ea8932014-05-28 14:53:06 +0200184
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
Adrian Roos82142c22014-03-27 14:56:59 +0100193 ComponentName name = getComponentName(resolveInfo);
194 if (!enabledAgents.contains(name)) continue;
195
Adrian Roos8f211582014-07-29 15:09:57 +0200196 if (disableTrustAgents) {
197 List<String> features =
198 dpm.getTrustAgentFeaturesEnabled(null /* admin */, name);
199 // Disable agent if no features are enabled.
200 if (features == null || features.isEmpty()) continue;
201 }
202
Adrian Roos82142c22014-03-27 14:56:59 +0100203 AgentInfo agentInfo = new AgentInfo();
204 agentInfo.component = name;
205 agentInfo.userId = userInfo.id;
206 if (!mActiveAgents.contains(agentInfo)) {
207 agentInfo.label = resolveInfo.loadLabel(pm);
208 agentInfo.icon = resolveInfo.loadIcon(pm);
209 agentInfo.settings = getSettingsComponentName(pm, resolveInfo);
210 agentInfo.agent = new TrustAgentWrapper(mContext, this,
211 new Intent().setComponent(name), userInfo.getUserHandle());
212 mActiveAgents.add(agentInfo);
213 } else {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200214 obsoleteAgents.remove(agentInfo);
Adrian Roos82142c22014-03-27 14:56:59 +0100215 }
216 }
217 }
218
219 boolean trustMayHaveChanged = false;
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200220 for (int i = 0; i < obsoleteAgents.size(); i++) {
221 AgentInfo info = obsoleteAgents.valueAt(i);
Adrian Roos7861c662014-07-25 15:37:28 +0200222 if (info.agent.isManagingTrust()) {
Adrian Roos82142c22014-03-27 14:56:59 +0100223 trustMayHaveChanged = true;
224 }
225 info.agent.unbind();
Adrian Roosa5956422014-04-30 18:23:38 +0200226 mActiveAgents.remove(info);
Adrian Roos82142c22014-03-27 14:56:59 +0100227 }
228
229 if (trustMayHaveChanged) {
230 updateTrustAll();
231 }
232 }
233
Adrian Roos8f211582014-07-29 15:09:57 +0200234 void updateDevicePolicyFeatures(int userId) {
235 for (int i = 0; i < mActiveAgents.size(); i++) {
236 AgentInfo info = mActiveAgents.valueAt(i);
237 if (info.agent.isConnected()) {
238 info.agent.updateDevicePolicyFeatures();
239 }
240 }
241 }
242
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200243 private void removeAgentsOfPackage(String packageName) {
244 boolean trustMayHaveChanged = false;
245 for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
246 AgentInfo info = mActiveAgents.valueAt(i);
247 if (packageName.equals(info.component.getPackageName())) {
248 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
Adrian Roos7861c662014-07-25 15:37:28 +0200249 if (info.agent.isManagingTrust()) {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200250 trustMayHaveChanged = true;
251 }
252 info.agent.unbind();
253 mActiveAgents.removeAt(i);
254 }
255 }
256 if (trustMayHaveChanged) {
257 updateTrustAll();
258 }
259 }
260
261 public void resetAgent(ComponentName name, int userId) {
262 boolean trustMayHaveChanged = false;
263 for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
264 AgentInfo info = mActiveAgents.valueAt(i);
265 if (name.equals(info.component) && userId == info.userId) {
266 Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
Adrian Roos7861c662014-07-25 15:37:28 +0200267 if (info.agent.isManagingTrust()) {
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200268 trustMayHaveChanged = true;
269 }
270 info.agent.unbind();
271 mActiveAgents.removeAt(i);
272 }
273 }
274 if (trustMayHaveChanged) {
Adrian Roos3c9a3502014-08-06 19:09:45 +0200275 updateTrust(userId, false);
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200276 }
277 refreshAgentList();
278 }
279
Adrian Roos82142c22014-03-27 14:56:59 +0100280 private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) {
281 if (resolveInfo == null || resolveInfo.serviceInfo == null
282 || resolveInfo.serviceInfo.metaData == null) return null;
283 String cn = null;
284 XmlResourceParser parser = null;
285 Exception caughtException = null;
286 try {
287 parser = resolveInfo.serviceInfo.loadXmlMetaData(pm,
288 TrustAgentService.TRUST_AGENT_META_DATA);
289 if (parser == null) {
290 Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data");
291 return null;
292 }
293 Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
294 AttributeSet attrs = Xml.asAttributeSet(parser);
295 int type;
296 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
297 && type != XmlPullParser.START_TAG) {
298 // Drain preamble.
299 }
300 String nodeName = parser.getName();
Adrian Roos7e03dfc2014-05-16 16:06:28 +0200301 if (!"trust-agent".equals(nodeName)) {
302 Slog.w(TAG, "Meta-data does not start with trust-agent tag");
Adrian Roos82142c22014-03-27 14:56:59 +0100303 return null;
304 }
305 TypedArray sa = res
306 .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
307 cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
308 sa.recycle();
309 } catch (PackageManager.NameNotFoundException e) {
310 caughtException = e;
311 } catch (IOException e) {
312 caughtException = e;
313 } catch (XmlPullParserException e) {
314 caughtException = e;
315 } finally {
316 if (parser != null) parser.close();
317 }
318 if (caughtException != null) {
319 Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
320 return null;
321 }
322 if (cn == null) {
323 return null;
324 }
325 if (cn.indexOf('/') < 0) {
326 cn = resolveInfo.serviceInfo.packageName + "/" + cn;
327 }
328 return ComponentName.unflattenFromString(cn);
329 }
330
331 private ComponentName getComponentName(ResolveInfo resolveInfo) {
332 if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
333 return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
334 }
335
336 // Agent dispatch and aggregation
337
338 private boolean aggregateIsTrusted(int userId) {
Adrian Roos7046bfd2014-05-16 21:20:54 +0200339 if (!mUserHasAuthenticatedSinceBoot.get(userId)) {
340 return false;
341 }
Adrian Roos82142c22014-03-27 14:56:59 +0100342 for (int i = 0; i < mActiveAgents.size(); i++) {
343 AgentInfo info = mActiveAgents.valueAt(i);
344 if (info.userId == userId) {
345 if (info.agent.isTrusted()) {
346 return true;
347 }
348 }
349 }
350 return false;
351 }
352
Adrian Roos7861c662014-07-25 15:37:28 +0200353 private boolean aggregateIsTrustManaged(int userId) {
354 if (!mUserHasAuthenticatedSinceBoot.get(userId)) {
355 return false;
356 }
357 for (int i = 0; i < mActiveAgents.size(); i++) {
358 AgentInfo info = mActiveAgents.valueAt(i);
359 if (info.userId == userId) {
360 if (info.agent.isManagingTrust()) {
361 return true;
362 }
363 }
364 }
365 return false;
366 }
367
Adrian Roos82142c22014-03-27 14:56:59 +0100368 private void dispatchUnlockAttempt(boolean successful, int userId) {
369 for (int i = 0; i < mActiveAgents.size(); i++) {
370 AgentInfo info = mActiveAgents.valueAt(i);
371 if (info.userId == userId) {
372 info.agent.onUnlockAttempt(successful);
373 }
374 }
Adrian Roos7046bfd2014-05-16 21:20:54 +0200375
Adrian Roos9dbe1902014-08-13 18:25:52 +0200376 if (successful) {
377 updateUserHasAuthenticated(userId);
378 }
379 }
380
381 private void updateUserHasAuthenticated(int userId) {
382 if (!mUserHasAuthenticatedSinceBoot.get(userId)) {
Adrian Roos7046bfd2014-05-16 21:20:54 +0200383 mUserHasAuthenticatedSinceBoot.put(userId, true);
Adrian Roos3c9a3502014-08-06 19:09:45 +0200384 updateTrust(userId, false);
Adrian Roos7046bfd2014-05-16 21:20:54 +0200385 }
Adrian Roos82142c22014-03-27 14:56:59 +0100386 }
387
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200388
389 private void requireCredentialEntry(int userId) {
390 if (userId == UserHandle.USER_ALL) {
391 mUserHasAuthenticatedSinceBoot.clear();
392 updateTrustAll();
393 } else {
394 mUserHasAuthenticatedSinceBoot.put(userId, false);
Adrian Roos3c9a3502014-08-06 19:09:45 +0200395 updateTrust(userId, false);
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200396 }
397 }
398
Adrian Roos82142c22014-03-27 14:56:59 +0100399 // Listeners
400
401 private void addListener(ITrustListener listener) {
402 for (int i = 0; i < mTrustListeners.size(); i++) {
403 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
404 return;
405 }
406 }
407 mTrustListeners.add(listener);
408 }
409
410 private void removeListener(ITrustListener listener) {
411 for (int i = 0; i < mTrustListeners.size(); i++) {
412 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
Jay Civelli979a32e2014-07-18 16:47:36 -0700413 mTrustListeners.remove(i);
Adrian Roos82142c22014-03-27 14:56:59 +0100414 return;
415 }
416 }
417 }
418
Adrian Roos3c9a3502014-08-06 19:09:45 +0200419 private void dispatchOnTrustChanged(boolean enabled, int userId, boolean initiatedByUser) {
420 if (!enabled) initiatedByUser = false;
Adrian Roos82142c22014-03-27 14:56:59 +0100421 for (int i = 0; i < mTrustListeners.size(); i++) {
422 try {
Adrian Roos3c9a3502014-08-06 19:09:45 +0200423 mTrustListeners.get(i).onTrustChanged(enabled, userId, initiatedByUser);
Adrian Roosa4ba56b2014-05-20 12:56:25 +0200424 } catch (DeadObjectException e) {
Adrian Roos7861c662014-07-25 15:37:28 +0200425 Slog.d(TAG, "Removing dead TrustListener.");
426 mTrustListeners.remove(i);
427 i--;
428 } catch (RemoteException e) {
429 Slog.e(TAG, "Exception while notifying TrustListener.", e);
430 }
431 }
432 }
433
434 private void dispatchOnTrustManagedChanged(boolean managed, int userId) {
435 for (int i = 0; i < mTrustListeners.size(); i++) {
436 try {
437 mTrustListeners.get(i).onTrustManagedChanged(managed, userId);
438 } catch (DeadObjectException e) {
439 Slog.d(TAG, "Removing dead TrustListener.");
Adrian Roosa4ba56b2014-05-20 12:56:25 +0200440 mTrustListeners.remove(i);
441 i--;
Adrian Roos82142c22014-03-27 14:56:59 +0100442 } catch (RemoteException e) {
Adrian Roosa4ba56b2014-05-20 12:56:25 +0200443 Slog.e(TAG, "Exception while notifying TrustListener.", e);
Adrian Roos82142c22014-03-27 14:56:59 +0100444 }
445 }
446 }
447
448 // Plumbing
449
450 private final IBinder mService = new ITrustManager.Stub() {
451 @Override
452 public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException {
453 enforceReportPermission();
454 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId)
455 .sendToTarget();
456 }
457
458 @Override
459 public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException {
460 enforceReportPermission();
461 // coalesce refresh messages.
462 mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED);
463 mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED);
464 }
465
466 @Override
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200467 public void reportRequireCredentialEntry(int userId) throws RemoteException {
468 enforceReportPermission();
469 if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_OWNER) {
470 mHandler.obtainMessage(MSG_REQUIRE_CREDENTIAL_ENTRY, userId, 0).sendToTarget();
471 } else {
472 throw new IllegalArgumentException(
473 "userId must be an explicit user id or USER_ALL");
474 }
475 }
476
477 @Override
Adrian Roos82142c22014-03-27 14:56:59 +0100478 public void registerTrustListener(ITrustListener trustListener) throws RemoteException {
479 enforceListenerPermission();
480 mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget();
481 }
482
483 @Override
484 public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException {
485 enforceListenerPermission();
486 mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget();
487 }
488
489 private void enforceReportPermission() {
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200490 mContext.enforceCallingOrSelfPermission(
491 Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, "reporting trust events");
Adrian Roos82142c22014-03-27 14:56:59 +0100492 }
493
494 private void enforceListenerPermission() {
495 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER,
496 "register trust listener");
497 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200498
499 @Override
500 protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) {
501 mContext.enforceCallingPermission(Manifest.permission.DUMP,
502 "dumping TrustManagerService");
503 final UserInfo currentUser;
504 final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
505 try {
506 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
507 } catch (RemoteException e) {
508 throw new RuntimeException(e);
509 }
510 mHandler.runWithScissors(new Runnable() {
511 @Override
512 public void run() {
513 fout.println("Trust manager state:");
514 for (UserInfo user : userInfos) {
515 dumpUser(fout, user, user.id == currentUser.id);
516 }
517 }
518 }, 1500);
519 }
520
521 private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) {
522 fout.printf(" User \"%s\" (id=%d, flags=%#x)",
523 user.name, user.id, user.flags);
524 if (isCurrent) {
525 fout.print(" (current)");
526 }
527 fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id)));
Adrian Roos7861c662014-07-25 15:37:28 +0200528 fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id)));
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200529 fout.println();
530 fout.println(" Enabled agents:");
531 boolean duplicateSimpleNames = false;
532 ArraySet<String> simpleNames = new ArraySet<String>();
533 for (AgentInfo info : mActiveAgents) {
534 if (info.userId != user.id) { continue; }
535 boolean trusted = info.agent.isTrusted();
536 fout.print(" "); fout.println(info.component.flattenToShortString());
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200537 fout.print(" bound=" + dumpBool(info.agent.isBound()));
538 fout.print(", connected=" + dumpBool(info.agent.isConnected()));
Adrian Roos7861c662014-07-25 15:37:28 +0200539 fout.print(", managingTrust=" + dumpBool(info.agent.isManagingTrust()));
540 fout.print(", trusted=" + dumpBool(trusted));
541 fout.println();
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200542 if (trusted) {
543 fout.println(" message=\"" + info.agent.getMessage() + "\"");
544 }
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200545 if (!info.agent.isConnected()) {
546 String restartTime = TrustArchive.formatDuration(
547 info.agent.getScheduledRestartUptimeMillis()
548 - SystemClock.uptimeMillis());
549 fout.println(" restartScheduledAt=" + restartTime);
550 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200551 if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) {
552 duplicateSimpleNames = true;
553 }
554 }
555 fout.println(" Events:");
556 mArchive.dump(fout, 50, user.id, " " /* linePrefix */, duplicateSimpleNames);
557 fout.println();
558 }
559
560 private String dumpBool(boolean b) {
561 return b ? "1" : "0";
562 }
Adrian Roos82142c22014-03-27 14:56:59 +0100563 };
564
565 private final Handler mHandler = new Handler() {
566 @Override
567 public void handleMessage(Message msg) {
568 switch (msg.what) {
569 case MSG_REGISTER_LISTENER:
570 addListener((ITrustListener) msg.obj);
571 break;
572 case MSG_UNREGISTER_LISTENER:
573 removeListener((ITrustListener) msg.obj);
574 break;
575 case MSG_DISPATCH_UNLOCK_ATTEMPT:
576 dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
577 break;
578 case MSG_ENABLED_AGENTS_CHANGED:
579 refreshAgentList();
580 break;
Adrian Roos2c12cfa2014-06-25 23:28:53 +0200581 case MSG_REQUIRE_CREDENTIAL_ENTRY:
582 requireCredentialEntry(msg.arg1);
583 break;
Adrian Roos82142c22014-03-27 14:56:59 +0100584 }
585 }
586 };
587
588 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
589 @Override
590 public void onSomePackagesChanged() {
591 refreshAgentList();
592 }
593
594 @Override
595 public boolean onPackageChanged(String packageName, int uid, String[] components) {
596 // We're interested in all changes, even if just some components get enabled / disabled.
597 return true;
598 }
Adrian Roosc5f95ce2014-07-24 16:00:46 +0200599
600 @Override
601 public void onPackageDisappeared(String packageName, int reason) {
602 removeAgentsOfPackage(packageName);
603 }
Adrian Roos82142c22014-03-27 14:56:59 +0100604 };
Adrian Roosca36b952014-05-16 18:52:29 +0200605
Adrian Roos9dbe1902014-08-13 18:25:52 +0200606 private class Receiver extends BroadcastReceiver {
Adrian Roosca36b952014-05-16 18:52:29 +0200607
608 @Override
609 public void onReceive(Context context, Intent intent) {
610 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(
611 intent.getAction())) {
612 refreshAgentList();
Adrian Roos8f211582014-07-29 15:09:57 +0200613 updateDevicePolicyFeatures(getSendingUserId());
Adrian Roos9dbe1902014-08-13 18:25:52 +0200614 } else if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())) {
615 updateUserHasAuthenticated(getSendingUserId());
Adrian Roosca36b952014-05-16 18:52:29 +0200616 }
617 }
618
619 public void register(Context context) {
Adrian Roos9dbe1902014-08-13 18:25:52 +0200620 IntentFilter filter = new IntentFilter();
621 filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
622 filter.addAction(Intent.ACTION_USER_PRESENT);
Adrian Roosca36b952014-05-16 18:52:29 +0200623 context.registerReceiverAsUser(this,
624 UserHandle.ALL,
Adrian Roos9dbe1902014-08-13 18:25:52 +0200625 filter,
Adrian Roosca36b952014-05-16 18:52:29 +0200626 null /* permission */,
627 null /* scheduler */);
628 }
629 }
Adrian Roos82142c22014-03-27 14:56:59 +0100630}