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