blob: 462b234c8c21be522a47c6d559c2006ac268f428 [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;
43import android.os.Handler;
44import android.os.IBinder;
45import android.os.Message;
46import android.os.RemoteException;
47import android.os.UserHandle;
48import android.os.UserManager;
49import android.service.trust.TrustAgentService;
50import android.util.ArraySet;
51import android.util.AttributeSet;
Adrian Roos18ea8932014-05-28 14:53:06 +020052import android.util.Log;
Adrian Roos82142c22014-03-27 14:56:59 +010053import android.util.Slog;
Adrian Roos7046bfd2014-05-16 21:20:54 +020054import android.util.SparseBooleanArray;
Adrian Roos82142c22014-03-27 14:56:59 +010055import android.util.Xml;
56
Adrian Roos7a4f3d42014-05-02 12:12:20 +020057import java.io.FileDescriptor;
Adrian Roos82142c22014-03-27 14:56:59 +010058import java.io.IOException;
Adrian Roos7a4f3d42014-05-02 12:12:20 +020059import java.io.PrintWriter;
Adrian Roos82142c22014-03-27 14:56:59 +010060import java.util.ArrayList;
61import java.util.List;
62
63/**
64 * Manages trust agents and trust listeners.
65 *
66 * It is responsible for binding to the enabled {@link android.service.trust.TrustAgentService}s
67 * of each user and notifies them about events that are relevant to them.
68 * It start and stops them based on the value of
69 * {@link com.android.internal.widget.LockPatternUtils#getEnabledTrustAgents(int)}.
70 *
71 * It also keeps a set of {@link android.app.trust.ITrustListener}s that are notified whenever the
72 * trust state changes for any user.
73 *
74 * Trust state and the setting of enabled agents is kept per user and each user has its own
75 * instance of a {@link android.service.trust.TrustAgentService}.
76 */
77public class TrustManagerService extends SystemService {
78
79 private static final boolean DEBUG = false;
80 private static final String TAG = "TrustManagerService";
81
82 private static final Intent TRUST_AGENT_INTENT =
83 new Intent(TrustAgentService.SERVICE_INTERFACE);
Adrian Roos18ea8932014-05-28 14:53:06 +020084 private static final String PERMISSION_PROVIDE_AGENT = Manifest.permission.PROVIDE_TRUST_AGENT;
Adrian Roos82142c22014-03-27 14:56:59 +010085
86 private static final int MSG_REGISTER_LISTENER = 1;
87 private static final int MSG_UNREGISTER_LISTENER = 2;
88 private static final int MSG_DISPATCH_UNLOCK_ATTEMPT = 3;
89 private static final int MSG_ENABLED_AGENTS_CHANGED = 4;
90
91 private final ArraySet<AgentInfo> mActiveAgents = new ArraySet<AgentInfo>();
92 private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<ITrustListener>();
Adrian Roosca36b952014-05-16 18:52:29 +020093 private final DevicePolicyReceiver mDevicePolicyReceiver = new DevicePolicyReceiver();
Adrian Roos7046bfd2014-05-16 21:20:54 +020094 private final SparseBooleanArray mUserHasAuthenticatedSinceBoot = new SparseBooleanArray();
Adrian Roos7a4f3d42014-05-02 12:12:20 +020095 /* package */ final TrustArchive mArchive = new TrustArchive();
Adrian Roos82142c22014-03-27 14:56:59 +010096 private final Context mContext;
97
98 private UserManager mUserManager;
99
100 /**
101 * Cache for {@link #refreshAgentList()}
102 */
103 private final ArraySet<AgentInfo> mObsoleteAgents = new ArraySet<AgentInfo>();
104
105
106 public TrustManagerService(Context context) {
107 super(context);
108 mContext = context;
109 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
110 }
111
112 @Override
113 public void onStart() {
114 publishBinderService(Context.TRUST_SERVICE, mService);
115 }
116
117 @Override
118 public void onBootPhase(int phase) {
119 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY && !isSafeMode()) {
Adrian Roos82142c22014-03-27 14:56:59 +0100120 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Adrian Roosca36b952014-05-16 18:52:29 +0200121 mDevicePolicyReceiver.register(mContext);
Adrian Roos82142c22014-03-27 14:56:59 +0100122 refreshAgentList();
123 }
124 }
125
126 // Agent management
127
128 private static final class AgentInfo {
129 CharSequence label;
130 Drawable icon;
131 ComponentName component; // service that implements ITrustAgent
132 ComponentName settings; // setting to launch to modify agent.
133 TrustAgentWrapper agent;
134 int userId;
135
136 @Override
137 public boolean equals(Object other) {
138 if (!(other instanceof AgentInfo)) {
139 return false;
140 }
141 AgentInfo o = (AgentInfo) other;
142 return component.equals(o.component) && userId == o.userId;
143 }
144
145 @Override
146 public int hashCode() {
147 return component.hashCode() * 31 + userId;
148 }
149 }
150
151 private void updateTrustAll() {
152 List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
153 for (UserInfo userInfo : userInfos) {
154 updateTrust(userInfo.id);
155 }
156 }
157
158 public void updateTrust(int userId) {
159 dispatchOnTrustChanged(aggregateIsTrusted(userId), userId);
160 }
161
162 protected void refreshAgentList() {
163 if (DEBUG) Slog.d(TAG, "refreshAgentList()");
164 PackageManager pm = mContext.getPackageManager();
165
166 List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
167 LockPatternUtils lockPatternUtils = new LockPatternUtils(mContext);
168
169 mObsoleteAgents.clear();
170 mObsoleteAgents.addAll(mActiveAgents);
171
172 for (UserInfo userInfo : userInfos) {
Adrian Roosca36b952014-05-16 18:52:29 +0200173 int disabledFeatures = lockPatternUtils.getDevicePolicyManager()
174 .getKeyguardDisabledFeatures(null, userInfo.id);
175 boolean disableTrustAgents =
176 (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
177
Adrian Roos82142c22014-03-27 14:56:59 +0100178 List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id);
Adrian Roosca36b952014-05-16 18:52:29 +0200179 if (disableTrustAgents || enabledAgents == null) {
Adrian Roos82142c22014-03-27 14:56:59 +0100180 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;
Adrian Roos18ea8932014-05-28 14:53:06 +0200186
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
Adrian Roos82142c22014-03-27 14:56:59 +0100195 ComponentName name = getComponentName(resolveInfo);
196 if (!enabledAgents.contains(name)) continue;
197
198 AgentInfo agentInfo = new AgentInfo();
199 agentInfo.component = name;
200 agentInfo.userId = userInfo.id;
201 if (!mActiveAgents.contains(agentInfo)) {
202 agentInfo.label = resolveInfo.loadLabel(pm);
203 agentInfo.icon = resolveInfo.loadIcon(pm);
204 agentInfo.settings = getSettingsComponentName(pm, resolveInfo);
205 agentInfo.agent = new TrustAgentWrapper(mContext, this,
206 new Intent().setComponent(name), userInfo.getUserHandle());
207 mActiveAgents.add(agentInfo);
208 } else {
209 mObsoleteAgents.remove(agentInfo);
210 }
211 }
212 }
213
214 boolean trustMayHaveChanged = false;
215 for (int i = 0; i < mObsoleteAgents.size(); i++) {
Adrian Roos81e04662014-04-30 17:48:18 +0200216 AgentInfo info = mObsoleteAgents.valueAt(i);
Adrian Roos82142c22014-03-27 14:56:59 +0100217 if (info.agent.isTrusted()) {
218 trustMayHaveChanged = true;
219 }
220 info.agent.unbind();
Adrian Roosa5956422014-04-30 18:23:38 +0200221 mActiveAgents.remove(info);
Adrian Roos82142c22014-03-27 14:56:59 +0100222 }
223
224 if (trustMayHaveChanged) {
225 updateTrustAll();
226 }
227 }
228
229 private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) {
230 if (resolveInfo == null || resolveInfo.serviceInfo == null
231 || resolveInfo.serviceInfo.metaData == null) return null;
232 String cn = null;
233 XmlResourceParser parser = null;
234 Exception caughtException = null;
235 try {
236 parser = resolveInfo.serviceInfo.loadXmlMetaData(pm,
237 TrustAgentService.TRUST_AGENT_META_DATA);
238 if (parser == null) {
239 Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data");
240 return null;
241 }
242 Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
243 AttributeSet attrs = Xml.asAttributeSet(parser);
244 int type;
245 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
246 && type != XmlPullParser.START_TAG) {
247 // Drain preamble.
248 }
249 String nodeName = parser.getName();
Adrian Roos7e03dfc2014-05-16 16:06:28 +0200250 if (!"trust-agent".equals(nodeName)) {
251 Slog.w(TAG, "Meta-data does not start with trust-agent tag");
Adrian Roos82142c22014-03-27 14:56:59 +0100252 return null;
253 }
254 TypedArray sa = res
255 .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
256 cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
257 sa.recycle();
258 } catch (PackageManager.NameNotFoundException e) {
259 caughtException = e;
260 } catch (IOException e) {
261 caughtException = e;
262 } catch (XmlPullParserException e) {
263 caughtException = e;
264 } finally {
265 if (parser != null) parser.close();
266 }
267 if (caughtException != null) {
268 Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
269 return null;
270 }
271 if (cn == null) {
272 return null;
273 }
274 if (cn.indexOf('/') < 0) {
275 cn = resolveInfo.serviceInfo.packageName + "/" + cn;
276 }
277 return ComponentName.unflattenFromString(cn);
278 }
279
280 private ComponentName getComponentName(ResolveInfo resolveInfo) {
281 if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
282 return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
283 }
284
285 // Agent dispatch and aggregation
286
287 private boolean aggregateIsTrusted(int userId) {
Adrian Roos7046bfd2014-05-16 21:20:54 +0200288 if (!mUserHasAuthenticatedSinceBoot.get(userId)) {
289 return false;
290 }
Adrian Roos82142c22014-03-27 14:56:59 +0100291 for (int i = 0; i < mActiveAgents.size(); i++) {
292 AgentInfo info = mActiveAgents.valueAt(i);
293 if (info.userId == userId) {
294 if (info.agent.isTrusted()) {
295 return true;
296 }
297 }
298 }
299 return false;
300 }
301
302 private void dispatchUnlockAttempt(boolean successful, int userId) {
303 for (int i = 0; i < mActiveAgents.size(); i++) {
304 AgentInfo info = mActiveAgents.valueAt(i);
305 if (info.userId == userId) {
306 info.agent.onUnlockAttempt(successful);
307 }
308 }
Adrian Roos7046bfd2014-05-16 21:20:54 +0200309
310 if (successful && !mUserHasAuthenticatedSinceBoot.get(userId)) {
311 mUserHasAuthenticatedSinceBoot.put(userId, true);
312 updateTrust(userId);
313 }
Adrian Roos82142c22014-03-27 14:56:59 +0100314 }
315
316 // Listeners
317
318 private void addListener(ITrustListener listener) {
319 for (int i = 0; i < mTrustListeners.size(); i++) {
320 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
321 return;
322 }
323 }
324 mTrustListeners.add(listener);
325 }
326
327 private void removeListener(ITrustListener listener) {
328 for (int i = 0; i < mTrustListeners.size(); i++) {
329 if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
330 mTrustListeners.get(i);
331 return;
332 }
333 }
334 }
335
336 private void dispatchOnTrustChanged(boolean enabled, int userId) {
337 for (int i = 0; i < mTrustListeners.size(); i++) {
338 try {
339 mTrustListeners.get(i).onTrustChanged(enabled, userId);
340 } catch (RemoteException e) {
341 Slog.e(TAG, "Exception while notifying TrustListener. Removing listener.", e);
Adrian Roos82142c22014-03-27 14:56:59 +0100342 }
343 }
344 }
345
346 // Plumbing
347
348 private final IBinder mService = new ITrustManager.Stub() {
349 @Override
350 public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException {
351 enforceReportPermission();
352 mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId)
353 .sendToTarget();
354 }
355
356 @Override
357 public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException {
358 enforceReportPermission();
359 // coalesce refresh messages.
360 mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED);
361 mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED);
362 }
363
364 @Override
365 public void registerTrustListener(ITrustListener trustListener) throws RemoteException {
366 enforceListenerPermission();
367 mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget();
368 }
369
370 @Override
371 public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException {
372 enforceListenerPermission();
373 mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget();
374 }
375
376 private void enforceReportPermission() {
377 mContext.enforceCallingPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE,
378 "reporting trust events");
379 }
380
381 private void enforceListenerPermission() {
382 mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER,
383 "register trust listener");
384 }
Adrian Roos7a4f3d42014-05-02 12:12:20 +0200385
386 @Override
387 protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) {
388 mContext.enforceCallingPermission(Manifest.permission.DUMP,
389 "dumping TrustManagerService");
390 final UserInfo currentUser;
391 final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
392 try {
393 currentUser = ActivityManagerNative.getDefault().getCurrentUser();
394 } catch (RemoteException e) {
395 throw new RuntimeException(e);
396 }
397 mHandler.runWithScissors(new Runnable() {
398 @Override
399 public void run() {
400 fout.println("Trust manager state:");
401 for (UserInfo user : userInfos) {
402 dumpUser(fout, user, user.id == currentUser.id);
403 }
404 }
405 }, 1500);
406 }
407
408 private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) {
409 fout.printf(" User \"%s\" (id=%d, flags=%#x)",
410 user.name, user.id, user.flags);
411 if (isCurrent) {
412 fout.print(" (current)");
413 }
414 fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id)));
415 fout.println();
416 fout.println(" Enabled agents:");
417 boolean duplicateSimpleNames = false;
418 ArraySet<String> simpleNames = new ArraySet<String>();
419 for (AgentInfo info : mActiveAgents) {
420 if (info.userId != user.id) { continue; }
421 boolean trusted = info.agent.isTrusted();
422 fout.print(" "); fout.println(info.component.flattenToShortString());
423 fout.print(" connected=" + dumpBool(info.agent.isConnected()));
424 fout.println(", trusted=" + dumpBool(trusted));
425 if (trusted) {
426 fout.println(" message=\"" + info.agent.getMessage() + "\"");
427 }
428 if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) {
429 duplicateSimpleNames = true;
430 }
431 }
432 fout.println(" Events:");
433 mArchive.dump(fout, 50, user.id, " " /* linePrefix */, duplicateSimpleNames);
434 fout.println();
435 }
436
437 private String dumpBool(boolean b) {
438 return b ? "1" : "0";
439 }
Adrian Roos82142c22014-03-27 14:56:59 +0100440 };
441
442 private final Handler mHandler = new Handler() {
443 @Override
444 public void handleMessage(Message msg) {
445 switch (msg.what) {
446 case MSG_REGISTER_LISTENER:
447 addListener((ITrustListener) msg.obj);
448 break;
449 case MSG_UNREGISTER_LISTENER:
450 removeListener((ITrustListener) msg.obj);
451 break;
452 case MSG_DISPATCH_UNLOCK_ATTEMPT:
453 dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
454 break;
455 case MSG_ENABLED_AGENTS_CHANGED:
456 refreshAgentList();
457 break;
458 }
459 }
460 };
461
462 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
463 @Override
464 public void onSomePackagesChanged() {
465 refreshAgentList();
466 }
467
468 @Override
469 public boolean onPackageChanged(String packageName, int uid, String[] components) {
470 // We're interested in all changes, even if just some components get enabled / disabled.
471 return true;
472 }
473 };
Adrian Roosca36b952014-05-16 18:52:29 +0200474
475 private class DevicePolicyReceiver extends BroadcastReceiver {
476
477 @Override
478 public void onReceive(Context context, Intent intent) {
479 if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(
480 intent.getAction())) {
481 refreshAgentList();
482 }
483 }
484
485 public void register(Context context) {
486 context.registerReceiverAsUser(this,
487 UserHandle.ALL,
488 new IntentFilter(
489 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
490 null /* permission */,
491 null /* scheduler */);
492 }
493 }
Adrian Roos82142c22014-03-27 14:56:59 +0100494}