1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.chrome.browser;
7 import android.content.Context;
8 import android.os.AsyncTask;
9 import android.util.Log;
11 import org.chromium.base.SecureRandomInitializer;
14 import java.io.FileInputStream;
15 import java.io.FileOutputStream;
16 import java.io.IOException;
17 import java.security.GeneralSecurityException;
18 import java.security.SecureRandom;
19 import java.util.concurrent.Callable;
20 import java.util.concurrent.ExecutionException;
21 import java.util.concurrent.FutureTask;
23 import javax.crypto.KeyGenerator;
24 import javax.crypto.Mac;
25 import javax.crypto.SecretKey;
26 import javax.crypto.spec.SecretKeySpec;
29 * Authenticate the source of Intents to launch web apps (see e.g. {@link #FullScreenActivity}).
31 * Chrome does not keep a store of valid URLs for installed web apps (because it cannot know when
32 * any have been uninstalled). Therefore, upon installation, it tells the Launcher a message
33 * authentication code (MAC) along with the URL for the web app, and then Chrome can verify the MAC
34 * when starting e.g. {@link #FullScreenActivity}. Chrome can thus distinguish between legitimate,
35 * installed web apps and arbitrary other URLs.
37 public class WebappAuthenticator {
38 private static final String TAG = "WebappAuthenticator";
39 private static final String MAC_ALGORITHM_NAME = "HmacSHA256";
40 private static final String MAC_KEY_BASENAME = "webapp-authenticator";
41 private static final int MAC_KEY_BYTE_COUNT = 32;
42 private static final Object sLock = new Object();
44 private static FutureTask<SecretKey> sMacKeyGenerator;
45 private static SecretKey sKey = null;
50 * @param url The URL to validate.
51 * @param mac The bytes of a previously-calculated MAC.
53 * @return true if the MAC is a valid MAC for the URL, false otherwise.
55 public static boolean isUrlValid(Context context, String url, byte[] mac) {
56 byte[] goodMac = getMacForUrl(context, url);
57 if (goodMac == null) {
60 return constantTimeAreArraysEqual(goodMac, mac);
66 * @param url A URL for which to calculate a MAC.
68 * @return The bytes of a MAC for the URL, or null if a secure MAC was not available.
70 public static byte[] getMacForUrl(Context context, String url) {
71 Mac mac = getMac(context);
75 return mac.doFinal(url.getBytes());
78 // TODO(palmer): Put this method, and as much of this class as possible, in a utility class.
79 private static boolean constantTimeAreArraysEqual(byte[] a, byte[] b) {
80 if (a.length != b.length) {
85 for (int i = 0; i < a.length; i++) {
86 result |= a[i] ^ b[i];
91 private static SecretKey readKeyFromFile(
92 Context context, String basename, String algorithmName) {
93 FileInputStream input = null;
94 File file = context.getFileStreamPath(basename);
96 if (file.length() != MAC_KEY_BYTE_COUNT) {
97 Log.w(TAG, "Could not read key from '" + file + "': invalid file contents");
101 byte[] keyBytes = new byte[MAC_KEY_BYTE_COUNT];
102 input = new FileInputStream(file);
103 if (MAC_KEY_BYTE_COUNT != input.read(keyBytes)) {
108 return new SecretKeySpec(keyBytes, algorithmName);
109 } catch (IllegalArgumentException e) {
112 } catch (Exception e) {
113 Log.w(TAG, "Could not read key from '" + file + "': " + e);
120 } catch (IOException e) {
121 Log.e(TAG, "Could not close key input stream '" + file + "': " + e);
126 private static boolean writeKeyToFile(Context context, String basename, SecretKey key) {
127 File file = context.getFileStreamPath(basename);
128 byte[] keyBytes = key.getEncoded();
129 FileOutputStream output = null;
130 if (MAC_KEY_BYTE_COUNT != keyBytes.length) {
131 Log.e(TAG, "writeKeyToFile got key encoded bytes length " + keyBytes.length +
132 "; expected " + MAC_KEY_BYTE_COUNT);
137 output = new FileOutputStream(file);
138 output.write(keyBytes);
140 } catch (Exception e) {
141 Log.e(TAG, "Could not write key to '" + file + "': " + e);
145 if (output != null) {
148 } catch (IOException e) {
149 Log.e(TAG, "Could not close key output stream '" + file + "': " + e);
154 private static SecretKey getKey(Context context) {
155 synchronized (sLock) {
157 SecretKey key = readKeyFromFile(context, MAC_KEY_BASENAME, MAC_ALGORITHM_NAME);
163 triggerMacKeyGeneration();
165 sKey = sMacKeyGenerator.get();
166 sMacKeyGenerator = null;
167 if (!writeKeyToFile(context, MAC_KEY_BASENAME, sKey)) {
172 } catch (InterruptedException e) {
173 throw new RuntimeException(e);
174 } catch (ExecutionException e) {
175 throw new RuntimeException(e);
183 * Generates the authentication encryption key in a background thread (if necessary).
185 private static void triggerMacKeyGeneration() {
186 synchronized (sLock) {
187 if (sKey != null || sMacKeyGenerator != null) {
191 sMacKeyGenerator = new FutureTask<SecretKey>(new Callable<SecretKey>() {
193 public SecretKey call() throws Exception {
194 KeyGenerator generator = KeyGenerator.getInstance(MAC_ALGORITHM_NAME);
195 SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
196 SecureRandomInitializer.initialize(random);
197 generator.init(MAC_KEY_BYTE_COUNT * 8, random);
198 return generator.generateKey();
201 AsyncTask.THREAD_POOL_EXECUTOR.execute(sMacKeyGenerator);
206 * @return A Mac, or null if it is not possible to instantiate one.
208 private static Mac getMac(Context context) {
210 SecretKey key = getKey(context);
212 // getKey should have invoked triggerMacKeyGeneration, which should have set the
213 // random seed and generated a key from it. If not, there is a problem with the
214 // random number generator, and we must not claim that authentication can work.
217 Mac mac = Mac.getInstance(MAC_ALGORITHM_NAME);
220 } catch (GeneralSecurityException e) {
221 Log.w(TAG, "Error in creating MAC instance", e);