Debian Codegraph @

core/java/android/security/ConfirmationPrompt.java

raw symbols SCIP
1 /*
2 * Copyright 2018 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.security;
18
19 import android.annotation.NonNull;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.provider.Settings;
23 import android.provider.Settings.SettingNotFoundException;
24 import android.text.TextUtils;
25 import android.util.Log;
26
27 import java.util.Locale;
28 import java.util.concurrent.Executor;
29
30 /**
31 * Class used for displaying confirmation prompts.
32 *
33 * <p>Confirmation prompts are prompts shown to the user to confirm a given text and are
34 * implemented in a way that a positive response indicates with high confidence that the user has
35 * seen the given text, even if the Android framework (including the kernel) was
36 * compromised. Implementing confirmation prompts with these guarantees requires dedicated
37 * hardware-support and may not always be available.
38 *
39 * <p>Confirmation prompts are typically used with an external entity - the <i>Relying Party</i> -
40 * in the following way. The setup steps are as follows:
41 * <ul>
42 * <li> Before first use, the application generates a key-pair with the
43 * {@link android.security.keystore.KeyGenParameterSpec.Builder#setUserConfirmationRequired
44 * CONFIRMATION tag} set. AndroidKeyStore key attestation, e.g.,
45 * {@link android.security.keystore.KeyGenParameterSpec.Builder#setAttestationChallenge(byte[])}
46 * is used to generate a certificate chain that includes the public key (<code>Kpub</code> in the
47 * following) of the newly generated key.
48 * <li> The application sends <code>Kpub</code> and the certificate chain resulting from device
49 * attestation to the <i>Relying Party</i>.
50 * <li> The <i>Relying Party</i> validates the certificate chain which involves checking the root
51 * certificate is what is expected (e.g. a certificate from Google), each certificate signs the
52 * next one in the chain, ending with <code>Kpub</code>, and that the attestation certificate
53 * asserts that <code>Kpub</code> has the
54 * {@link android.security.keystore.KeyGenParameterSpec.Builder#setUserConfirmationRequired
55 * CONFIRMATION tag} set.
56 * Additionally the relying party stores <code>Kpub</code> and associates it with the device
57 * it was received from.
58 * </ul>
59 *
60 * <p>The <i>Relying Party</i> is typically an external device (for example connected via
61 * Bluetooth) or application server.
62 *
63 * <p>Before executing a transaction which requires a high assurance of user content, the
64 * application does the following:
65 * <ul>
66 * <li> The application gets a cryptographic nonce from the <i>Relying Party</i> and passes this as
67 * the <code>extraData</code> (via the Builder helper class) to the
68 * {@link #presentPrompt presentPrompt()} method. The <i>Relying Party</i> stores the nonce locally
69 * since it'll use it in a later step.
70 * <li> If the user approves the prompt a <i>Confirmation Response</i> is returned in the
71 * {@link ConfirmationCallback#onConfirmed onConfirmed(byte[])} callback as the
72 * <code>dataThatWasConfirmed</code> parameter. This blob contains the text that was shown to the
73 * user, the <code>extraData</code> parameter, and possibly other data.
74 * <li> The application signs the <i>Confirmation Response</i> with the previously created key and
75 * sends the blob and the signature to the <i>Relying Party</i>.
76 * <li> The <i>Relying Party</i> checks that the signature was made with <code>Kpub</code> and then
77 * extracts <code>promptText</code> matches what is expected and <code>extraData</code> matches the
78 * previously created nonce. If all checks passes, the transaction is executed.
79 * </ul>
80 *
81 * <p>Note: It is vital to check the <code>promptText</code> because this is the only part that
82 * the user has approved. To avoid writing parsers for all of the possible locales, it is
83 * recommended that the <i>Relying Party</i> uses the same string generator as used on the device
84 * and performs a simple string comparison.
85 */
86 public class ConfirmationPrompt {
87 private static final String TAG = "ConfirmationPrompt";
88
89 private CharSequence mPromptText;
90 private byte[] mExtraData;
91 private ConfirmationCallback mCallback;
92 private Executor mExecutor;
93 private Context mContext;
94
95 private final KeyStore mKeyStore = KeyStore.getInstance();
96 private AndroidProtectedConfirmation mProtectedConfirmation;
97
98 private AndroidProtectedConfirmation getService() {
99 if (mProtectedConfirmation == null) {
100 mProtectedConfirmation = new AndroidProtectedConfirmation();
101 }
102 return mProtectedConfirmation;
103 }
104
105 private void doCallback(int responseCode, byte[] dataThatWasConfirmed,
106 ConfirmationCallback callback) {
107 switch (responseCode) {
108 case AndroidProtectedConfirmation.ERROR_OK:
109 callback.onConfirmed(dataThatWasConfirmed);
110 break;
111
112 case AndroidProtectedConfirmation.ERROR_CANCELED:
113 callback.onDismissed();
114 break;
115
116 case AndroidProtectedConfirmation.ERROR_ABORTED:
117 callback.onCanceled();
118 break;
119
120 case AndroidProtectedConfirmation.ERROR_SYSTEM_ERROR:
121 callback.onError(new Exception("System error returned by ConfirmationUI."));
122 break;
123
124 default:
125 callback.onError(new Exception("Unexpected responseCode=" + responseCode
126 + " from onConfirmtionPromptCompleted() callback."));
127 break;
128 }
129 }
130
131 private final android.security.apc.IConfirmationCallback mConfirmationCallback =
132 new android.security.apc.IConfirmationCallback.Stub() {
133 @Override
134 public void onCompleted(int result, byte[] dataThatWasConfirmed)
135 throws android.os.RemoteException {
136 if (mCallback != null) {
137 ConfirmationCallback callback = mCallback;
138 Executor executor = mExecutor;
139 mCallback = null;
140 mExecutor = null;
141 if (executor == null) {
142 doCallback(result, dataThatWasConfirmed, callback);
143 } else {
144 executor.execute(new Runnable() {
145 @Override public void run() {
146 doCallback(result, dataThatWasConfirmed, callback);
147 }
148 });
149 }
150 }
151 }
152 };
153
154 /**
155 * A builder that collects arguments, to be shown on the system-provided confirmation prompt.
156 */
157 public static final class Builder {
158
159 private Context mContext;
160 private CharSequence mPromptText;
161 private byte[] mExtraData;
162
163 /**
164 * Creates a builder for the confirmation prompt.
165 *
166 * @param context the application context
167 */
168 public Builder(Context context) {
169 mContext = context;
170 }
171
172 /**
173 * Sets the prompt text for the prompt.
174 *
175 * @param promptText the text to present in the prompt.
176 * @return the builder.
177 */
178 public Builder setPromptText(CharSequence promptText) {
179 mPromptText = promptText;
180 return this;
181 }
182
183 /**
184 * Sets the extra data for the prompt.
185 *
186 * @param extraData data to include in the response data.
187 * @return the builder.
188 */
189 public Builder setExtraData(byte[] extraData) {
190 mExtraData = extraData;
191 return this;
192 }
193
194 /**
195 * Creates a {@link ConfirmationPrompt} with the arguments supplied to this builder.
196 *
197 * @return a {@link ConfirmationPrompt}
198 * @throws IllegalArgumentException if any of the required fields are not set.
199 */
200 public ConfirmationPrompt build() {
201 if (TextUtils.isEmpty(mPromptText)) {
202 throw new IllegalArgumentException("prompt text must be set and non-empty");
203 }
204 if (mExtraData == null) {
205 throw new IllegalArgumentException("extraData must be set");
206 }
207 return new ConfirmationPrompt(mContext, mPromptText, mExtraData);
208 }
209 }
210
211 private ConfirmationPrompt(Context context, CharSequence promptText, byte[] extraData) {
212 mContext = context;
213 mPromptText = promptText;
214 mExtraData = extraData;
215 }
216
217 private int getUiOptionsAsFlags() {
218 int uiOptionsAsFlags = 0;
219 ContentResolver contentResolver = mContext.getContentResolver();
220 int inversionEnabled = Settings.Secure.getInt(contentResolver,
221 Settings.Secure.ACCESSIBILITY_DISPLAY_INVERSION_ENABLED, 0);
222 if (inversionEnabled == 1) {
223 uiOptionsAsFlags |= AndroidProtectedConfirmation.FLAG_UI_OPTION_INVERTED;
224 }
225 float fontScale = Settings.System.getFloat(contentResolver,
226 Settings.System.FONT_SCALE, (float) 1.0);
227 if (fontScale > 1.0) {
228 uiOptionsAsFlags |= AndroidProtectedConfirmation.FLAG_UI_OPTION_MAGNIFIED;
229 }
230 return uiOptionsAsFlags;
231 }
232
233 private static boolean isAccessibilityServiceRunning(Context context) {
234 boolean serviceRunning = false;
235 try {
236 ContentResolver contentResolver = context.getContentResolver();
237 int a11yEnabled = Settings.Secure.getInt(contentResolver,
238 Settings.Secure.ACCESSIBILITY_ENABLED);
239 if (a11yEnabled == 1) {
240 serviceRunning = true;
241 }
242 } catch (SettingNotFoundException e) {
243 Log.w(TAG, "Unexpected SettingNotFoundException");
244 e.printStackTrace();
245 }
246 return serviceRunning;
247 }
248
249 /**
250 * Requests a confirmation prompt to be presented to the user.
251 *
252 * When the prompt is no longer being presented, one of the methods in
253 * {@link ConfirmationCallback} is called on the supplied callback object.
254 *
255 * Confirmation prompts may not be available when accessibility services are running so this
256 * may fail with a {@link ConfirmationNotAvailableException} exception even if
257 * {@link #isSupported} returns {@code true}.
258 *
259 * @param executor the executor identifying the thread that will receive the callback.
260 * @param callback the callback to use when the prompt is done showing.
261 * @throws IllegalArgumentException if the prompt text is too long or malfomed.
262 * @throws ConfirmationAlreadyPresentingException if another prompt is being presented.
263 * @throws ConfirmationNotAvailableException if confirmation prompts are not supported.
264 */
265 public void presentPrompt(@NonNull Executor executor, @NonNull ConfirmationCallback callback)
266 throws ConfirmationAlreadyPresentingException,
267 ConfirmationNotAvailableException {
268 if (mCallback != null) {
269 throw new ConfirmationAlreadyPresentingException();
270 }
271 if (isAccessibilityServiceRunning(mContext)) {
272 throw new ConfirmationNotAvailableException();
273 }
274 mCallback = callback;
275 mExecutor = executor;
276
277 String locale = Locale.getDefault().toLanguageTag();
278 int uiOptionsAsFlags = getUiOptionsAsFlags();
279 int responseCode = getService().presentConfirmationPrompt(
280 mConfirmationCallback, mPromptText.toString(), mExtraData, locale,
281 uiOptionsAsFlags);
282 switch (responseCode) {
283 case AndroidProtectedConfirmation.ERROR_OK:
284 return;
285
286 case AndroidProtectedConfirmation.ERROR_OPERATION_PENDING:
287 throw new ConfirmationAlreadyPresentingException();
288
289 case AndroidProtectedConfirmation.ERROR_UNIMPLEMENTED:
290 throw new ConfirmationNotAvailableException();
291
292 default:
293 // Unexpected error code.
294 Log.w(TAG,
295 "Unexpected responseCode=" + responseCode
296 + " from presentConfirmationPrompt() call.");
297 throw new IllegalArgumentException();
298 }
299 }
300
301 /**
302 * Cancels a prompt currently being displayed.
303 *
304 * On success, the
305 * {@link ConfirmationCallback#onCanceled onCanceled()} method on
306 * the supplied callback object will be called asynchronously.
307 *
308 * @throws IllegalStateException if no prompt is currently being presented.
309 */
310 public void cancelPrompt() {
311 int responseCode =
312 getService().cancelConfirmationPrompt(mConfirmationCallback);
313 if (responseCode == AndroidProtectedConfirmation.ERROR_OK) {
314 return;
315 } else if (responseCode == AndroidProtectedConfirmation.ERROR_OPERATION_PENDING) {
316 throw new IllegalStateException();
317 } else {
318 // Unexpected error code.
319 Log.w(TAG,
320 "Unexpected responseCode=" + responseCode
321 + " from cancelConfirmationPrompt() call.");
322 throw new IllegalStateException();
323 }
324 }
325
326 /**
327 * Checks if the device supports confirmation prompts.
328 *
329 * @param context the application context.
330 * @return true if confirmation prompts are supported by the device.
331 */
332 public static boolean isSupported(Context context) {
333 if (isAccessibilityServiceRunning(context)) {
334 return false;
335 }
336 return new AndroidProtectedConfirmation().isConfirmationPromptSupported();
337 }
338 }