TrustManagerService.java revision 8ae1be120806d0189f65a492004a7b5416aa6c6f
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.annotations.GuardedBy;
20import com.android.internal.content.PackageMonitor;
21import com.android.internal.widget.LockPatternUtils;
22import com.android.server.SystemService;
23
24import org.xmlpull.v1.XmlPullParser;
25import org.xmlpull.v1.XmlPullParserException;
26
27import android.Manifest;
28import android.app.ActivityManager;
29import android.app.admin.DevicePolicyManager;
30import android.app.trust.ITrustListener;
31import android.app.trust.ITrustManager;
32import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.pm.ApplicationInfo;
38import android.content.pm.PackageManager;
39import android.content.pm.ResolveInfo;
40import android.content.pm.UserInfo;
41import android.content.res.Resources;
42import android.content.res.TypedArray;
43import android.content.res.XmlResourceParser;
44import android.graphics.drawable.Drawable;
45import android.os.Binder;
46import android.os.DeadObjectException;
47import android.os.Handler;
48import android.os.IBinder;
49import android.os.Message;
50import android.os.PersistableBundle;
51import android.os.RemoteException;
52import android.os.SystemClock;
53import android.os.UserHandle;
54import android.os.UserManager;
55import android.provider.Settings;
56import android.service.trust.TrustAgentService;
57import android.util.ArraySet;
58import android.util.AttributeSet;
59import android.util.Log;
60import android.util.Slog;
61import android.util.SparseBooleanArray;
62import android.util.Xml;
63import android.view.IWindowManager;
64import android.view.WindowManagerGlobal;
65
66import java.io.FileDescriptor;
67import java.io.IOException;
68import java.io.PrintWriter;
69import java.util.ArrayList;
70import java.util.List;
71
72/**
73 * Manages trust agents and trust listeners.
74 *
75 * It is responsible for binding to the enabled {@link android.service.trust.TrustAgentService}s
76 * of each user and notifies them about events that are relevant to them.
77 * It start and stops them based on the value of
78 * {@link com.android.internal.widget.LockPatternUtils#getEnabledTrustAgents(int)}.
79 *
80 * It also keeps a set of {@link android.app.trust.ITrustListener}s that are notified whenever the
81 * trust state changes for any user.
82 *
83 * Trust state and the setting of enabled agents is kept per user and each user has its own
84 * instance of a {@link android.service.trust.TrustAgentService}.
85 */
86public class TrustManagerService extends SystemService {
87
88    private static final boolean DEBUG = false;
89    private static final String TAG = "TrustManagerService";
90
91    private static final Intent TRUST_AGENT_INTENT =
92            new Intent(TrustAgentService.SERVICE_INTERFACE);
93    private static final String PERMISSION_PROVIDE_AGENT = Manifest.permission.PROVIDE_TRUST_AGENT;
94
95    private static final int MSG_REGISTER_LISTENER = 1;
96    private static final int MSG_UNREGISTER_LISTENER = 2;
97    private static final int MSG_DISPATCH_UNLOCK_ATTEMPT = 3;
98    private static final int MSG_ENABLED_AGENTS_CHANGED = 4;
99    private static final int MSG_REQUIRE_CREDENTIAL_ENTRY = 5;
100    private static final int MSG_KEYGUARD_SHOWING_CHANGED = 6;
101    private static final int MSG_START_USER = 7;
102    private static final int MSG_CLEANUP_USER = 8;
103    private static final int MSG_SWITCH_USER = 9;
104
105    private final ArraySet<AgentInfo> mActiveAgents = new ArraySet<AgentInfo>();
106    private final ArrayList<ITrustListener> mTrustListeners = new ArrayList<ITrustListener>();
107    private final Receiver mReceiver = new Receiver();
108    private final SparseBooleanArray mUserHasAuthenticated = new SparseBooleanArray();
109    /* package */ final TrustArchive mArchive = new TrustArchive();
110    private final Context mContext;
111    private final LockPatternUtils mLockPatternUtils;
112    private final UserManager mUserManager;
113    private final ActivityManager mActivityManager;
114
115    @GuardedBy("mUserIsTrusted")
116    private final SparseBooleanArray mUserIsTrusted = new SparseBooleanArray();
117
118    @GuardedBy("mDeviceLockedForUser")
119    private final SparseBooleanArray mDeviceLockedForUser = new SparseBooleanArray();
120
121    @GuardedBy("mUserHasAuthenticatedSinceBoot")
122    private final SparseBooleanArray mUserHasAuthenticatedSinceBoot = new SparseBooleanArray();
123
124    private boolean mTrustAgentsCanRun = false;
125    private int mCurrentUser = UserHandle.USER_OWNER;
126
127    public TrustManagerService(Context context) {
128        super(context);
129        mContext = context;
130        mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
131        mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
132        mLockPatternUtils = new LockPatternUtils(context);
133    }
134
135    @Override
136    public void onStart() {
137        publishBinderService(Context.TRUST_SERVICE, mService);
138    }
139
140    @Override
141    public void onBootPhase(int phase) {
142        if (isSafeMode()) {
143            // No trust agents in safe mode.
144            return;
145        }
146        if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
147            mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
148            mReceiver.register(mContext);
149        } else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
150            mTrustAgentsCanRun = true;
151            refreshAgentList(UserHandle.USER_ALL);
152        } else if (phase == SystemService.PHASE_BOOT_COMPLETED) {
153            maybeEnableFactoryTrustAgents(mLockPatternUtils, UserHandle.USER_OWNER);
154        }
155    }
156
157    // Agent management
158
159    private static final class AgentInfo {
160        CharSequence label;
161        Drawable icon;
162        ComponentName component; // service that implements ITrustAgent
163        ComponentName settings; // setting to launch to modify agent.
164        TrustAgentWrapper agent;
165        int userId;
166
167        @Override
168        public boolean equals(Object other) {
169            if (!(other instanceof AgentInfo)) {
170                return false;
171            }
172            AgentInfo o = (AgentInfo) other;
173            return component.equals(o.component) && userId == o.userId;
174        }
175
176        @Override
177        public int hashCode() {
178            return component.hashCode() * 31 + userId;
179        }
180    }
181
182    private void updateTrustAll() {
183        List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
184        for (UserInfo userInfo : userInfos) {
185            updateTrust(userInfo.id, 0);
186        }
187    }
188
189    public void updateTrust(int userId, int flags) {
190        dispatchOnTrustManagedChanged(aggregateIsTrustManaged(userId), userId);
191        boolean trusted = aggregateIsTrusted(userId);
192        boolean changed;
193        synchronized (mUserIsTrusted) {
194            changed = mUserIsTrusted.get(userId) != trusted;
195            mUserIsTrusted.put(userId, trusted);
196        }
197        dispatchOnTrustChanged(trusted, userId, flags);
198        if (changed) {
199            refreshDeviceLockedForUser(userId);
200        }
201    }
202
203    void refreshAgentList(int userId) {
204        if (DEBUG) Slog.d(TAG, "refreshAgentList()");
205        if (!mTrustAgentsCanRun) {
206            return;
207        }
208        if (userId != UserHandle.USER_ALL && userId < UserHandle.USER_OWNER) {
209            Log.e(TAG, "refreshAgentList(userId=" + userId + "): Invalid user handle,"
210                    + " must be USER_ALL or a specific user.", new Throwable("here"));
211            userId = UserHandle.USER_ALL;
212        }
213        PackageManager pm = mContext.getPackageManager();
214
215        List<UserInfo> userInfos;
216        if (userId == UserHandle.USER_ALL) {
217            userInfos = mUserManager.getUsers(true /* excludeDying */);
218        } else {
219            userInfos = new ArrayList<>();
220            userInfos.add(mUserManager.getUserInfo(userId));
221        }
222        LockPatternUtils lockPatternUtils = mLockPatternUtils;
223
224        ArraySet<AgentInfo> obsoleteAgents = new ArraySet<>();
225        obsoleteAgents.addAll(mActiveAgents);
226
227        for (UserInfo userInfo : userInfos) {
228            if (userInfo == null || userInfo.partial || !userInfo.isEnabled()
229                    || userInfo.guestToRemove) continue;
230            if (!userInfo.supportsSwitchTo()) continue;
231            if (!mActivityManager.isUserRunning(userInfo.id)) continue;
232            if (!lockPatternUtils.isSecure(userInfo.id)) continue;
233            if (!getUserHasAuthenticated(userInfo.id)) continue;
234            DevicePolicyManager dpm = lockPatternUtils.getDevicePolicyManager();
235            int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, userInfo.id);
236            final boolean disableTrustAgents =
237                    (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_TRUST_AGENTS) != 0;
238
239            List<ComponentName> enabledAgents = lockPatternUtils.getEnabledTrustAgents(userInfo.id);
240            if (enabledAgents == null) {
241                continue;
242            }
243            List<ResolveInfo> resolveInfos = resolveAllowedTrustAgents(pm, userInfo.id);
244            for (ResolveInfo resolveInfo : resolveInfos) {
245                ComponentName name = getComponentName(resolveInfo);
246
247                if (!enabledAgents.contains(name)) continue;
248                if (disableTrustAgents) {
249                    List<PersistableBundle> config =
250                            dpm.getTrustAgentConfiguration(null /* admin */, name, userInfo.id);
251                    // Disable agent if no features are enabled.
252                    if (config == null || config.isEmpty()) continue;
253                }
254
255                AgentInfo agentInfo = new AgentInfo();
256                agentInfo.component = name;
257                agentInfo.userId = userInfo.id;
258                if (!mActiveAgents.contains(agentInfo)) {
259                    agentInfo.label = resolveInfo.loadLabel(pm);
260                    agentInfo.icon = resolveInfo.loadIcon(pm);
261                    agentInfo.settings = getSettingsComponentName(pm, resolveInfo);
262                    agentInfo.agent = new TrustAgentWrapper(mContext, this,
263                            new Intent().setComponent(name), userInfo.getUserHandle());
264                    mActiveAgents.add(agentInfo);
265                } else {
266                    obsoleteAgents.remove(agentInfo);
267                }
268            }
269        }
270
271        boolean trustMayHaveChanged = false;
272        for (int i = 0; i < obsoleteAgents.size(); i++) {
273            AgentInfo info = obsoleteAgents.valueAt(i);
274            if (userId == UserHandle.USER_ALL || userId == info.userId) {
275                if (info.agent.isManagingTrust()) {
276                    trustMayHaveChanged = true;
277                }
278                info.agent.destroy();
279                mActiveAgents.remove(info);
280            }
281        }
282
283        if (trustMayHaveChanged) {
284            if (userId == UserHandle.USER_ALL) {
285                updateTrustAll();
286            } else {
287                updateTrust(userId, 0);
288            }
289        }
290    }
291
292    boolean isDeviceLockedInner(int userId) {
293        synchronized (mDeviceLockedForUser) {
294            return mDeviceLockedForUser.get(userId, true);
295        }
296    }
297
298    private void refreshDeviceLockedForUser(int userId) {
299        if (userId != UserHandle.USER_ALL && userId < UserHandle.USER_OWNER) {
300            Log.e(TAG, "refreshDeviceLockedForUser(userId=" + userId + "): Invalid user handle,"
301                    + " must be USER_ALL or a specific user.", new Throwable("here"));
302            userId = UserHandle.USER_ALL;
303        }
304
305        List<UserInfo> userInfos;
306        if (userId == UserHandle.USER_ALL) {
307            userInfos = mUserManager.getUsers(true /* excludeDying */);
308        } else {
309            userInfos = new ArrayList<>();
310            userInfos.add(mUserManager.getUserInfo(userId));
311        }
312
313        IWindowManager wm = WindowManagerGlobal.getWindowManagerService();
314
315        for (int i = 0; i < userInfos.size(); i++) {
316            UserInfo info = userInfos.get(i);
317
318            if (info == null || info.partial || !info.isEnabled() || info.guestToRemove
319                    || !info.supportsSwitchTo()) {
320                continue;
321            }
322
323            int id = info.id;
324            boolean secure = mLockPatternUtils.isSecure(id);
325            boolean trusted = aggregateIsTrusted(id);
326            boolean showingKeyguard = true;
327            if (mCurrentUser == id) {
328                try {
329                    showingKeyguard = wm.isKeyguardLocked();
330                } catch (RemoteException e) {
331                }
332            }
333            boolean deviceLocked = secure && showingKeyguard && !trusted;
334
335            boolean changed;
336            synchronized (mDeviceLockedForUser) {
337                changed = isDeviceLockedInner(id) != deviceLocked;
338                mDeviceLockedForUser.put(id, deviceLocked);
339            }
340            if (changed) {
341                dispatchDeviceLocked(id, deviceLocked);
342            }
343        }
344    }
345
346    private void dispatchDeviceLocked(int userId, boolean isLocked) {
347        for (int i = 0; i < mActiveAgents.size(); i++) {
348            AgentInfo agent = mActiveAgents.valueAt(i);
349            if (agent.userId == userId) {
350                if (isLocked) {
351                    agent.agent.onDeviceLocked();
352                } else{
353                    agent.agent.onDeviceUnlocked();
354                }
355            }
356        }
357    }
358
359    void updateDevicePolicyFeatures() {
360        for (int i = 0; i < mActiveAgents.size(); i++) {
361            AgentInfo info = mActiveAgents.valueAt(i);
362            if (info.agent.isConnected()) {
363                info.agent.updateDevicePolicyFeatures();
364            }
365        }
366    }
367
368    private void removeAgentsOfPackage(String packageName) {
369        boolean trustMayHaveChanged = false;
370        for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
371            AgentInfo info = mActiveAgents.valueAt(i);
372            if (packageName.equals(info.component.getPackageName())) {
373                Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
374                if (info.agent.isManagingTrust()) {
375                    trustMayHaveChanged = true;
376                }
377                info.agent.destroy();
378                mActiveAgents.removeAt(i);
379            }
380        }
381        if (trustMayHaveChanged) {
382            updateTrustAll();
383        }
384    }
385
386    public void resetAgent(ComponentName name, int userId) {
387        boolean trustMayHaveChanged = false;
388        for (int i = mActiveAgents.size() - 1; i >= 0; i--) {
389            AgentInfo info = mActiveAgents.valueAt(i);
390            if (name.equals(info.component) && userId == info.userId) {
391                Log.i(TAG, "Resetting agent " + info.component.flattenToShortString());
392                if (info.agent.isManagingTrust()) {
393                    trustMayHaveChanged = true;
394                }
395                info.agent.destroy();
396                mActiveAgents.removeAt(i);
397            }
398        }
399        if (trustMayHaveChanged) {
400            updateTrust(userId, 0);
401        }
402        refreshAgentList(userId);
403    }
404
405    private ComponentName getSettingsComponentName(PackageManager pm, ResolveInfo resolveInfo) {
406        if (resolveInfo == null || resolveInfo.serviceInfo == null
407                || resolveInfo.serviceInfo.metaData == null) return null;
408        String cn = null;
409        XmlResourceParser parser = null;
410        Exception caughtException = null;
411        try {
412            parser = resolveInfo.serviceInfo.loadXmlMetaData(pm,
413                    TrustAgentService.TRUST_AGENT_META_DATA);
414            if (parser == null) {
415                Slog.w(TAG, "Can't find " + TrustAgentService.TRUST_AGENT_META_DATA + " meta-data");
416                return null;
417            }
418            Resources res = pm.getResourcesForApplication(resolveInfo.serviceInfo.applicationInfo);
419            AttributeSet attrs = Xml.asAttributeSet(parser);
420            int type;
421            while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
422                    && type != XmlPullParser.START_TAG) {
423                // Drain preamble.
424            }
425            String nodeName = parser.getName();
426            if (!"trust-agent".equals(nodeName)) {
427                Slog.w(TAG, "Meta-data does not start with trust-agent tag");
428                return null;
429            }
430            TypedArray sa = res
431                    .obtainAttributes(attrs, com.android.internal.R.styleable.TrustAgent);
432            cn = sa.getString(com.android.internal.R.styleable.TrustAgent_settingsActivity);
433            sa.recycle();
434        } catch (PackageManager.NameNotFoundException e) {
435            caughtException = e;
436        } catch (IOException e) {
437            caughtException = e;
438        } catch (XmlPullParserException e) {
439            caughtException = e;
440        } finally {
441            if (parser != null) parser.close();
442        }
443        if (caughtException != null) {
444            Slog.w(TAG, "Error parsing : " + resolveInfo.serviceInfo.packageName, caughtException);
445            return null;
446        }
447        if (cn == null) {
448            return null;
449        }
450        if (cn.indexOf('/') < 0) {
451            cn = resolveInfo.serviceInfo.packageName + "/" + cn;
452        }
453        return ComponentName.unflattenFromString(cn);
454    }
455
456    private ComponentName getComponentName(ResolveInfo resolveInfo) {
457        if (resolveInfo == null || resolveInfo.serviceInfo == null) return null;
458        return new ComponentName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name);
459    }
460
461    private void maybeEnableFactoryTrustAgents(LockPatternUtils utils, int userId) {
462        if (0 != Settings.Secure.getIntForUser(mContext.getContentResolver(),
463                Settings.Secure.TRUST_AGENTS_INITIALIZED, 0, userId)) {
464            return;
465        }
466        PackageManager pm = mContext.getPackageManager();
467        List<ResolveInfo> resolveInfos = resolveAllowedTrustAgents(pm, userId);
468        ArraySet<ComponentName> discoveredAgents = new ArraySet<>();
469        for (ResolveInfo resolveInfo : resolveInfos) {
470            ComponentName componentName = getComponentName(resolveInfo);
471            int applicationInfoFlags = resolveInfo.serviceInfo.applicationInfo.flags;
472            if ((applicationInfoFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
473                Log.i(TAG, "Leaving agent " + componentName + " disabled because package "
474                        + "is not a system package.");
475                continue;
476            }
477            discoveredAgents.add(componentName);
478        }
479
480        List<ComponentName> previouslyEnabledAgents = utils.getEnabledTrustAgents(userId);
481        if (previouslyEnabledAgents != null) {
482            discoveredAgents.addAll(previouslyEnabledAgents);
483        }
484        utils.setEnabledTrustAgents(discoveredAgents, userId);
485        Settings.Secure.putIntForUser(mContext.getContentResolver(),
486                Settings.Secure.TRUST_AGENTS_INITIALIZED, 1, userId);
487    }
488
489    private List<ResolveInfo> resolveAllowedTrustAgents(PackageManager pm, int userId) {
490        List<ResolveInfo> resolveInfos = pm.queryIntentServicesAsUser(TRUST_AGENT_INTENT,
491                0 /* flags */, userId);
492        ArrayList<ResolveInfo> allowedAgents = new ArrayList<>(resolveInfos.size());
493        for (ResolveInfo resolveInfo : resolveInfos) {
494            if (resolveInfo.serviceInfo == null) continue;
495            if (resolveInfo.serviceInfo.applicationInfo == null) continue;
496            String packageName = resolveInfo.serviceInfo.packageName;
497            if (pm.checkPermission(PERMISSION_PROVIDE_AGENT, packageName)
498                    != PackageManager.PERMISSION_GRANTED) {
499                ComponentName name = getComponentName(resolveInfo);
500                Log.w(TAG, "Skipping agent " + name + " because package does not have"
501                        + " permission " + PERMISSION_PROVIDE_AGENT + ".");
502                continue;
503            }
504            allowedAgents.add(resolveInfo);
505        }
506        return allowedAgents;
507    }
508
509    // Agent dispatch and aggregation
510
511    private boolean aggregateIsTrusted(int userId) {
512        if (!getUserHasAuthenticated(userId)) {
513            return false;
514        }
515        for (int i = 0; i < mActiveAgents.size(); i++) {
516            AgentInfo info = mActiveAgents.valueAt(i);
517            if (info.userId == userId) {
518                if (info.agent.isTrusted()) {
519                    return true;
520                }
521            }
522        }
523        return false;
524    }
525
526    private boolean aggregateIsTrustManaged(int userId) {
527        if (!getUserHasAuthenticated(userId)) {
528            return false;
529        }
530        for (int i = 0; i < mActiveAgents.size(); i++) {
531            AgentInfo info = mActiveAgents.valueAt(i);
532            if (info.userId == userId) {
533                if (info.agent.isManagingTrust()) {
534                    return true;
535                }
536            }
537        }
538        return false;
539    }
540
541    private void dispatchUnlockAttempt(boolean successful, int userId) {
542        for (int i = 0; i < mActiveAgents.size(); i++) {
543            AgentInfo info = mActiveAgents.valueAt(i);
544            if (info.userId == userId) {
545                info.agent.onUnlockAttempt(successful);
546            }
547        }
548
549        if (successful) {
550            updateUserHasAuthenticated(userId);
551        }
552    }
553
554    private void updateUserHasAuthenticated(int userId) {
555        boolean changed = setUserHasAuthenticated(userId);
556        if (changed) {
557            refreshAgentList(userId);
558        }
559    }
560
561    private boolean getUserHasAuthenticated(int userId) {
562        return mUserHasAuthenticated.get(userId);
563    }
564
565    /**
566     * @return whether the value has changed
567     */
568    private boolean setUserHasAuthenticated(int userId) {
569        if (!mUserHasAuthenticated.get(userId)) {
570            mUserHasAuthenticated.put(userId, true);
571            synchronized (mUserHasAuthenticatedSinceBoot) {
572                mUserHasAuthenticatedSinceBoot.put(userId, true);
573            }
574            return true;
575        }
576        return false;
577    }
578
579    private void clearUserHasAuthenticated(int userId) {
580        if (userId == UserHandle.USER_ALL) {
581            mUserHasAuthenticated.clear();
582            synchronized (mUserHasAuthenticatedSinceBoot) {
583                mUserHasAuthenticatedSinceBoot.clear();
584            }
585        } else {
586            mUserHasAuthenticated.put(userId, false);
587            synchronized (mUserHasAuthenticatedSinceBoot) {
588                mUserHasAuthenticatedSinceBoot.put(userId, false);
589            }
590        }
591    }
592
593    private boolean getUserHasAuthenticatedSinceBoot(int userId) {
594        synchronized (mUserHasAuthenticatedSinceBoot) {
595            return mUserHasAuthenticatedSinceBoot.get(userId);
596        }
597    }
598
599    private void requireCredentialEntry(int userId) {
600        clearUserHasAuthenticated(userId);
601        refreshAgentList(userId);
602    }
603
604    // Listeners
605
606    private void addListener(ITrustListener listener) {
607        for (int i = 0; i < mTrustListeners.size(); i++) {
608            if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
609                return;
610            }
611        }
612        mTrustListeners.add(listener);
613        updateTrustAll();
614    }
615
616    private void removeListener(ITrustListener listener) {
617        for (int i = 0; i < mTrustListeners.size(); i++) {
618            if (mTrustListeners.get(i).asBinder() == listener.asBinder()) {
619                mTrustListeners.remove(i);
620                return;
621            }
622        }
623    }
624
625    private void dispatchOnTrustChanged(boolean enabled, int userId, int flags) {
626        if (!enabled) flags = 0;
627        for (int i = 0; i < mTrustListeners.size(); i++) {
628            try {
629                mTrustListeners.get(i).onTrustChanged(enabled, userId, flags);
630            } catch (DeadObjectException e) {
631                Slog.d(TAG, "Removing dead TrustListener.");
632                mTrustListeners.remove(i);
633                i--;
634            } catch (RemoteException e) {
635                Slog.e(TAG, "Exception while notifying TrustListener.", e);
636            }
637        }
638    }
639
640    private void dispatchOnTrustManagedChanged(boolean managed, int userId) {
641        for (int i = 0; i < mTrustListeners.size(); i++) {
642            try {
643                mTrustListeners.get(i).onTrustManagedChanged(managed, userId);
644            } catch (DeadObjectException e) {
645                Slog.d(TAG, "Removing dead TrustListener.");
646                mTrustListeners.remove(i);
647                i--;
648            } catch (RemoteException e) {
649                Slog.e(TAG, "Exception while notifying TrustListener.", e);
650            }
651        }
652    }
653
654    // User lifecycle
655
656    @Override
657    public void onStartUser(int userId) {
658        mHandler.obtainMessage(MSG_START_USER, userId, 0, null).sendToTarget();
659    }
660
661    @Override
662    public void onCleanupUser(int userId) {
663        mHandler.obtainMessage(MSG_CLEANUP_USER, userId, 0, null).sendToTarget();
664    }
665
666    @Override
667    public void onSwitchUser(int userId) {
668        mHandler.obtainMessage(MSG_SWITCH_USER, userId, 0, null).sendToTarget();
669    }
670
671    // Plumbing
672
673    private final IBinder mService = new ITrustManager.Stub() {
674        @Override
675        public void reportUnlockAttempt(boolean authenticated, int userId) throws RemoteException {
676            enforceReportPermission();
677            mHandler.obtainMessage(MSG_DISPATCH_UNLOCK_ATTEMPT, authenticated ? 1 : 0, userId)
678                    .sendToTarget();
679        }
680
681        @Override
682        public void reportEnabledTrustAgentsChanged(int userId) throws RemoteException {
683            enforceReportPermission();
684            // coalesce refresh messages.
685            mHandler.removeMessages(MSG_ENABLED_AGENTS_CHANGED);
686            mHandler.sendEmptyMessage(MSG_ENABLED_AGENTS_CHANGED);
687        }
688
689        @Override
690        public void reportRequireCredentialEntry(int userId) throws RemoteException {
691            enforceReportPermission();
692            if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_OWNER) {
693                mHandler.obtainMessage(MSG_REQUIRE_CREDENTIAL_ENTRY, userId, 0).sendToTarget();
694            } else {
695                throw new IllegalArgumentException(
696                        "userId must be an explicit user id or USER_ALL");
697            }
698        }
699
700        @Override
701        public void reportKeyguardShowingChanged() throws RemoteException {
702            enforceReportPermission();
703            // coalesce refresh messages.
704            mHandler.removeMessages(MSG_KEYGUARD_SHOWING_CHANGED);
705            mHandler.sendEmptyMessage(MSG_KEYGUARD_SHOWING_CHANGED);
706        }
707
708        @Override
709        public void registerTrustListener(ITrustListener trustListener) throws RemoteException {
710            enforceListenerPermission();
711            mHandler.obtainMessage(MSG_REGISTER_LISTENER, trustListener).sendToTarget();
712        }
713
714        @Override
715        public void unregisterTrustListener(ITrustListener trustListener) throws RemoteException {
716            enforceListenerPermission();
717            mHandler.obtainMessage(MSG_UNREGISTER_LISTENER, trustListener).sendToTarget();
718        }
719
720        @Override
721        public boolean isDeviceLocked(int userId) throws RemoteException {
722            userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId,
723                    false /* allowAll */, true /* requireFull */, "isDeviceLocked", null);
724            userId = resolveProfileParent(userId);
725
726            return isDeviceLockedInner(userId);
727        }
728
729        @Override
730        public boolean isDeviceSecure(int userId) throws RemoteException {
731            userId = ActivityManager.handleIncomingUser(getCallingPid(), getCallingUid(), userId,
732                    false /* allowAll */, true /* requireFull */, "isDeviceSecure", null);
733            userId = resolveProfileParent(userId);
734
735            long token = Binder.clearCallingIdentity();
736            try {
737                return new LockPatternUtils(mContext).isSecure(userId);
738            } finally {
739                Binder.restoreCallingIdentity(token);
740            }
741        }
742
743        @Override
744        public boolean hasUserAuthenticatedSinceBoot(int userId) throws RemoteException {
745            mContext.enforceCallingOrSelfPermission(
746                    Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, null);
747            long token = Binder.clearCallingIdentity();
748            try {
749                return getUserHasAuthenticatedSinceBoot(userId);
750            } finally {
751                Binder.restoreCallingIdentity(token);
752            }
753        }
754
755        private void enforceReportPermission() {
756            mContext.enforceCallingOrSelfPermission(
757                    Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE, "reporting trust events");
758        }
759
760        private void enforceListenerPermission() {
761            mContext.enforceCallingPermission(Manifest.permission.TRUST_LISTENER,
762                    "register trust listener");
763        }
764
765        @Override
766        protected void dump(FileDescriptor fd, final PrintWriter fout, String[] args) {
767            mContext.enforceCallingPermission(Manifest.permission.DUMP,
768                    "dumping TrustManagerService");
769            if (isSafeMode()) {
770                fout.println("disabled because the system is in safe mode.");
771                return;
772            }
773            if (!mTrustAgentsCanRun) {
774                fout.println("disabled because the third-party apps can't run yet.");
775                return;
776            }
777            final List<UserInfo> userInfos = mUserManager.getUsers(true /* excludeDying */);
778            mHandler.runWithScissors(new Runnable() {
779                @Override
780                public void run() {
781                    fout.println("Trust manager state:");
782                    for (UserInfo user : userInfos) {
783                        dumpUser(fout, user, user.id == mCurrentUser);
784                    }
785                }
786            }, 1500);
787        }
788
789        private void dumpUser(PrintWriter fout, UserInfo user, boolean isCurrent) {
790            fout.printf(" User \"%s\" (id=%d, flags=%#x)",
791                    user.name, user.id, user.flags);
792            if (!user.supportsSwitchTo()) {
793                fout.println("(managed profile)");
794                fout.println("   disabled because switching to this user is not possible.");
795                return;
796            }
797            if (isCurrent) {
798                fout.print(" (current)");
799            }
800            fout.print(": trusted=" + dumpBool(aggregateIsTrusted(user.id)));
801            fout.print(", trustManaged=" + dumpBool(aggregateIsTrustManaged(user.id)));
802            fout.print(", deviceLocked=" + dumpBool(isDeviceLockedInner(user.id)));
803            fout.print(", hasAuthenticated=" + dumpBool(getUserHasAuthenticated(user.id)));
804            fout.print(", hasAuthenticatedSinceBoot="
805                    + dumpBool(getUserHasAuthenticatedSinceBoot(user.id)));
806            fout.println();
807            fout.println("   Enabled agents:");
808            boolean duplicateSimpleNames = false;
809            ArraySet<String> simpleNames = new ArraySet<String>();
810            for (AgentInfo info : mActiveAgents) {
811                if (info.userId != user.id) { continue; }
812                boolean trusted = info.agent.isTrusted();
813                fout.print("    "); fout.println(info.component.flattenToShortString());
814                fout.print("     bound=" + dumpBool(info.agent.isBound()));
815                fout.print(", connected=" + dumpBool(info.agent.isConnected()));
816                fout.print(", managingTrust=" + dumpBool(info.agent.isManagingTrust()));
817                fout.print(", trusted=" + dumpBool(trusted));
818                fout.println();
819                if (trusted) {
820                    fout.println("      message=\"" + info.agent.getMessage() + "\"");
821                }
822                if (!info.agent.isConnected()) {
823                    String restartTime = TrustArchive.formatDuration(
824                            info.agent.getScheduledRestartUptimeMillis()
825                                    - SystemClock.uptimeMillis());
826                    fout.println("      restartScheduledAt=" + restartTime);
827                }
828                if (!simpleNames.add(TrustArchive.getSimpleName(info.component))) {
829                    duplicateSimpleNames = true;
830                }
831            }
832            fout.println("   Events:");
833            mArchive.dump(fout, 50, user.id, "    " /* linePrefix */, duplicateSimpleNames);
834            fout.println();
835        }
836
837        private String dumpBool(boolean b) {
838            return b ? "1" : "0";
839        }
840    };
841
842    private int resolveProfileParent(int userId) {
843        long identity = Binder.clearCallingIdentity();
844        try {
845            UserInfo parent = mUserManager.getProfileParent(userId);
846            if (parent != null) {
847                return parent.getUserHandle().getIdentifier();
848            }
849            return userId;
850        } finally {
851            Binder.restoreCallingIdentity(identity);
852        }
853    }
854
855    private final Handler mHandler = new Handler() {
856        @Override
857        public void handleMessage(Message msg) {
858            switch (msg.what) {
859                case MSG_REGISTER_LISTENER:
860                    addListener((ITrustListener) msg.obj);
861                    break;
862                case MSG_UNREGISTER_LISTENER:
863                    removeListener((ITrustListener) msg.obj);
864                    break;
865                case MSG_DISPATCH_UNLOCK_ATTEMPT:
866                    dispatchUnlockAttempt(msg.arg1 != 0, msg.arg2);
867                    break;
868                case MSG_ENABLED_AGENTS_CHANGED:
869                    refreshAgentList(UserHandle.USER_ALL);
870                    // This is also called when the security mode of a user changes.
871                    refreshDeviceLockedForUser(UserHandle.USER_ALL);
872                    break;
873                case MSG_REQUIRE_CREDENTIAL_ENTRY:
874                    requireCredentialEntry(msg.arg1);
875                    break;
876                case MSG_KEYGUARD_SHOWING_CHANGED:
877                    refreshDeviceLockedForUser(mCurrentUser);
878                    break;
879                case MSG_START_USER:
880                case MSG_CLEANUP_USER:
881                    refreshAgentList(msg.arg1);
882                    break;
883                case MSG_SWITCH_USER:
884                    mCurrentUser = msg.arg1;
885                    refreshDeviceLockedForUser(UserHandle.USER_ALL);
886                    break;
887            }
888        }
889    };
890
891    private final PackageMonitor mPackageMonitor = new PackageMonitor() {
892        @Override
893        public void onSomePackagesChanged() {
894            refreshAgentList(UserHandle.USER_ALL);
895        }
896
897        @Override
898        public boolean onPackageChanged(String packageName, int uid, String[] components) {
899            // We're interested in all changes, even if just some components get enabled / disabled.
900            return true;
901        }
902
903        @Override
904        public void onPackageDisappeared(String packageName, int reason) {
905            removeAgentsOfPackage(packageName);
906        }
907    };
908
909    private class Receiver extends BroadcastReceiver {
910
911        @Override
912        public void onReceive(Context context, Intent intent) {
913            String action = intent.getAction();
914            if (DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED.equals(action)) {
915                refreshAgentList(getSendingUserId());
916                updateDevicePolicyFeatures();
917            } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
918                updateUserHasAuthenticated(getSendingUserId());
919            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
920                int userId = getUserId(intent);
921                if (userId > 0) {
922                    maybeEnableFactoryTrustAgents(mLockPatternUtils, userId);
923                }
924            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
925                int userId = getUserId(intent);
926                if (userId > 0) {
927                    mUserHasAuthenticated.delete(userId);
928                    synchronized (mUserIsTrusted) {
929                        mUserIsTrusted.delete(userId);
930                    }
931                    synchronized (mDeviceLockedForUser) {
932                        mDeviceLockedForUser.delete(userId);
933                    }
934                    refreshAgentList(userId);
935                    refreshDeviceLockedForUser(userId);
936                }
937            }
938        }
939
940        private int getUserId(Intent intent) {
941            int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -100);
942            if (userId > 0) {
943                return userId;
944            } else {
945                Slog.wtf(TAG, "EXTRA_USER_HANDLE missing or invalid, value=" + userId);
946                return -100;
947            }
948        }
949
950        public void register(Context context) {
951            IntentFilter filter = new IntentFilter();
952            filter.addAction(DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED);
953            filter.addAction(Intent.ACTION_USER_PRESENT);
954            filter.addAction(Intent.ACTION_USER_ADDED);
955            filter.addAction(Intent.ACTION_USER_REMOVED);
956            context.registerReceiverAsUser(this,
957                    UserHandle.ALL,
958                    filter,
959                    null /* permission */,
960                    null /* scheduler */);
961        }
962    }
963}
964