TrustAgentService.java revision b1474f4432097cf20c06b471b57359ddd16fe460
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 android.service.trust; 18 19import android.Manifest; 20import android.annotation.SdkConstant; 21import android.annotation.SystemApi; 22import android.app.Service; 23import android.app.admin.DevicePolicyManager; 24import android.content.ComponentName; 25import android.content.Intent; 26import android.content.pm.PackageManager; 27import android.content.pm.ServiceInfo; 28import android.os.Bundle; 29import android.os.Handler; 30import android.os.IBinder; 31import android.os.Message; 32import android.os.RemoteException; 33import android.os.SystemClock; 34import android.util.Log; 35import android.util.Slog; 36 37/** 38 * A service that notifies the system about whether it believes the environment of the device 39 * to be trusted. 40 * 41 * <p>Trust agents may only be provided by the platform. It is expected that there is only 42 * one trust agent installed on the platform. In the event there is more than one, 43 * either trust agent can enable trust. 44 * </p> 45 * 46 * <p>To extend this class, you must declare the service in your manifest file with 47 * the {@link android.Manifest.permission#BIND_TRUST_AGENT} permission 48 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p> 49 * <pre> 50 * <service android:name=".TrustAgent" 51 * android:label="@string/service_name" 52 * android:permission="android.permission.BIND_TRUST_AGENT"> 53 * <intent-filter> 54 * <action android:name="android.service.trust.TrustAgentService" /> 55 * </intent-filter> 56 * <meta-data android:name="android.service.trust.trustagent" 57 * android:value="@xml/trust_agent" /> 58 * </service></pre> 59 * 60 * <p>The associated meta-data file can specify an activity that is accessible through Settings 61 * and should allow configuring the trust agent, as defined in 62 * {@link android.R.styleable#TrustAgent}. For example:</p> 63 * 64 * <pre> 65 * <trust-agent xmlns:android="http://schemas.android.com/apk/res/android" 66 * android:settingsActivity=".TrustAgentSettings" /></pre> 67 * 68 * @hide 69 */ 70@SystemApi 71public class TrustAgentService extends Service { 72 private final String TAG = TrustAgentService.class.getSimpleName() + 73 "[" + getClass().getSimpleName() + "]"; 74 private static final boolean DEBUG = false; 75 76 /** 77 * The {@link Intent} that must be declared as handled by the service. 78 */ 79 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 80 public static final String SERVICE_INTERFACE 81 = "android.service.trust.TrustAgentService"; 82 83 /** 84 * The name of the {@code meta-data} tag pointing to additional configuration of the trust 85 * agent. 86 */ 87 public static final String TRUST_AGENT_META_DATA = "android.service.trust.trustagent"; 88 89 /** 90 * A white list of features that the given trust agent should support when otherwise disabled 91 * by device policy. 92 * @hide 93 */ 94 public static final String KEY_FEATURES = "trust_agent_features"; 95 96 private static final int MSG_UNLOCK_ATTEMPT = 1; 97 private static final int MSG_SET_TRUST_AGENT_FEATURES_ENABLED = 2; 98 private static final int MSG_TRUST_TIMEOUT = 3; 99 100 private ITrustAgentServiceCallback mCallback; 101 102 private Runnable mPendingGrantTrustTask; 103 104 private boolean mManagingTrust; 105 106 // Lock used to access mPendingGrantTrustTask and mCallback. 107 private final Object mLock = new Object(); 108 109 private Handler mHandler = new Handler() { 110 public void handleMessage(android.os.Message msg) { 111 switch (msg.what) { 112 case MSG_UNLOCK_ATTEMPT: 113 onUnlockAttempt(msg.arg1 != 0); 114 break; 115 case MSG_SET_TRUST_AGENT_FEATURES_ENABLED: 116 Bundle features = msg.peekData(); 117 IBinder token = (IBinder) msg.obj; 118 boolean result = onSetTrustAgentFeaturesEnabled(features); 119 try { 120 synchronized (mLock) { 121 mCallback.onSetTrustAgentFeaturesEnabledCompleted(result, token); 122 } 123 } catch (RemoteException e) { 124 onError("calling onSetTrustAgentFeaturesEnabledCompleted()"); 125 } 126 break; 127 case MSG_TRUST_TIMEOUT: 128 onTrustTimeout(); 129 break; 130 } 131 } 132 }; 133 134 @Override 135 public void onCreate() { 136 super.onCreate(); 137 ComponentName component = new ComponentName(this, getClass()); 138 try { 139 ServiceInfo serviceInfo = getPackageManager().getServiceInfo(component, 0 /* flags */); 140 if (!Manifest.permission.BIND_TRUST_AGENT.equals(serviceInfo.permission)) { 141 throw new IllegalStateException(component.flattenToShortString() 142 + " is not declared with the permission " 143 + "\"" + Manifest.permission.BIND_TRUST_AGENT + "\""); 144 } 145 } catch (PackageManager.NameNotFoundException e) { 146 Log.e(TAG, "Can't get ServiceInfo for " + component.toShortString()); 147 } 148 } 149 150 /** 151 * Called after the user attempts to authenticate in keyguard with their device credentials, 152 * such as pin, pattern or password. 153 * 154 * @param successful true if the user successfully completed the challenge. 155 */ 156 public void onUnlockAttempt(boolean successful) { 157 } 158 159 /** 160 * Called when the timeout provided by the agent expires. Note that this may be called earlier 161 * than requested by the agent if the trust timeout is adjusted by the system or 162 * {@link DevicePolicyManager}. The agent is expected to re-evaluate the trust state and only 163 * call {@link #grantTrust(CharSequence, long, boolean)} if the trust state should be 164 * continued. 165 */ 166 public void onTrustTimeout() { 167 } 168 169 private void onError(String msg) { 170 Slog.v(TAG, "Remote exception while " + msg); 171 } 172 173 /** 174 * Called when device policy wants to restrict features in the agent in response to 175 * {@link DevicePolicyManager#setTrustAgentFeaturesEnabled(ComponentName, ComponentName, java.util.List) }. 176 * Agents that support this feature should overload this method and return 'true'. 177 * 178 * The list of options can be obtained by calling 179 * options.getStringArrayList({@link #KEY_FEATURES}). Presence of a feature string in the list 180 * means it should be enabled ("white-listed"). Absence of the feature means it should be 181 * disabled. An empty list means all features should be disabled. 182 * 183 * This function is only called if {@link DevicePolicyManager#KEYGUARD_DISABLE_TRUST_AGENTS} is 184 * set. 185 * 186 * @param options Option feature bundle. 187 * @return true if the {@link TrustAgentService} supports this feature. 188 * @hide 189 */ 190 public boolean onSetTrustAgentFeaturesEnabled(Bundle options) { 191 return false; 192 } 193 194 /** 195 * Call to grant trust on the device. 196 * 197 * @param message describes why the device is trusted, e.g. "Trusted by location". 198 * @param durationMs amount of time in milliseconds to keep the device in a trusted state. 199 * Trust for this agent will automatically be revoked when the timeout expires unless 200 * extended by a subsequent call to this function. The timeout is measured from the 201 * invocation of this function as dictated by {@link SystemClock#elapsedRealtime())}. 202 * For security reasons, the value should be no larger than necessary. 203 * The value may be adjusted by the system as necessary to comply with a policy controlled 204 * by the system or {@link DevicePolicyManager} restrictions. See {@link #onTrustTimeout()} 205 * for determining when trust expires. 206 * @param initiatedByUser this is a hint to the system that trust is being granted as the 207 * direct result of user action - such as solving a security challenge. The hint is used 208 * by the system to optimize the experience. Behavior may vary by device and release, so 209 * one should only set this parameter if it meets the above criteria rather than relying on 210 * the behavior of any particular device or release. 211 * @throws IllegalStateException if the agent is not currently managing trust. 212 */ 213 public final void grantTrust( 214 final CharSequence message, final long durationMs, final boolean initiatedByUser) { 215 synchronized (mLock) { 216 if (!mManagingTrust) { 217 throw new IllegalStateException("Cannot grant trust if agent is not managing trust." 218 + " Call setManagingTrust(true) first."); 219 } 220 if (mCallback != null) { 221 try { 222 mCallback.grantTrust(message.toString(), durationMs, initiatedByUser); 223 } catch (RemoteException e) { 224 onError("calling enableTrust()"); 225 } 226 } else { 227 // Remember trust has been granted so we can effectively grant it once the service 228 // is bound. 229 mPendingGrantTrustTask = new Runnable() { 230 @Override 231 public void run() { 232 grantTrust(message, durationMs, initiatedByUser); 233 } 234 }; 235 } 236 } 237 } 238 239 /** 240 * Call to revoke trust on the device. 241 */ 242 public final void revokeTrust() { 243 synchronized (mLock) { 244 if (mPendingGrantTrustTask != null) { 245 mPendingGrantTrustTask = null; 246 } 247 if (mCallback != null) { 248 try { 249 mCallback.revokeTrust(); 250 } catch (RemoteException e) { 251 onError("calling revokeTrust()"); 252 } 253 } 254 } 255 } 256 257 /** 258 * Call to notify the system if the agent is ready to manage trust. 259 * 260 * This property is not persistent across recreating the service and defaults to false. 261 * Therefore this method is typically called when initializing the agent in {@link #onCreate}. 262 * 263 * @param managingTrust indicates if the agent would like to manage trust. 264 */ 265 public final void setManagingTrust(boolean managingTrust) { 266 synchronized (mLock) { 267 if (mManagingTrust != managingTrust) { 268 mManagingTrust = managingTrust; 269 if (mCallback != null) { 270 try { 271 mCallback.setManagingTrust(managingTrust); 272 } catch (RemoteException e) { 273 onError("calling setManagingTrust()"); 274 } 275 } 276 } 277 } 278 } 279 280 @Override 281 public final IBinder onBind(Intent intent) { 282 if (DEBUG) Slog.v(TAG, "onBind() intent = " + intent); 283 return new TrustAgentServiceWrapper(); 284 } 285 286 private final class TrustAgentServiceWrapper extends ITrustAgentService.Stub { 287 @Override /* Binder API */ 288 public void onUnlockAttempt(boolean successful) { 289 mHandler.obtainMessage(MSG_UNLOCK_ATTEMPT, successful ? 1 : 0, 0).sendToTarget(); 290 } 291 292 @Override /* Binder API */ 293 public void onTrustTimeout() { 294 mHandler.sendEmptyMessage(MSG_TRUST_TIMEOUT); 295 } 296 297 @Override /* Binder API */ 298 public void setCallback(ITrustAgentServiceCallback callback) { 299 synchronized (mLock) { 300 mCallback = callback; 301 // The managingTrust property is false implicitly on the server-side, so we only 302 // need to set it here if the agent has decided to manage trust. 303 if (mManagingTrust) { 304 try { 305 mCallback.setManagingTrust(mManagingTrust); 306 } catch (RemoteException e ) { 307 onError("calling setManagingTrust()"); 308 } 309 } 310 if (mPendingGrantTrustTask != null) { 311 mPendingGrantTrustTask.run(); 312 mPendingGrantTrustTask = null; 313 } 314 } 315 } 316 317 @Override /* Binder API */ 318 public void setTrustAgentFeaturesEnabled(Bundle features, IBinder token) { 319 Message msg = mHandler.obtainMessage(MSG_SET_TRUST_AGENT_FEATURES_ENABLED, token); 320 msg.setData(features); 321 msg.sendToTarget(); 322 } 323 } 324 325} 326