TrustAgentService.java revision 0814d41c73fe3ebc2d1269f1a4fc73d0cf4cb230
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.PersistableBundle;
33import android.os.RemoteException;
34import android.os.SystemClock;
35import android.util.Log;
36import android.util.Slog;
37
38import java.util.List;
39
40/**
41 * A service that notifies the system about whether it believes the environment of the device
42 * to be trusted.
43 *
44 * <p>Trust agents may only be provided by the platform. It is expected that there is only
45 * one trust agent installed on the platform. In the event there is more than one,
46 * either trust agent can enable trust.
47 * </p>
48 *
49 * <p>To extend this class, you must declare the service in your manifest file with
50 * the {@link android.Manifest.permission#BIND_TRUST_AGENT} permission
51 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p>
52 * <pre>
53 * &lt;service android:name=".TrustAgent"
54 *          android:label="&#64;string/service_name"
55 *          android:permission="android.permission.BIND_TRUST_AGENT">
56 *     &lt;intent-filter>
57 *         &lt;action android:name="android.service.trust.TrustAgentService" />
58 *     &lt;/intent-filter>
59 *     &lt;meta-data android:name="android.service.trust.trustagent"
60 *          android:value="&#64;xml/trust_agent" />
61 * &lt;/service></pre>
62 *
63 * <p>The associated meta-data file can specify an activity that is accessible through Settings
64 * and should allow configuring the trust agent, as defined in
65 * {@link android.R.styleable#TrustAgent}. For example:</p>
66 *
67 * <pre>
68 * &lt;trust-agent xmlns:android="http://schemas.android.com/apk/res/android"
69 *          android:settingsActivity=".TrustAgentSettings" /></pre>
70 *
71 * @hide
72 */
73@SystemApi
74public class TrustAgentService extends Service {
75    private final String TAG = TrustAgentService.class.getSimpleName() +
76            "[" + getClass().getSimpleName() + "]";
77    private static final boolean DEBUG = false;
78
79    /**
80     * The {@link Intent} that must be declared as handled by the service.
81     */
82    @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION)
83    public static final String SERVICE_INTERFACE
84            = "android.service.trust.TrustAgentService";
85
86    /**
87     * The name of the {@code meta-data} tag pointing to additional configuration of the trust
88     * agent.
89     */
90    public static final String TRUST_AGENT_META_DATA = "android.service.trust.trustagent";
91
92    private static final int MSG_UNLOCK_ATTEMPT = 1;
93    private static final int MSG_CONFIGURE = 2;
94    private static final int MSG_TRUST_TIMEOUT = 3;
95
96    /**
97     * Class containing raw data for a given configuration request.
98     */
99    private static final class ConfigurationData {
100        final IBinder token;
101        final List<PersistableBundle> options;
102        ConfigurationData(List<PersistableBundle> opts, IBinder t) {
103            options = opts;
104            token = t;
105        }
106    }
107
108    private ITrustAgentServiceCallback mCallback;
109
110    private Runnable mPendingGrantTrustTask;
111
112    private boolean mManagingTrust;
113
114    // Lock used to access mPendingGrantTrustTask and mCallback.
115    private final Object mLock = new Object();
116
117    private Handler mHandler = new Handler() {
118        public void handleMessage(android.os.Message msg) {
119            switch (msg.what) {
120                case MSG_UNLOCK_ATTEMPT:
121                    onUnlockAttempt(msg.arg1 != 0);
122                    break;
123                case MSG_CONFIGURE:
124                    ConfigurationData data = (ConfigurationData) msg.obj;
125                    boolean result = onConfigure(data.options);
126                    try {
127                        synchronized (mLock) {
128                            mCallback.onConfigureCompleted(result, data.token);
129                        }
130                    } catch (RemoteException e) {
131                        onError("calling onSetTrustAgentFeaturesEnabledCompleted()");
132                    }
133                    break;
134                case MSG_TRUST_TIMEOUT:
135                    onTrustTimeout();
136                    break;
137            }
138        }
139    };
140
141    @Override
142    public void onCreate() {
143        super.onCreate();
144        ComponentName component = new ComponentName(this, getClass());
145        try {
146            ServiceInfo serviceInfo = getPackageManager().getServiceInfo(component, 0 /* flags */);
147            if (!Manifest.permission.BIND_TRUST_AGENT.equals(serviceInfo.permission)) {
148                throw new IllegalStateException(component.flattenToShortString()
149                        + " is not declared with the permission "
150                        + "\"" + Manifest.permission.BIND_TRUST_AGENT + "\"");
151            }
152        } catch (PackageManager.NameNotFoundException e) {
153            Log.e(TAG, "Can't get ServiceInfo for " + component.toShortString());
154        }
155    }
156
157    /**
158     * Called after the user attempts to authenticate in keyguard with their device credentials,
159     * such as pin, pattern or password.
160     *
161     * @param successful true if the user successfully completed the challenge.
162     */
163    public void onUnlockAttempt(boolean successful) {
164    }
165
166    /**
167     * Called when the timeout provided by the agent expires.  Note that this may be called earlier
168     * than requested by the agent if the trust timeout is adjusted by the system or
169     * {@link DevicePolicyManager}.  The agent is expected to re-evaluate the trust state and only
170     * call {@link #grantTrust(CharSequence, long, boolean)} if the trust state should be
171     * continued.
172     */
173    public void onTrustTimeout() {
174    }
175
176    private void onError(String msg) {
177        Slog.v(TAG, "Remote exception while " + msg);
178    }
179
180    /**
181     * Called when device policy admin wants to enable specific options for agent in response to
182     * {@link DevicePolicyManager#setKeyguardDisabledFeatures(ComponentName, int)} and
183     * {@link DevicePolicyManager#setTrustAgentConfiguration(ComponentName, ComponentName,
184     * PersistableBundle)}.
185     * <p>Agents that support configuration options should overload this method and return 'true'.
186     *
187     * @param options bundle containing all options or null if none.
188     * @return true if the {@link TrustAgentService} supports configuration options.
189     */
190    public boolean onConfigure(List<PersistableBundle> 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 onConfigure(List<PersistableBundle> args, IBinder token) {
299            mHandler.obtainMessage(MSG_CONFIGURE, new ConfigurationData(args, token))
300                    .sendToTarget();
301        }
302
303        @Override /* Binder API */
304        public void setCallback(ITrustAgentServiceCallback callback) {
305            synchronized (mLock) {
306                mCallback = callback;
307                // The managingTrust property is false implicitly on the server-side, so we only
308                // need to set it here if the agent has decided to manage trust.
309                if (mManagingTrust) {
310                    try {
311                        mCallback.setManagingTrust(mManagingTrust);
312                    } catch (RemoteException e ) {
313                        onError("calling setManagingTrust()");
314                    }
315                }
316                if (mPendingGrantTrustTask != null) {
317                    mPendingGrantTrustTask.run();
318                    mPendingGrantTrustTask = null;
319                }
320            }
321        }
322    }
323
324}
325