Debian Codegraph @

keystore/java/android/security/keystore2/AndroidKeyStoreKeyGeneratorSpi.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2015 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.keystore2;
18
19 import android.hardware.security.keymint.KeyParameter;
20 import android.hardware.security.keymint.SecurityLevel;
21 import android.security.KeyStore2;
22 import android.security.KeyStoreSecurityLevel;
23 import android.security.keymaster.KeymasterDefs;
24 import android.security.keystore.ArrayUtils;
25 import android.security.keystore.KeyGenParameterSpec;
26 import android.security.keystore.KeyProperties;
27 import android.security.keystore.StrongBoxUnavailableException;
28 import android.system.keystore2.Domain;
29 import android.system.keystore2.IKeystoreSecurityLevel;
30 import android.system.keystore2.KeyDescriptor;
31 import android.system.keystore2.KeyMetadata;
32 import android.util.Log;
33
34 import libcore.util.EmptyArray;
35
36 import java.security.InvalidAlgorithmParameterException;
37 import java.security.ProviderException;
38 import java.security.SecureRandom;
39 import java.security.spec.AlgorithmParameterSpec;
40 import java.util.ArrayList;
41 import java.util.Arrays;
42 import java.util.List;
43
44 import javax.crypto.KeyGeneratorSpi;
45 import javax.crypto.SecretKey;
46
47 /**
48 * {@link KeyGeneratorSpi} backed by Android KeyStore.
49 *
50 * @hide
51 */
52 public abstract class AndroidKeyStoreKeyGeneratorSpi extends KeyGeneratorSpi {
53 private static final String TAG = "AndroidKeyStoreKeyGeneratorSpi";
54
55 public static class AES extends AndroidKeyStoreKeyGeneratorSpi {
56 public AES() {
57 super(KeymasterDefs.KM_ALGORITHM_AES, 128);
58 }
59
60 @Override
61 protected void engineInit(AlgorithmParameterSpec params, SecureRandom random)
62 throws InvalidAlgorithmParameterException {
63 super.engineInit(params, random);
64 if ((mKeySizeBits != 128) && (mKeySizeBits != 192) && (mKeySizeBits != 256)) {
65 throw new InvalidAlgorithmParameterException(
66 "Unsupported key size: " + mKeySizeBits
67 + ". Supported: 128, 192, 256.");
68 }
69 }
70 }
71
72 public static class DESede extends AndroidKeyStoreKeyGeneratorSpi {
73 public DESede() {
74 super(KeymasterDefs.KM_ALGORITHM_3DES, 168);
75 }
76 }
77
78 protected static abstract class HmacBase extends AndroidKeyStoreKeyGeneratorSpi {
79 protected HmacBase(int keymasterDigest) {
80 super(KeymasterDefs.KM_ALGORITHM_HMAC,
81 keymasterDigest,
82 KeymasterUtils.getDigestOutputSizeBits(keymasterDigest));
83 }
84 }
85
86 public static class HmacSHA1 extends HmacBase {
87 public HmacSHA1() {
88 super(KeymasterDefs.KM_DIGEST_SHA1);
89 }
90 }
91
92 public static class HmacSHA224 extends HmacBase {
93 public HmacSHA224() {
94 super(KeymasterDefs.KM_DIGEST_SHA_2_224);
95 }
96 }
97
98 public static class HmacSHA256 extends HmacBase {
99 public HmacSHA256() {
100 super(KeymasterDefs.KM_DIGEST_SHA_2_256);
101 }
102 }
103
104 public static class HmacSHA384 extends HmacBase {
105 public HmacSHA384() {
106 super(KeymasterDefs.KM_DIGEST_SHA_2_384);
107 }
108 }
109
110 public static class HmacSHA512 extends HmacBase {
111 public HmacSHA512() {
112 super(KeymasterDefs.KM_DIGEST_SHA_2_512);
113 }
114 }
115
116 private final KeyStore2 mKeyStore = KeyStore2.getInstance();
117 private final int mKeymasterAlgorithm;
118 private final int mKeymasterDigest;
119 private final int mDefaultKeySizeBits;
120
121 private KeyGenParameterSpec mSpec;
122 private SecureRandom mRng;
123
124 protected int mKeySizeBits;
125 private int[] mKeymasterPurposes;
126 private int[] mKeymasterBlockModes;
127 private int[] mKeymasterPaddings;
128 private int[] mKeymasterDigests;
129
130 protected AndroidKeyStoreKeyGeneratorSpi(
131 int keymasterAlgorithm,
132 int defaultKeySizeBits) {
133 this(keymasterAlgorithm, -1, defaultKeySizeBits);
134 }
135
136 protected AndroidKeyStoreKeyGeneratorSpi(
137 int keymasterAlgorithm,
138 int keymasterDigest,
139 int defaultKeySizeBits) {
140 mKeymasterAlgorithm = keymasterAlgorithm;
141 mKeymasterDigest = keymasterDigest;
142 mDefaultKeySizeBits = defaultKeySizeBits;
143 if (mDefaultKeySizeBits <= 0) {
144 throw new IllegalArgumentException("Default key size must be positive");
145 }
146
147 if ((mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) && (mKeymasterDigest == -1)) {
148 throw new IllegalArgumentException(
149 "Digest algorithm must be specified for HMAC key");
150 }
151 }
152
153 @Override
154 protected void engineInit(SecureRandom random) {
155 throw new UnsupportedOperationException("Cannot initialize without a "
156 + KeyGenParameterSpec.class.getName() + " parameter");
157 }
158
159 @Override
160 protected void engineInit(int keySize, SecureRandom random) {
161 throw new UnsupportedOperationException("Cannot initialize without a "
162 + KeyGenParameterSpec.class.getName() + " parameter");
163 }
164
165 @Override
166 protected void engineInit(AlgorithmParameterSpec params, SecureRandom random)
167 throws InvalidAlgorithmParameterException {
168 resetAll();
169
170 boolean success = false;
171 try {
172 if ((params == null) || (!(params instanceof KeyGenParameterSpec))) {
173 throw new InvalidAlgorithmParameterException("Cannot initialize without a "
174 + KeyGenParameterSpec.class.getName() + " parameter");
175 }
176 KeyGenParameterSpec spec = (KeyGenParameterSpec) params;
177 if (spec.getKeystoreAlias() == null) {
178 throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
179 }
180
181 mRng = random;
182 mSpec = spec;
183
184 mKeySizeBits = (spec.getKeySize() != -1) ? spec.getKeySize() : mDefaultKeySizeBits;
185 if (mKeySizeBits <= 0) {
186 throw new InvalidAlgorithmParameterException(
187 "Key size must be positive: " + mKeySizeBits);
188 } else if ((mKeySizeBits % 8) != 0) {
189 throw new InvalidAlgorithmParameterException(
190 "Key size must be a multiple of 8: " + mKeySizeBits);
191 }
192
193 try {
194 mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
195 mKeymasterPaddings = KeyProperties.EncryptionPadding.allToKeymaster(
196 spec.getEncryptionPaddings());
197 if (spec.getSignaturePaddings().length > 0) {
198 throw new InvalidAlgorithmParameterException(
199 "Signature paddings not supported for symmetric key algorithms");
200 }
201 mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
202 if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0)
203 && (spec.isRandomizedEncryptionRequired())) {
204 for (int keymasterBlockMode : mKeymasterBlockModes) {
205 if (!KeymasterUtils.isKeymasterBlockModeIndCpaCompatibleWithSymmetricCrypto(
206 keymasterBlockMode)) {
207 throw new InvalidAlgorithmParameterException(
208 "Randomized encryption (IND-CPA) required but may be violated"
209 + " by block mode: "
210 + KeyProperties.BlockMode.fromKeymaster(keymasterBlockMode)
211 + ". See " + KeyGenParameterSpec.class.getName()
212 + " documentation.");
213 }
214 }
215 }
216 if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_3DES) {
217 if (mKeySizeBits != 168) {
218 throw new InvalidAlgorithmParameterException(
219 "3DES key size must be 168 bits.");
220 }
221 }
222 if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) {
223 if (mKeySizeBits < 64 || mKeySizeBits > 512) {
224 throw new InvalidAlgorithmParameterException(
225 "HMAC key sizes must be within 64-512 bits, inclusive.");
226 }
227
228 // JCA HMAC key algorithm implies a digest (e.g., HmacSHA256 key algorithm
229 // implies SHA-256 digest). Because keymaster HMAC key is authorized only for
230 // one digest, we don't let algorithm parameter spec override the digest implied
231 // by the key. If the spec specifies digests at all, it must specify only one
232 // digest, the only implied by key algorithm.
233 mKeymasterDigests = new int[] {mKeymasterDigest};
234 if (spec.isDigestsSpecified()) {
235 // Digest(s) explicitly specified in the spec. Check that the list
236 // consists of exactly one digest, the one implied by key algorithm.
237 int[] keymasterDigestsFromSpec =
238 KeyProperties.Digest.allToKeymaster(spec.getDigests());
239 if ((keymasterDigestsFromSpec.length != 1)
240 || (keymasterDigestsFromSpec[0] != mKeymasterDigest)) {
241 throw new InvalidAlgorithmParameterException(
242 "Unsupported digests specification: "
243 + Arrays.asList(spec.getDigests()) + ". Only "
244 + KeyProperties.Digest.fromKeymaster(mKeymasterDigest)
245 + " supported for this HMAC key algorithm");
246 }
247 }
248 } else {
249 // Key algorithm does not imply a digest.
250 if (spec.isDigestsSpecified()) {
251 mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
252 } else {
253 mKeymasterDigests = EmptyArray.INT;
254 }
255 }
256
257 // Check that user authentication related parameters are acceptable. This method
258 // will throw an IllegalStateException if there are issues (e.g., secure lock screen
259 // not set up).
260 KeyStore2ParameterUtils.addUserAuthArgs(new ArrayList<>(), spec);
261 } catch (IllegalStateException | IllegalArgumentException e) {
262 throw new InvalidAlgorithmParameterException(e);
263 }
264
265 success = true;
266 } finally {
267 if (!success) {
268 resetAll();
269 }
270 }
271 }
272
273 private void resetAll() {
274 mSpec = null;
275 mRng = null;
276 mKeySizeBits = -1;
277 mKeymasterPurposes = null;
278 mKeymasterPaddings = null;
279 mKeymasterBlockModes = null;
280 }
281
282 @Override
283 protected SecretKey engineGenerateKey() {
284 KeyGenParameterSpec spec = mSpec;
285 if (spec == null) {
286 throw new IllegalStateException("Not initialized");
287 }
288
289 List<KeyParameter> params = new ArrayList<>();
290
291 params.add(KeyStore2ParameterUtils.makeInt(
292 KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits
293 ));
294 params.add(KeyStore2ParameterUtils.makeEnum(
295 KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm
296 ));
297 ArrayUtils.forEach(mKeymasterPurposes, (purpose) -> {
298 params.add(KeyStore2ParameterUtils.makeEnum(
299 KeymasterDefs.KM_TAG_PURPOSE, purpose
300 ));
301 });
302 ArrayUtils.forEach(mKeymasterBlockModes, (blockMode) -> {
303 if (blockMode == KeymasterDefs.KM_MODE_GCM
304 && mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_AES) {
305 params.add(KeyStore2ParameterUtils.makeInt(
306 KeymasterDefs.KM_TAG_MIN_MAC_LENGTH,
307 AndroidKeyStoreAuthenticatedAESCipherSpi.GCM
308 .MIN_SUPPORTED_TAG_LENGTH_BITS
309 ));
310 }
311 params.add(KeyStore2ParameterUtils.makeEnum(
312 KeymasterDefs.KM_TAG_BLOCK_MODE, blockMode
313 ));
314 });
315 ArrayUtils.forEach(mKeymasterPaddings, (padding) -> {
316 params.add(KeyStore2ParameterUtils.makeEnum(
317 KeymasterDefs.KM_TAG_PADDING, padding
318 ));
319 });
320 ArrayUtils.forEach(mKeymasterDigests, (digest) -> {
321 params.add(KeyStore2ParameterUtils.makeEnum(
322 KeymasterDefs.KM_TAG_DIGEST, digest
323 ));
324 });
325
326 if (mKeymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC
327 && mKeymasterDigests.length != 0) {
328 int digestOutputSizeBits = KeymasterUtils.getDigestOutputSizeBits(mKeymasterDigests[0]);
329 if (digestOutputSizeBits == -1) {
330 throw new ProviderException(
331 "HMAC key authorized for unsupported digest: "
332 + KeyProperties.Digest.fromKeymaster(mKeymasterDigests[0]));
333 }
334 params.add(KeyStore2ParameterUtils.makeInt(
335 KeymasterDefs.KM_TAG_MIN_MAC_LENGTH, digestOutputSizeBits
336 ));
337 }
338
339 KeyStore2ParameterUtils.addUserAuthArgs(params, spec);
340
341 if (spec.getKeyValidityStart() != null) {
342 params.add(KeyStore2ParameterUtils.makeDate(
343 KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart()
344 ));
345 }
346 if (spec.getKeyValidityForOriginationEnd() != null) {
347 params.add(KeyStore2ParameterUtils.makeDate(
348 KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME,
349 spec.getKeyValidityForOriginationEnd()
350 ));
351 }
352 if (spec.getKeyValidityForConsumptionEnd() != null) {
353 params.add(KeyStore2ParameterUtils.makeDate(
354 KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME,
355 spec.getKeyValidityForConsumptionEnd()
356 ));
357 }
358
359 if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0)
360 && (!spec.isRandomizedEncryptionRequired())) {
361 // Permit caller-provided IV when encrypting with this key
362 params.add(KeyStore2ParameterUtils.makeBool(
363 KeymasterDefs.KM_TAG_CALLER_NONCE
364 ));
365 }
366
367 if (spec.getMaxUsageCount() != KeyProperties.UNRESTRICTED_USAGE_COUNT) {
368 params.add(KeyStore2ParameterUtils.makeInt(
369 KeymasterDefs.KM_TAG_USAGE_COUNT_LIMIT,
370 spec.getMaxUsageCount()
371 ));
372 }
373
374 byte[] additionalEntropy =
375 KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(
376 mRng, (mKeySizeBits + 7) / 8);
377
378 @SecurityLevel int securityLevel = SecurityLevel.TRUSTED_ENVIRONMENT;
379 if (spec.isStrongBoxBacked()) {
380 securityLevel = SecurityLevel.STRONGBOX;
381 }
382
383 int flags = 0;
384 if (spec.isCriticalToDeviceEncryption()) {
385 flags |= IKeystoreSecurityLevel.KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING;
386 }
387
388 KeyDescriptor descriptor = new KeyDescriptor();
389 descriptor.alias = spec.getKeystoreAlias();
390 descriptor.nspace = spec.getNamespace();
391 descriptor.domain = descriptor.nspace == KeyProperties.NAMESPACE_APPLICATION
392 ? Domain.APP
393 : Domain.SELINUX;
394 descriptor.blob = null;
395
396 KeyMetadata metadata = null;
397 KeyStoreSecurityLevel iSecurityLevel = null;
398 try {
399 iSecurityLevel = mKeyStore.getSecurityLevel(securityLevel);
400 metadata = iSecurityLevel.generateKey(
401 descriptor,
402 null, /* Attestation key not applicable to symmetric keys. */
403 params,
404 flags,
405 additionalEntropy);
406 } catch (android.security.KeyStoreException e) {
407 switch (e.getErrorCode()) {
408 // TODO replace with ErrorCode.HARDWARE_TYPE_UNAVAILABLE when KeyMint spec
409 // becomes available.
410 case KeymasterDefs.KM_ERROR_HARDWARE_TYPE_UNAVAILABLE:
411 throw new StrongBoxUnavailableException("Failed to generate key");
412 default:
413 throw new ProviderException("Keystore key generation failed", e);
414 }
415 }
416 @KeyProperties.KeyAlgorithmEnum String keyAlgorithmJCA;
417 try {
418 keyAlgorithmJCA = KeyProperties.KeyAlgorithm.fromKeymasterSecretKeyAlgorithm(
419 mKeymasterAlgorithm, mKeymasterDigest);
420 } catch (IllegalArgumentException e) {
421 try {
422 mKeyStore.deleteKey(descriptor);
423 } catch (android.security.KeyStoreException kse) {
424 Log.e(TAG, "Failed to delete key after generating successfully but"
425 + " failed to get the algorithm string.", kse);
426 }
427 throw new ProviderException("Failed to obtain JCA secret key algorithm name", e);
428 }
429 SecretKey result = new AndroidKeyStoreSecretKey(descriptor, metadata, keyAlgorithmJCA,
430 iSecurityLevel);
431 return result;
432 }
433 }