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 
17 package android.app.trust;
18 
19 import android.Manifest;
20 import android.annotation.RequiresPermission;
21 import android.annotation.SystemService;
22 import android.compat.annotation.UnsupportedAppUsage;
23 import android.content.Context;
24 import android.hardware.biometrics.BiometricSourceType;
25 import android.os.Bundle;
26 import android.os.Handler;
27 import android.os.IBinder;
28 import android.os.Looper;
29 import android.os.Message;
30 import android.os.RemoteException;
31 import android.util.ArrayMap;
32 
33 import java.util.ArrayList;
34 import java.util.List;
35 
36 /**
37  * See {@link com.android.server.trust.TrustManagerService}
38  * @hide
39  */
40 @SystemService(Context.TRUST_SERVICE)
41 public class TrustManager {
42 
43     private static final int MSG_TRUST_CHANGED = 1;
44     private static final int MSG_TRUST_MANAGED_CHANGED = 2;
45     private static final int MSG_TRUST_ERROR = 3;
46     private static final int MSG_ENABLED_TRUST_AGENTS_CHANGED = 4;
47     private static final int MSG_IS_ACTIVE_UNLOCK_RUNNING = 5;
48 
49     private static final String TAG = "TrustManager";
50     private static final String DATA_FLAGS = "initiatedByUser";
51     private static final String DATA_NEWLY_UNLOCKED = "newlyUnlocked";
52     private static final String DATA_MESSAGE = "message";
53     private static final String DATA_GRANTED_MESSAGES = "grantedMessages";
54 
55     private final ITrustManager mService;
56     private final ArrayMap<TrustListener, ITrustListener> mTrustListeners;
57 
TrustManager(IBinder b)58     public TrustManager(IBinder b) {
59         mService = ITrustManager.Stub.asInterface(b);
60         mTrustListeners = new ArrayMap<TrustListener, ITrustListener>();
61     }
62 
63     /**
64      * Changes the lock status for the given user. This is only applicable to Managed Profiles,
65      * other users should be handled by Keyguard.
66      *
67      * @param userId The id for the user to be locked/unlocked.
68      * @param locked The value for that user's locked state.
69      */
70     @RequiresPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE)
setDeviceLockedForUser(int userId, boolean locked)71     public void setDeviceLockedForUser(int userId, boolean locked) {
72         try {
73             mService.setDeviceLockedForUser(userId, locked);
74         } catch (RemoteException e) {
75             throw e.rethrowFromSystemServer();
76         }
77     }
78 
79     /**
80      * Reports that user {@param userId} has tried to unlock the device.
81      *
82      * @param successful if true, the unlock attempt was successful.
83      *
84      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
85      */
86     @UnsupportedAppUsage
reportUnlockAttempt(boolean successful, int userId)87     public void reportUnlockAttempt(boolean successful, int userId) {
88         try {
89             mService.reportUnlockAttempt(successful, userId);
90         } catch (RemoteException e) {
91             throw e.rethrowFromSystemServer();
92         }
93     }
94 
95     /**
96      * Reports that the user {@code userId} is likely interested in unlocking the device.
97      *
98      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
99      *
100      * @param dismissKeyguard whether the user wants to dismiss keyguard
101      */
reportUserRequestedUnlock(int userId, boolean dismissKeyguard)102     public void reportUserRequestedUnlock(int userId, boolean dismissKeyguard) {
103         try {
104             mService.reportUserRequestedUnlock(userId, dismissKeyguard);
105         } catch (RemoteException e) {
106             throw e.rethrowFromSystemServer();
107         }
108     }
109 
110     /**
111      * Reports that the user {@code userId} may want to unlock the device soon.
112      *
113      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
114      */
reportUserMayRequestUnlock(int userId)115     public void reportUserMayRequestUnlock(int userId) {
116         try {
117             mService.reportUserMayRequestUnlock(userId);
118         } catch (RemoteException e) {
119             throw e.rethrowFromSystemServer();
120         }
121     }
122 
123     /**
124      * Reports that user {@param userId} has entered a temporary device lockout.
125      *
126      * This generally occurs when  the user has unsuccessfully tried to unlock the device too many
127      * times. The user will then be unable to unlock the device until a set amount of time has
128      * elapsed.
129      *
130      * @param timeout The amount of time that needs to elapse, in milliseconds, until the user may
131      *    attempt to unlock the device again.
132      *
133      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
134      */
reportUnlockLockout(int timeoutMs, int userId)135     public void reportUnlockLockout(int timeoutMs, int userId) {
136         try {
137             mService.reportUnlockLockout(timeoutMs, userId);
138         } catch (RemoteException e) {
139             throw e.rethrowFromSystemServer();
140         }
141     }
142 
143     /**
144      * Reports that the list of enabled trust agents changed for user {@param userId}.
145      *
146      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
147      */
reportEnabledTrustAgentsChanged(int userId)148     public void reportEnabledTrustAgentsChanged(int userId) {
149         try {
150             mService.reportEnabledTrustAgentsChanged(userId);
151         } catch (RemoteException e) {
152             throw e.rethrowFromSystemServer();
153         }
154     }
155 
156     /**
157      * Reports that the visibility of the keyguard has changed.
158      *
159      * Requires the {@link android.Manifest.permission#ACCESS_KEYGUARD_SECURE_STORAGE} permission.
160      */
reportKeyguardShowingChanged()161     public void reportKeyguardShowingChanged() {
162         try {
163             mService.reportKeyguardShowingChanged();
164         } catch (RemoteException e) {
165             throw e.rethrowFromSystemServer();
166         }
167     }
168 
169     /**
170      * Returns whether active unlock can be used to unlock the device for user {@code userId}.
171      */
isActiveUnlockRunning(int userId)172     public boolean isActiveUnlockRunning(int userId) {
173         try {
174             return mService.isActiveUnlockRunning(userId);
175         } catch (RemoteException e) {
176             throw e.rethrowFromSystemServer();
177         }
178     }
179 
180     /**
181      * Registers a listener for trust events.
182      *
183      * Requires the {@link android.Manifest.permission#TRUST_LISTENER} permission.
184      */
registerTrustListener(final TrustListener trustListener)185     public void registerTrustListener(final TrustListener trustListener) {
186         try {
187             ITrustListener.Stub iTrustListener = new ITrustListener.Stub() {
188                 @Override
189                 public void onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId,
190                         int flags, List<String> trustGrantedMessages) {
191                     Message m = mHandler.obtainMessage(MSG_TRUST_CHANGED, (enabled ? 1 : 0), userId,
192                             trustListener);
193                     if (flags != 0) {
194                         m.getData().putInt(DATA_FLAGS, flags);
195                     }
196                     m.getData().putInt(DATA_NEWLY_UNLOCKED, newlyUnlocked ? 1 : 0);
197                     m.getData().putCharSequenceArrayList(
198                             DATA_GRANTED_MESSAGES, (ArrayList) trustGrantedMessages);
199                     m.sendToTarget();
200                 }
201 
202                 @Override
203                 public void onEnabledTrustAgentsChanged(int userId) {
204                     final Message m = mHandler.obtainMessage(MSG_ENABLED_TRUST_AGENTS_CHANGED,
205                             userId, 0, trustListener);
206                     m.sendToTarget();
207                 }
208 
209                 @Override
210                 public void onTrustManagedChanged(boolean managed, int userId) {
211                     mHandler.obtainMessage(MSG_TRUST_MANAGED_CHANGED, (managed ? 1 : 0), userId,
212                             trustListener).sendToTarget();
213                 }
214 
215                 @Override
216                 public void onTrustError(CharSequence message) {
217                     Message m = mHandler.obtainMessage(MSG_TRUST_ERROR, trustListener);
218                     m.getData().putCharSequence(DATA_MESSAGE, message);
219                     m.sendToTarget();
220                 }
221 
222                 @Override
223                 public void onIsActiveUnlockRunningChanged(boolean isRunning, int userId) {
224                     mHandler.obtainMessage(MSG_IS_ACTIVE_UNLOCK_RUNNING,
225                             (isRunning ? 1 : 0), userId, trustListener).sendToTarget();
226                 }
227             };
228             mService.registerTrustListener(iTrustListener);
229             mTrustListeners.put(trustListener, iTrustListener);
230         } catch (RemoteException e) {
231             throw e.rethrowFromSystemServer();
232         }
233     }
234 
235     /**
236      * Unregisters a listener for trust events.
237      *
238      * Requires the {@link android.Manifest.permission#TRUST_LISTENER} permission.
239      */
unregisterTrustListener(final TrustListener trustListener)240     public void unregisterTrustListener(final TrustListener trustListener) {
241         ITrustListener iTrustListener = mTrustListeners.remove(trustListener);
242         if (iTrustListener != null) {
243             try {
244                 mService.unregisterTrustListener(iTrustListener);
245             } catch (RemoteException e) {
246                 throw e.rethrowFromSystemServer();
247             }
248         }
249     }
250 
251     /**
252      * @return whether {@param userId} has enabled and configured trust agents. Ignores short-term
253      * unavailability of trust due to {@link LockPatternUtils.StrongAuthTracker}.
254      */
255     @RequiresPermission(android.Manifest.permission.TRUST_LISTENER)
isTrustUsuallyManaged(int userId)256     public boolean isTrustUsuallyManaged(int userId) {
257         try {
258             return mService.isTrustUsuallyManaged(userId);
259         } catch (RemoteException e) {
260             throw e.rethrowFromSystemServer();
261         }
262     }
263 
264     /**
265      * Updates the trust state for the user due to the user unlocking via a biometric sensor.
266      * Should only be called if user authenticated via fingerprint, face, or iris and bouncer
267      * can be skipped.
268      *
269      * @param userId
270      */
271     @RequiresPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE)
unlockedByBiometricForUser(int userId, BiometricSourceType source)272     public void unlockedByBiometricForUser(int userId, BiometricSourceType source) {
273         try {
274             mService.unlockedByBiometricForUser(userId, source);
275         } catch (RemoteException e) {
276             throw e.rethrowFromSystemServer();
277         }
278     }
279 
280     /**
281      * Clears authentication by the specified biometric type for all users.
282      */
283     @RequiresPermission(Manifest.permission.ACCESS_KEYGUARD_SECURE_STORAGE)
clearAllBiometricRecognized(BiometricSourceType source, int unlockedUser)284     public void clearAllBiometricRecognized(BiometricSourceType source, int unlockedUser) {
285         try {
286             mService.clearAllBiometricRecognized(source, unlockedUser);
287         } catch (RemoteException e) {
288             throw e.rethrowFromSystemServer();
289         }
290     }
291 
292     private final Handler mHandler = new Handler(Looper.getMainLooper()) {
293         @Override
294         public void handleMessage(Message msg) {
295             switch(msg.what) {
296                 case MSG_TRUST_CHANGED:
297                     Bundle data = msg.peekData();
298                     int flags = data != null ? data.getInt(DATA_FLAGS) : 0;
299                     boolean enabled = msg.arg1 != 0;
300                     int newlyUnlockedInt =
301                             data != null ? data.getInt(DATA_NEWLY_UNLOCKED) : 0;
302                     boolean newlyUnlocked = newlyUnlockedInt != 0;
303                     ((TrustListener) msg.obj).onTrustChanged(enabled, newlyUnlocked, msg.arg2,
304                             flags, msg.getData().getStringArrayList(DATA_GRANTED_MESSAGES));
305                     break;
306                 case MSG_TRUST_MANAGED_CHANGED:
307                     ((TrustListener)msg.obj).onTrustManagedChanged(msg.arg1 != 0, msg.arg2);
308                     break;
309                 case MSG_TRUST_ERROR:
310                     final CharSequence message = msg.peekData().getCharSequence(DATA_MESSAGE);
311                     ((TrustListener) msg.obj).onTrustError(message);
312                     break;
313                 case MSG_ENABLED_TRUST_AGENTS_CHANGED:
314                     ((TrustListener) msg.obj).onEnabledTrustAgentsChanged(msg.arg1);
315                     break;
316                 case MSG_IS_ACTIVE_UNLOCK_RUNNING:
317                     ((TrustListener) msg.obj)
318                             .onIsActiveUnlockRunningChanged(msg.arg1 != 0, msg.arg2);
319                     break;
320             }
321         }
322     };
323 
324     public interface TrustListener {
325 
326         /**
327          * Reports that the trust state has changed.
328          * @param enabled If true, the system believes the environment to be trusted.
329          * @param newlyUnlocked If true, the system believes the device is newly unlocked due
330          *        to the trust changing.
331          * @param userId The user, for which the trust changed.
332          * @param flags Flags specified by the trust agent when granting trust. See
333          *     {@link android.service.trust.TrustAgentService#grantTrust(CharSequence, long, int)
334          *                 TrustAgentService.grantTrust(CharSequence, long, int)}.
335          * @param trustGrantedMessages Messages to display to the user when trust has been granted
336          *        by one or more trust agents.
337          */
onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags, List<String> trustGrantedMessages)338         void onTrustChanged(boolean enabled, boolean newlyUnlocked, int userId, int flags,
339                 List<String> trustGrantedMessages);
340 
341         /**
342          * Reports that whether trust is managed has changed
343          * @param enabled If true, at least one trust agent is managing trust.
344          * @param userId The user, for which the state changed.
345          */
onTrustManagedChanged(boolean enabled, int userId)346         void onTrustManagedChanged(boolean enabled, int userId);
347 
348         /**
349          * Reports that an error happened on a TrustAgentService.
350          * @param message A message that should be displayed on the UI.
351          */
onTrustError(CharSequence message)352         void onTrustError(CharSequence message);
353 
354         /**
355          * Reports that the enabled trust agents for the specified user has changed.
356          */
onEnabledTrustAgentsChanged(int userId)357         void onEnabledTrustAgentsChanged(int userId);
358 
359         /**
360          * Reports changes on if the device can be unlocked with active unlock.
361          * @param isRunning If true, the device can be unlocked with active unlock.
362          * @param userId The user, for which the state changed.
363         */
onIsActiveUnlockRunningChanged(boolean isRunning, int userId)364         void onIsActiveUnlockRunningChanged(boolean isRunning, int userId);
365     }
366 }
367