| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package android.security.keystore2; |
| 18 |
|
| 19 |
import static android.security.keystore2.AndroidKeyStoreCipherSpiBase.DEFAULT_MGF1_DIGEST; |
| 20 |
|
| 21 |
import android.annotation.NonNull; |
| 22 |
import android.hardware.biometrics.BiometricManager; |
| 23 |
import android.hardware.security.keymint.EcCurve; |
| 24 |
import android.hardware.security.keymint.HardwareAuthenticatorType; |
| 25 |
import android.hardware.security.keymint.KeyParameter; |
| 26 |
import android.hardware.security.keymint.SecurityLevel; |
| 27 |
import android.security.GateKeeper; |
| 28 |
import android.security.KeyStore2; |
| 29 |
import android.security.KeyStoreParameter; |
| 30 |
import android.security.KeyStoreSecurityLevel; |
| 31 |
import android.security.keymaster.KeymasterDefs; |
| 32 |
import android.security.keystore.KeyGenParameterSpec; |
| 33 |
import android.security.keystore.KeyPermanentlyInvalidatedException; |
| 34 |
import android.security.keystore.KeyProperties; |
| 35 |
import android.security.keystore.KeyProtection; |
| 36 |
import android.security.keystore.SecureKeyImportUnavailableException; |
| 37 |
import android.security.keystore.WrappedKeyEntry; |
| 38 |
import android.system.keystore2.AuthenticatorSpec; |
| 39 |
import android.system.keystore2.Domain; |
| 40 |
import android.system.keystore2.IKeystoreSecurityLevel; |
| 41 |
import android.system.keystore2.KeyDescriptor; |
| 42 |
import android.system.keystore2.KeyEntryResponse; |
| 43 |
import android.system.keystore2.KeyMetadata; |
| 44 |
import android.system.keystore2.ResponseCode; |
| 45 |
import android.util.Log; |
| 46 |
|
| 47 |
import com.android.internal.annotations.VisibleForTesting; |
| 48 |
|
| 49 |
import java.io.ByteArrayInputStream; |
| 50 |
import java.io.IOException; |
| 51 |
import java.io.InputStream; |
| 52 |
import java.io.OutputStream; |
| 53 |
import java.security.Key; |
| 54 |
import java.security.KeyStore.Entry; |
| 55 |
import java.security.KeyStore.LoadStoreParameter; |
| 56 |
import java.security.KeyStore.PrivateKeyEntry; |
| 57 |
import java.security.KeyStore.ProtectionParameter; |
| 58 |
import java.security.KeyStore.SecretKeyEntry; |
| 59 |
import java.security.KeyStoreException; |
| 60 |
import java.security.KeyStoreSpi; |
| 61 |
import java.security.NoSuchAlgorithmException; |
| 62 |
import java.security.PrivateKey; |
| 63 |
import java.security.ProviderException; |
| 64 |
import java.security.UnrecoverableKeyException; |
| 65 |
import java.security.cert.Certificate; |
| 66 |
import java.security.cert.CertificateEncodingException; |
| 67 |
import java.security.cert.CertificateException; |
| 68 |
import java.security.cert.CertificateFactory; |
| 69 |
import java.security.cert.X509Certificate; |
| 70 |
import java.security.interfaces.ECKey; |
| 71 |
import java.security.interfaces.ECPrivateKey; |
| 72 |
import java.security.interfaces.EdECKey; |
| 73 |
import java.security.interfaces.EdECPrivateKey; |
| 74 |
import java.security.interfaces.XECKey; |
| 75 |
import java.security.interfaces.XECPrivateKey; |
| 76 |
import java.security.spec.AlgorithmParameterSpec; |
| 77 |
import java.security.spec.ECParameterSpec; |
| 78 |
import java.security.spec.NamedParameterSpec; |
| 79 |
import java.util.ArrayList; |
| 80 |
import java.util.Arrays; |
| 81 |
import java.util.Collection; |
| 82 |
import java.util.Date; |
| 83 |
import java.util.Enumeration; |
| 84 |
import java.util.Iterator; |
| 85 |
import java.util.List; |
| 86 |
import java.util.NoSuchElementException; |
| 87 |
|
| 88 |
import javax.crypto.SecretKey; |
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
public class AndroidKeyStoreSpi extends KeyStoreSpi { |
| 110 |
public static final String TAG = "AndroidKeyStoreSpi"; |
| 111 |
public static final String NAME = "AndroidKeyStore"; |
| 112 |
|
| 113 |
private KeyStore2 mKeyStore; |
| 114 |
private @KeyProperties.Namespace int mNamespace = KeyProperties.NAMESPACE_APPLICATION; |
| 115 |
|
| 116 |
@Override |
| 117 |
public Key engineGetKey(String alias, char[] password) throws NoSuchAlgorithmException, |
| 118 |
UnrecoverableKeyException { |
| 119 |
try { |
| 120 |
return AndroidKeyStoreProvider.loadAndroidKeyStoreKeyFromKeystore(mKeyStore, |
| 121 |
alias, |
| 122 |
mNamespace); |
| 123 |
} catch (KeyPermanentlyInvalidatedException e) { |
| 124 |
throw new UnrecoverableKeyException(e.getMessage()); |
| 125 |
} catch (UnrecoverableKeyException e) { |
| 126 |
Throwable cause = e.getCause(); |
| 127 |
if (cause instanceof android.security.KeyStoreException) { |
| 128 |
if (((android.security.KeyStoreException) cause).getErrorCode() |
| 129 |
== ResponseCode.KEY_NOT_FOUND) { |
| 130 |
return null; |
| 131 |
} |
| 132 |
} |
| 133 |
throw e; |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
private KeyDescriptor makeKeyDescriptor(@NonNull String alias) { |
| 145 |
KeyDescriptor descriptor = new KeyDescriptor(); |
| 146 |
descriptor.domain = getTargetDomain(); |
| 147 |
descriptor.nspace = mNamespace; |
| 148 |
descriptor.alias = alias; |
| 149 |
descriptor.blob = null; |
| 150 |
return descriptor; |
| 151 |
} |
| 152 |
|
| 153 |
private @Domain int getTargetDomain() { |
| 154 |
return mNamespace == KeyProperties.NAMESPACE_APPLICATION |
| 155 |
? Domain.APP |
| 156 |
: Domain.SELINUX; |
| 157 |
} |
| 158 |
private KeyEntryResponse getKeyMetadata(String alias) { |
| 159 |
if (alias == null) { |
| 160 |
throw new NullPointerException("alias == null"); |
| 161 |
} |
| 162 |
|
| 163 |
KeyDescriptor descriptor = makeKeyDescriptor(alias); |
| 164 |
|
| 165 |
try { |
| 166 |
return mKeyStore.getKeyEntry(descriptor); |
| 167 |
} catch (android.security.KeyStoreException e) { |
| 168 |
if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) { |
| 169 |
Log.w(TAG, "Could not get key metadata from Keystore.", e); |
| 170 |
} |
| 171 |
return null; |
| 172 |
} |
| 173 |
} |
| 174 |
|
| 175 |
@Override |
| 176 |
public Certificate[] engineGetCertificateChain(String alias) { |
| 177 |
KeyEntryResponse response = getKeyMetadata(alias); |
| 178 |
|
| 179 |
if (response == null || response.metadata.certificate == null) { |
| 180 |
return null; |
| 181 |
} |
| 182 |
|
| 183 |
final X509Certificate leaf = (X509Certificate) toCertificate(response.metadata.certificate); |
| 184 |
if (leaf == null) { |
| 185 |
return null; |
| 186 |
} |
| 187 |
|
| 188 |
final Certificate[] caList; |
| 189 |
|
| 190 |
final byte[] caBytes = response.metadata.certificateChain; |
| 191 |
|
| 192 |
if (caBytes != null) { |
| 193 |
final Collection<X509Certificate> caChain = toCertificates(caBytes); |
| 194 |
|
| 195 |
caList = new Certificate[caChain.size() + 1]; |
| 196 |
|
| 197 |
final Iterator<X509Certificate> it = caChain.iterator(); |
| 198 |
int i = 1; |
| 199 |
while (it.hasNext()) { |
| 200 |
caList[i++] = it.next(); |
| 201 |
} |
| 202 |
} else { |
| 203 |
caList = new Certificate[1]; |
| 204 |
} |
| 205 |
|
| 206 |
caList[0] = leaf; |
| 207 |
|
| 208 |
return caList; |
| 209 |
} |
| 210 |
|
| 211 |
@Override |
| 212 |
public Certificate engineGetCertificate(String alias) { |
| 213 |
KeyEntryResponse response = getKeyMetadata(alias); |
| 214 |
|
| 215 |
if (response == null) { |
| 216 |
return null; |
| 217 |
} |
| 218 |
|
| 219 |
byte[] encodedCert = response.metadata.certificate; |
| 220 |
if (encodedCert != null) { |
| 221 |
return toCertificate(encodedCert); |
| 222 |
} |
| 223 |
|
| 224 |
encodedCert = response.metadata.certificateChain; |
| 225 |
if (encodedCert != null) { |
| 226 |
return toCertificate(encodedCert); |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
return null; |
| 231 |
} |
| 232 |
|
| 233 |
static X509Certificate toCertificate(byte[] bytes) { |
| 234 |
try { |
| 235 |
final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); |
| 236 |
return (X509Certificate) certFactory.generateCertificate( |
| 237 |
new ByteArrayInputStream(bytes)); |
| 238 |
} catch (CertificateException e) { |
| 239 |
Log.w(NAME, "Couldn't parse certificate in keystore", e); |
| 240 |
return null; |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
@SuppressWarnings("unchecked") |
| 245 |
private static Collection<X509Certificate> toCertificates(byte[] bytes) { |
| 246 |
try { |
| 247 |
final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); |
| 248 |
return (Collection<X509Certificate>) certFactory.generateCertificates( |
| 249 |
new ByteArrayInputStream(bytes)); |
| 250 |
} catch (CertificateException e) { |
| 251 |
Log.w(NAME, "Couldn't parse certificates in keystore", e); |
| 252 |
return new ArrayList<X509Certificate>(); |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
@Override |
| 257 |
public Date engineGetCreationDate(String alias) { |
| 258 |
KeyEntryResponse response = getKeyMetadata(alias); |
| 259 |
|
| 260 |
if (response == null) { |
| 261 |
return null; |
| 262 |
} |
| 263 |
|
| 264 |
if (response.metadata.modificationTimeMs == -1) { |
| 265 |
return null; |
| 266 |
} |
| 267 |
return new Date(response.metadata.modificationTimeMs); |
| 268 |
} |
| 269 |
|
| 270 |
@Override |
| 271 |
public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) |
| 272 |
throws KeyStoreException { |
| 273 |
if ((password != null) && (password.length > 0)) { |
| 274 |
throw new KeyStoreException("entries cannot be protected with passwords"); |
| 275 |
} |
| 276 |
|
| 277 |
if (key instanceof PrivateKey) { |
| 278 |
setPrivateKeyEntry(alias, (PrivateKey) key, chain, null); |
| 279 |
} else if (key instanceof SecretKey) { |
| 280 |
setSecretKeyEntry(alias, (SecretKey) key, null); |
| 281 |
} else { |
| 282 |
throw new KeyStoreException("Only PrivateKey and SecretKey are supported"); |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
private static KeyProtection getLegacyKeyProtectionParameter(PrivateKey key) |
| 287 |
throws KeyStoreException { |
| 288 |
String keyAlgorithm = key.getAlgorithm(); |
| 289 |
KeyProtection.Builder specBuilder; |
| 290 |
if (KeyProperties.KEY_ALGORITHM_EC.equalsIgnoreCase(keyAlgorithm)) { |
| 291 |
specBuilder = |
| 292 |
new KeyProtection.Builder( |
| 293 |
KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY); |
| 294 |
|
| 295 |
|
| 296 |
specBuilder.setDigests( |
| 297 |
KeyProperties.DIGEST_NONE, |
| 298 |
KeyProperties.DIGEST_SHA1, |
| 299 |
KeyProperties.DIGEST_SHA224, |
| 300 |
KeyProperties.DIGEST_SHA256, |
| 301 |
KeyProperties.DIGEST_SHA384, |
| 302 |
KeyProperties.DIGEST_SHA512); |
| 303 |
} else if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(keyAlgorithm)) { |
| 304 |
specBuilder = |
| 305 |
new KeyProtection.Builder( |
| 306 |
KeyProperties.PURPOSE_ENCRYPT |
| 307 |
| KeyProperties.PURPOSE_DECRYPT |
| 308 |
| KeyProperties.PURPOSE_SIGN |
| 309 |
| KeyProperties.PURPOSE_VERIFY); |
| 310 |
|
| 311 |
specBuilder.setDigests( |
| 312 |
KeyProperties.DIGEST_NONE, |
| 313 |
KeyProperties.DIGEST_MD5, |
| 314 |
KeyProperties.DIGEST_SHA1, |
| 315 |
KeyProperties.DIGEST_SHA224, |
| 316 |
KeyProperties.DIGEST_SHA256, |
| 317 |
KeyProperties.DIGEST_SHA384, |
| 318 |
KeyProperties.DIGEST_SHA512); |
| 319 |
|
| 320 |
|
| 321 |
specBuilder.setEncryptionPaddings( |
| 322 |
KeyProperties.ENCRYPTION_PADDING_NONE, |
| 323 |
KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, |
| 324 |
KeyProperties.ENCRYPTION_PADDING_RSA_OAEP); |
| 325 |
specBuilder.setSignaturePaddings( |
| 326 |
KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, |
| 327 |
KeyProperties.SIGNATURE_PADDING_RSA_PSS); |
| 328 |
|
| 329 |
|
| 330 |
specBuilder.setRandomizedEncryptionRequired(false); |
| 331 |
} else { |
| 332 |
throw new KeyStoreException("Unsupported key algorithm: " + keyAlgorithm); |
| 333 |
} |
| 334 |
specBuilder.setUserAuthenticationRequired(false); |
| 335 |
|
| 336 |
return specBuilder.build(); |
| 337 |
} |
| 338 |
|
| 339 |
private void setPrivateKeyEntry(String alias, PrivateKey key, Certificate[] chain, |
| 340 |
java.security.KeyStore.ProtectionParameter param) throws KeyStoreException { |
| 341 |
@SecurityLevel int securitylevel = SecurityLevel.TRUSTED_ENVIRONMENT; |
| 342 |
int flags = 0; |
| 343 |
KeyProtection spec; |
| 344 |
if (param == null) { |
| 345 |
spec = getLegacyKeyProtectionParameter(key); |
| 346 |
} else if (param instanceof KeyStoreParameter) { |
| 347 |
spec = getLegacyKeyProtectionParameter(key); |
| 348 |
KeyStoreParameter legacySpec = (KeyStoreParameter) param; |
| 349 |
} else if (param instanceof KeyProtection) { |
| 350 |
spec = (KeyProtection) param; |
| 351 |
if (spec.isCriticalToDeviceEncryption()) { |
| 352 |
|
| 353 |
|
| 354 |
|
| 355 |
|
| 356 |
|
| 357 |
flags |= IKeystoreSecurityLevel |
| 358 |
.KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING; |
| 359 |
} |
| 360 |
|
| 361 |
if (spec.isStrongBoxBacked()) { |
| 362 |
securitylevel = SecurityLevel.STRONGBOX; |
| 363 |
} |
| 364 |
} else { |
| 365 |
throw new KeyStoreException( |
| 366 |
"Unsupported protection parameter class:" + param.getClass().getName() |
| 367 |
+ ". Supported: " + KeyProtection.class.getName() + ", " |
| 368 |
+ KeyStoreParameter.class.getName()); |
| 369 |
} |
| 370 |
|
| 371 |
|
| 372 |
if ((chain == null) || (chain.length == 0)) { |
| 373 |
throw new KeyStoreException("Must supply at least one Certificate with PrivateKey"); |
| 374 |
} |
| 375 |
|
| 376 |
|
| 377 |
X509Certificate[] x509chain = new X509Certificate[chain.length]; |
| 378 |
for (int i = 0; i < chain.length; i++) { |
| 379 |
if (!"X.509".equals(chain[i].getType())) { |
| 380 |
throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" |
| 381 |
+ i); |
| 382 |
} |
| 383 |
|
| 384 |
if (!(chain[i] instanceof X509Certificate)) { |
| 385 |
throw new KeyStoreException("Certificates must be in X.509 format: invalid cert #" |
| 386 |
+ i); |
| 387 |
} |
| 388 |
|
| 389 |
x509chain[i] = (X509Certificate) chain[i]; |
| 390 |
} |
| 391 |
|
| 392 |
final byte[] userCertBytes; |
| 393 |
try { |
| 394 |
userCertBytes = x509chain[0].getEncoded(); |
| 395 |
} catch (CertificateEncodingException e) { |
| 396 |
throw new KeyStoreException("Failed to encode certificate #0", e); |
| 397 |
} |
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
final byte[] chainBytes; |
| 405 |
if (chain.length > 1) { |
| 406 |
|
| 407 |
|
| 408 |
|
| 409 |
|
| 410 |
final byte[][] certsBytes = new byte[x509chain.length - 1][]; |
| 411 |
int totalCertLength = 0; |
| 412 |
for (int i = 0; i < certsBytes.length; i++) { |
| 413 |
try { |
| 414 |
certsBytes[i] = x509chain[i + 1].getEncoded(); |
| 415 |
totalCertLength += certsBytes[i].length; |
| 416 |
} catch (CertificateEncodingException e) { |
| 417 |
throw new KeyStoreException("Failed to encode certificate #" + i, e); |
| 418 |
} |
| 419 |
} |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
|
| 425 |
chainBytes = new byte[totalCertLength]; |
| 426 |
int outputOffset = 0; |
| 427 |
for (int i = 0; i < certsBytes.length; i++) { |
| 428 |
final int certLength = certsBytes[i].length; |
| 429 |
System.arraycopy(certsBytes[i], 0, chainBytes, outputOffset, certLength); |
| 430 |
outputOffset += certLength; |
| 431 |
certsBytes[i] = null; |
| 432 |
} |
| 433 |
} else { |
| 434 |
chainBytes = null; |
| 435 |
} |
| 436 |
|
| 437 |
@Domain int targetDomain = getTargetDomain(); |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
if (key instanceof AndroidKeyStorePrivateKey) { |
| 442 |
AndroidKeyStoreKey ksKey = (AndroidKeyStoreKey) key; |
| 443 |
KeyDescriptor descriptor = ksKey.getUserKeyDescriptor(); |
| 444 |
|
| 445 |
|
| 446 |
assertCanReplace(alias, targetDomain, mNamespace, descriptor); |
| 447 |
|
| 448 |
try { |
| 449 |
mKeyStore.updateSubcomponents( |
| 450 |
((AndroidKeyStorePrivateKey) key).getKeyIdDescriptor(), |
| 451 |
userCertBytes, chainBytes); |
| 452 |
} catch (android.security.KeyStoreException e) { |
| 453 |
throw new KeyStoreException("Failed to store certificate and certificate chain", e); |
| 454 |
} |
| 455 |
return; |
| 456 |
} |
| 457 |
|
| 458 |
|
| 459 |
final String keyFormat = key.getFormat(); |
| 460 |
if ((keyFormat == null) || (!"PKCS#8".equals(keyFormat))) { |
| 461 |
throw new KeyStoreException( |
| 462 |
"Unsupported private key export format: " + keyFormat |
| 463 |
+ ". Only private keys which export their key material in PKCS#8 format are" |
| 464 |
+ " supported."); |
| 465 |
} |
| 466 |
|
| 467 |
|
| 468 |
byte[] pkcs8EncodedPrivateKeyBytes = key.getEncoded(); |
| 469 |
if (pkcs8EncodedPrivateKeyBytes == null) { |
| 470 |
throw new KeyStoreException("Private key did not export any key material"); |
| 471 |
} |
| 472 |
|
| 473 |
final List<KeyParameter> importArgs = new ArrayList<>(); |
| 474 |
|
| 475 |
try { |
| 476 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 477 |
KeymasterDefs.KM_TAG_ALGORITHM, |
| 478 |
KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm( |
| 479 |
key.getAlgorithm())) |
| 480 |
); |
| 481 |
KeyStore2ParameterUtils.forEachSetFlag(spec.getPurposes(), (purpose) -> { |
| 482 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 483 |
KeymasterDefs.KM_TAG_PURPOSE, |
| 484 |
KeyProperties.Purpose.toKeymaster(purpose) |
| 485 |
)); |
| 486 |
}); |
| 487 |
if (spec.isDigestsSpecified()) { |
| 488 |
for (String digest : spec.getDigests()) { |
| 489 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 490 |
KeymasterDefs.KM_TAG_DIGEST, |
| 491 |
KeyProperties.Digest.toKeymaster(digest) |
| 492 |
)); |
| 493 |
} |
| 494 |
} |
| 495 |
for (String blockMode : spec.getBlockModes()) { |
| 496 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 497 |
KeymasterDefs.KM_TAG_BLOCK_MODE, |
| 498 |
KeyProperties.BlockMode.toKeymaster(blockMode) |
| 499 |
)); |
| 500 |
} |
| 501 |
int[] keymasterEncryptionPaddings = |
| 502 |
KeyProperties.EncryptionPadding.allToKeymaster( |
| 503 |
spec.getEncryptionPaddings()); |
| 504 |
if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) |
| 505 |
&& (spec.isRandomizedEncryptionRequired())) { |
| 506 |
for (int keymasterPadding : keymasterEncryptionPaddings) { |
| 507 |
if (!KeymasterUtils |
| 508 |
.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto( |
| 509 |
keymasterPadding)) { |
| 510 |
throw new KeyStoreException( |
| 511 |
"Randomized encryption (IND-CPA) required but is violated by" |
| 512 |
+ " encryption padding mode: " |
| 513 |
+ KeyProperties.EncryptionPadding.fromKeymaster( |
| 514 |
keymasterPadding) |
| 515 |
+ ". See KeyProtection documentation."); |
| 516 |
} |
| 517 |
} |
| 518 |
} |
| 519 |
for (int padding : keymasterEncryptionPaddings) { |
| 520 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 521 |
KeymasterDefs.KM_TAG_PADDING, |
| 522 |
padding |
| 523 |
)); |
| 524 |
if (padding == KeymasterDefs.KM_PAD_RSA_OAEP) { |
| 525 |
if (spec.isDigestsSpecified()) { |
| 526 |
boolean hasDefaultMgf1DigestBeenAdded = false; |
| 527 |
for (String digest : spec.getDigests()) { |
| 528 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 529 |
KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST, |
| 530 |
KeyProperties.Digest.toKeymaster(digest) |
| 531 |
)); |
| 532 |
hasDefaultMgf1DigestBeenAdded |= digest.equals(DEFAULT_MGF1_DIGEST); |
| 533 |
} |
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
if (!hasDefaultMgf1DigestBeenAdded) { |
| 539 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 540 |
KeymasterDefs.KM_TAG_RSA_OAEP_MGF_DIGEST, |
| 541 |
KeyProperties.Digest.toKeymaster(DEFAULT_MGF1_DIGEST) |
| 542 |
)); |
| 543 |
} |
| 544 |
} |
| 545 |
} |
| 546 |
} |
| 547 |
for (String padding : spec.getSignaturePaddings()) { |
| 548 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 549 |
KeymasterDefs.KM_TAG_PADDING, |
| 550 |
KeyProperties.SignaturePadding.toKeymaster(padding) |
| 551 |
)); |
| 552 |
} |
| 553 |
KeyStore2ParameterUtils.addUserAuthArgs(importArgs, spec); |
| 554 |
if (spec.getKeyValidityStart() != null) { |
| 555 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 556 |
KeymasterDefs.KM_TAG_ACTIVE_DATETIME, spec.getKeyValidityStart() |
| 557 |
)); |
| 558 |
} |
| 559 |
if (spec.getKeyValidityForOriginationEnd() != null) { |
| 560 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 561 |
KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, |
| 562 |
spec.getKeyValidityForOriginationEnd() |
| 563 |
)); |
| 564 |
} |
| 565 |
if (spec.getKeyValidityForConsumptionEnd() != null) { |
| 566 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 567 |
KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, |
| 568 |
spec.getKeyValidityForConsumptionEnd() |
| 569 |
)); |
| 570 |
} |
| 571 |
if (spec.getMaxUsageCount() != KeyProperties.UNRESTRICTED_USAGE_COUNT) { |
| 572 |
importArgs.add(KeyStore2ParameterUtils.makeInt( |
| 573 |
KeymasterDefs.KM_TAG_USAGE_COUNT_LIMIT, |
| 574 |
spec.getMaxUsageCount() |
| 575 |
)); |
| 576 |
} |
| 577 |
if (KeymasterDefs.KM_ALGORITHM_EC |
| 578 |
== KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm( |
| 579 |
key.getAlgorithm())) { |
| 580 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 581 |
KeymasterDefs.KM_TAG_EC_CURVE, |
| 582 |
getKeymasterEcCurve(key) |
| 583 |
)); |
| 584 |
} |
| 585 |
} catch (IllegalArgumentException | IllegalStateException e) { |
| 586 |
throw new KeyStoreException(e); |
| 587 |
} |
| 588 |
|
| 589 |
try { |
| 590 |
KeyStoreSecurityLevel securityLevelInterface = mKeyStore.getSecurityLevel( |
| 591 |
securitylevel); |
| 592 |
|
| 593 |
KeyDescriptor descriptor = makeKeyDescriptor(alias); |
| 594 |
|
| 595 |
KeyMetadata metadata = securityLevelInterface.importKey(descriptor, null, |
| 596 |
importArgs, flags, pkcs8EncodedPrivateKeyBytes); |
| 597 |
|
| 598 |
try { |
| 599 |
mKeyStore.updateSubcomponents(metadata.key, userCertBytes, chainBytes); |
| 600 |
} catch (android.security.KeyStoreException e) { |
| 601 |
mKeyStore.deleteKey(metadata.key); |
| 602 |
throw new KeyStoreException("Failed to store certificate and certificate chain", e); |
| 603 |
} |
| 604 |
|
| 605 |
} catch (android.security.KeyStoreException e) { |
| 606 |
throw new KeyStoreException("Failed to store private key", e); |
| 607 |
} |
| 608 |
} |
| 609 |
|
| 610 |
private int getKeymasterEcCurve(PrivateKey key) { |
| 611 |
if (key instanceof ECKey) { |
| 612 |
ECParameterSpec param = ((ECPrivateKey) key).getParams(); |
| 613 |
int kmECCurve = KeymasterUtils.getKeymasterEcCurve(KeymasterUtils.getCurveName(param)); |
| 614 |
if (kmECCurve >= 0) { |
| 615 |
return kmECCurve; |
| 616 |
} |
| 617 |
} else if (key instanceof XECKey) { |
| 618 |
AlgorithmParameterSpec param = ((XECPrivateKey) key).getParams(); |
| 619 |
if (param.equals(NamedParameterSpec.X25519)) { |
| 620 |
return EcCurve.CURVE_25519; |
| 621 |
} |
| 622 |
} else if (key.getAlgorithm().equals("XDH")) { |
| 623 |
|
| 624 |
|
| 625 |
return EcCurve.CURVE_25519; |
| 626 |
} else if (key instanceof EdECKey) { |
| 627 |
AlgorithmParameterSpec param = ((EdECPrivateKey) key).getParams(); |
| 628 |
if (param.equals(NamedParameterSpec.ED25519)) { |
| 629 |
return EcCurve.CURVE_25519; |
| 630 |
} |
| 631 |
} |
| 632 |
throw new IllegalArgumentException("Unexpected Key " + key.getClass().getName()); |
| 633 |
} |
| 634 |
|
| 635 |
private static void assertCanReplace(String alias, @Domain int targetDomain, |
| 636 |
int targetNamespace, KeyDescriptor descriptor) |
| 637 |
throws KeyStoreException { |
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
|
| 643 |
|
| 644 |
|
| 645 |
|
| 646 |
|
| 647 |
if (!alias.equals(descriptor.alias) |
| 648 |
|| descriptor.domain != targetDomain |
| 649 |
|| (descriptor.domain == Domain.SELINUX && descriptor.nspace != targetNamespace)) { |
| 650 |
throw new KeyStoreException("Can only replace keys with same alias: " + alias |
| 651 |
+ " != " + descriptor.alias + " in the same target domain: " + targetDomain |
| 652 |
+ " != " + descriptor.domain |
| 653 |
+ (targetDomain == Domain.SELINUX ? " in the same target namespace: " |
| 654 |
+ targetNamespace + " != " + descriptor.nspace : "") |
| 655 |
); |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
private void setSecretKeyEntry(String alias, SecretKey key, |
| 660 |
java.security.KeyStore.ProtectionParameter param) |
| 661 |
throws KeyStoreException { |
| 662 |
if ((param != null) && (!(param instanceof KeyProtection))) { |
| 663 |
throw new KeyStoreException( |
| 664 |
"Unsupported protection parameter class: " + param.getClass().getName() |
| 665 |
+ ". Supported: " + KeyProtection.class.getName()); |
| 666 |
} |
| 667 |
KeyProtection params = (KeyProtection) param; |
| 668 |
|
| 669 |
@Domain int targetDomain = (getTargetDomain()); |
| 670 |
|
| 671 |
if (key instanceof AndroidKeyStoreSecretKey) { |
| 672 |
String keyAliasInKeystore = |
| 673 |
((AndroidKeyStoreSecretKey) key).getUserKeyDescriptor().alias; |
| 674 |
|
| 675 |
KeyDescriptor descriptor = ((AndroidKeyStoreSecretKey) key).getUserKeyDescriptor(); |
| 676 |
|
| 677 |
|
| 678 |
assertCanReplace(alias, targetDomain, mNamespace, descriptor); |
| 679 |
|
| 680 |
|
| 681 |
if (params != null) { |
| 682 |
throw new KeyStoreException("Modifying KeyStore-backed key using protection" |
| 683 |
+ " parameters not supported"); |
| 684 |
} |
| 685 |
return; |
| 686 |
} |
| 687 |
|
| 688 |
if (params == null) { |
| 689 |
throw new KeyStoreException( |
| 690 |
"Protection parameters must be specified when importing a symmetric key"); |
| 691 |
} |
| 692 |
|
| 693 |
|
| 694 |
String keyExportFormat = key.getFormat(); |
| 695 |
if (keyExportFormat == null) { |
| 696 |
throw new KeyStoreException( |
| 697 |
"Only secret keys that export their key material are supported"); |
| 698 |
} else if (!"RAW".equals(keyExportFormat)) { |
| 699 |
throw new KeyStoreException( |
| 700 |
"Unsupported secret key material export format: " + keyExportFormat); |
| 701 |
} |
| 702 |
byte[] keyMaterial = key.getEncoded(); |
| 703 |
if (keyMaterial == null) { |
| 704 |
throw new KeyStoreException("Key did not export its key material despite supporting" |
| 705 |
+ " RAW format export"); |
| 706 |
} |
| 707 |
|
| 708 |
final List<KeyParameter> importArgs = new ArrayList<>(); |
| 709 |
|
| 710 |
try { |
| 711 |
int keymasterAlgorithm = |
| 712 |
KeyProperties.KeyAlgorithm.toKeymasterSecretKeyAlgorithm( |
| 713 |
key.getAlgorithm()); |
| 714 |
|
| 715 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 716 |
KeymasterDefs.KM_TAG_ALGORITHM, |
| 717 |
keymasterAlgorithm |
| 718 |
)); |
| 719 |
|
| 720 |
if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_HMAC) { |
| 721 |
|
| 722 |
|
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
int keymasterImpliedDigest = |
| 727 |
KeyProperties.KeyAlgorithm.toKeymasterDigest(key.getAlgorithm()); |
| 728 |
if (keymasterImpliedDigest == -1) { |
| 729 |
throw new ProviderException( |
| 730 |
"HMAC key algorithm digest unknown for key algorithm " |
| 731 |
+ key.getAlgorithm()); |
| 732 |
} |
| 733 |
|
| 734 |
if (params.isDigestsSpecified()) { |
| 735 |
|
| 736 |
|
| 737 |
int[] keymasterDigestsFromParams = |
| 738 |
KeyProperties.Digest.allToKeymaster(params.getDigests()); |
| 739 |
if ((keymasterDigestsFromParams.length != 1) |
| 740 |
|| (keymasterDigestsFromParams[0] != keymasterImpliedDigest)) { |
| 741 |
throw new KeyStoreException( |
| 742 |
"Unsupported digests specification: " |
| 743 |
+ Arrays.asList(params.getDigests()) + ". Only " |
| 744 |
+ KeyProperties.Digest.fromKeymaster(keymasterImpliedDigest) |
| 745 |
+ " supported for HMAC key algorithm " |
| 746 |
+ key.getAlgorithm()); |
| 747 |
} |
| 748 |
} |
| 749 |
int outputBits = KeymasterUtils.getDigestOutputSizeBits(keymasterImpliedDigest); |
| 750 |
if (outputBits == -1) { |
| 751 |
throw new ProviderException( |
| 752 |
"HMAC key authorized for unsupported digest: " |
| 753 |
+ KeyProperties.Digest.fromKeymaster(keymasterImpliedDigest)); |
| 754 |
} |
| 755 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 756 |
KeymasterDefs.KM_TAG_DIGEST, keymasterImpliedDigest |
| 757 |
)); |
| 758 |
importArgs.add(KeyStore2ParameterUtils.makeInt( |
| 759 |
KeymasterDefs.KM_TAG_MIN_MAC_LENGTH, outputBits |
| 760 |
)); |
| 761 |
} else { |
| 762 |
if (params.isDigestsSpecified()) { |
| 763 |
for (String digest : params.getDigests()) { |
| 764 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 765 |
KeymasterDefs.KM_TAG_DIGEST, |
| 766 |
KeyProperties.Digest.toKeymaster(digest) |
| 767 |
)); |
| 768 |
} |
| 769 |
} |
| 770 |
} |
| 771 |
|
| 772 |
KeyStore2ParameterUtils.forEachSetFlag(params.getPurposes(), (purpose) -> { |
| 773 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 774 |
KeymasterDefs.KM_TAG_PURPOSE, |
| 775 |
KeyProperties.Purpose.toKeymaster(purpose) |
| 776 |
)); |
| 777 |
}); |
| 778 |
|
| 779 |
boolean indCpa = false; |
| 780 |
if ((params.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) { |
| 781 |
if (((KeyProtection) param).isRandomizedEncryptionRequired()) { |
| 782 |
indCpa = true; |
| 783 |
} else { |
| 784 |
importArgs.add(KeyStore2ParameterUtils.makeBool( |
| 785 |
KeymasterDefs.KM_TAG_CALLER_NONCE |
| 786 |
)); |
| 787 |
} |
| 788 |
} |
| 789 |
|
| 790 |
for (String blockMode : params.getBlockModes()) { |
| 791 |
int keymasterBlockMode = KeyProperties.BlockMode.toKeymaster(blockMode); |
| 792 |
if (indCpa |
| 793 |
&& !KeymasterUtils.isKeymasterBlockModeIndCpaCompatibleWithSymmetricCrypto( |
| 794 |
keymasterBlockMode)) { |
| 795 |
throw new KeyStoreException( |
| 796 |
"Randomized encryption (IND-CPA) required but may be violated by" |
| 797 |
+ " block mode: " + blockMode |
| 798 |
+ ". See KeyProtection documentation."); |
| 799 |
|
| 800 |
} |
| 801 |
if (keymasterAlgorithm == KeymasterDefs.KM_ALGORITHM_AES |
| 802 |
&& keymasterBlockMode == KeymasterDefs.KM_MODE_GCM) { |
| 803 |
importArgs.add(KeyStore2ParameterUtils.makeInt( |
| 804 |
KeymasterDefs.KM_TAG_MIN_MAC_LENGTH, |
| 805 |
AndroidKeyStoreAuthenticatedAESCipherSpi.GCM |
| 806 |
.MIN_SUPPORTED_TAG_LENGTH_BITS |
| 807 |
)); |
| 808 |
} |
| 809 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 810 |
KeymasterDefs.KM_TAG_BLOCK_MODE, |
| 811 |
keymasterBlockMode |
| 812 |
)); |
| 813 |
} |
| 814 |
|
| 815 |
if (params.getSignaturePaddings().length > 0) { |
| 816 |
throw new KeyStoreException("Signature paddings not supported for symmetric keys"); |
| 817 |
} |
| 818 |
|
| 819 |
for (String padding : params.getEncryptionPaddings()) { |
| 820 |
importArgs.add(KeyStore2ParameterUtils.makeEnum( |
| 821 |
KeymasterDefs.KM_TAG_PADDING, |
| 822 |
KeyProperties.EncryptionPadding.toKeymaster(padding) |
| 823 |
)); |
| 824 |
} |
| 825 |
|
| 826 |
KeyStore2ParameterUtils.addUserAuthArgs(importArgs, params); |
| 827 |
|
| 828 |
if (params.getKeyValidityStart() != null) { |
| 829 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 830 |
KeymasterDefs.KM_TAG_ACTIVE_DATETIME, params.getKeyValidityStart() |
| 831 |
)); |
| 832 |
} |
| 833 |
if (params.getKeyValidityForOriginationEnd() != null) { |
| 834 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 835 |
KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, |
| 836 |
params.getKeyValidityForOriginationEnd() |
| 837 |
)); |
| 838 |
} |
| 839 |
if (params.getKeyValidityForConsumptionEnd() != null) { |
| 840 |
importArgs.add(KeyStore2ParameterUtils.makeDate( |
| 841 |
KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, |
| 842 |
params.getKeyValidityForConsumptionEnd() |
| 843 |
)); |
| 844 |
} |
| 845 |
if (params.getMaxUsageCount() != KeyProperties.UNRESTRICTED_USAGE_COUNT) { |
| 846 |
importArgs.add(KeyStore2ParameterUtils.makeInt( |
| 847 |
KeymasterDefs.KM_TAG_USAGE_COUNT_LIMIT, |
| 848 |
params.getMaxUsageCount() |
| 849 |
)); |
| 850 |
} |
| 851 |
} catch (IllegalArgumentException | IllegalStateException e) { |
| 852 |
throw new KeyStoreException(e); |
| 853 |
} |
| 854 |
|
| 855 |
int flags = 0; |
| 856 |
if (params.isCriticalToDeviceEncryption()) { |
| 857 |
flags |= IKeystoreSecurityLevel.KEY_FLAG_AUTH_BOUND_WITHOUT_CRYPTOGRAPHIC_LSKF_BINDING; |
| 858 |
} |
| 859 |
|
| 860 |
@SecurityLevel int securityLevel = params.isStrongBoxBacked() ? SecurityLevel.STRONGBOX : |
| 861 |
SecurityLevel.TRUSTED_ENVIRONMENT; |
| 862 |
|
| 863 |
try { |
| 864 |
KeyStoreSecurityLevel securityLevelInterface = mKeyStore.getSecurityLevel( |
| 865 |
securityLevel); |
| 866 |
|
| 867 |
KeyDescriptor descriptor = makeKeyDescriptor(alias); |
| 868 |
|
| 869 |
securityLevelInterface.importKey(descriptor, null , |
| 870 |
importArgs, flags, keyMaterial); |
| 871 |
} catch (android.security.KeyStoreException e) { |
| 872 |
throw new KeyStoreException("Failed to import secret key.", e); |
| 873 |
} |
| 874 |
} |
| 875 |
|
| 876 |
private void setWrappedKeyEntry(String alias, WrappedKeyEntry entry, |
| 877 |
java.security.KeyStore.ProtectionParameter param) throws KeyStoreException { |
| 878 |
if (param != null) { |
| 879 |
throw new KeyStoreException("Protection parameters are specified inside wrapped keys"); |
| 880 |
} |
| 881 |
|
| 882 |
byte[] maskingKey = new byte[32]; |
| 883 |
|
| 884 |
String[] parts = entry.getTransformation().split("/"); |
| 885 |
|
| 886 |
List<KeyParameter> args = new ArrayList<>(); |
| 887 |
|
| 888 |
String algorithm = parts[0]; |
| 889 |
if (KeyProperties.KEY_ALGORITHM_RSA.equalsIgnoreCase(algorithm)) { |
| 890 |
args.add(KeyStore2ParameterUtils.makeEnum( |
| 891 |
KeymasterDefs.KM_TAG_ALGORITHM, |
| 892 |
KeymasterDefs.KM_ALGORITHM_RSA |
| 893 |
)); |
| 894 |
} else { |
| 895 |
throw new KeyStoreException("Algorithm \"" + algorithm + "\" not supported for " |
| 896 |
+ "wrapping. Only RSA wrapping keys are supported."); |
| 897 |
} |
| 898 |
|
| 899 |
if (parts.length > 1) { |
| 900 |
String mode = parts[1]; |
| 901 |
args.add(KeyStore2ParameterUtils.makeEnum( |
| 902 |
KeymasterDefs.KM_TAG_BLOCK_MODE, |
| 903 |
KeyProperties.BlockMode.toKeymaster(mode) |
| 904 |
)); |
| 905 |
} |
| 906 |
|
| 907 |
if (parts.length > 2) { |
| 908 |
@KeyProperties.EncryptionPaddingEnum int padding = |
| 909 |
KeyProperties.EncryptionPadding.toKeymaster(parts[2]); |
| 910 |
if (padding != KeymasterDefs.KM_PAD_NONE) { |
| 911 |
args.add(KeyStore2ParameterUtils.makeEnum( |
| 912 |
KeymasterDefs.KM_TAG_PADDING, |
| 913 |
padding |
| 914 |
)); |
| 915 |
} |
| 916 |
} |
| 917 |
|
| 918 |
KeyGenParameterSpec spec = (KeyGenParameterSpec) entry.getAlgorithmParameterSpec(); |
| 919 |
if (spec.isDigestsSpecified()) { |
| 920 |
@KeyProperties.DigestEnum int digest = |
| 921 |
KeyProperties.Digest.toKeymaster(spec.getDigests()[0]); |
| 922 |
if (digest != KeymasterDefs.KM_DIGEST_NONE) { |
| 923 |
args.add(KeyStore2ParameterUtils.makeEnum( |
| 924 |
KeymasterDefs.KM_TAG_DIGEST, |
| 925 |
digest |
| 926 |
)); |
| 927 |
} |
| 928 |
} |
| 929 |
|
| 930 |
KeyDescriptor wrappingkey = makeKeyDescriptor(entry.getWrappingKeyAlias()); |
| 931 |
|
| 932 |
KeyEntryResponse response = null; |
| 933 |
try { |
| 934 |
response = mKeyStore.getKeyEntry(wrappingkey); |
| 935 |
} catch (android.security.KeyStoreException e) { |
| 936 |
throw new KeyStoreException("Failed to import wrapped key. Keystore error code: " |
| 937 |
+ e.getErrorCode(), e); |
| 938 |
} |
| 939 |
|
| 940 |
KeyDescriptor wrappedKey = makeKeyDescriptor(alias); |
| 941 |
|
| 942 |
KeyStoreSecurityLevel securityLevel = new KeyStoreSecurityLevel(response.iSecurityLevel); |
| 943 |
|
| 944 |
final BiometricManager bm = android.app.AppGlobals.getInitialApplication() |
| 945 |
.getSystemService(BiometricManager.class); |
| 946 |
|
| 947 |
long[] biometricSids = bm.getAuthenticatorIds(); |
| 948 |
|
| 949 |
List<AuthenticatorSpec> authenticatorSpecs = new ArrayList<>(); |
| 950 |
|
| 951 |
AuthenticatorSpec authenticatorSpec = new AuthenticatorSpec(); |
| 952 |
authenticatorSpec.authenticatorType = HardwareAuthenticatorType.PASSWORD; |
| 953 |
authenticatorSpec.authenticatorId = GateKeeper.getSecureUserId(); |
| 954 |
authenticatorSpecs.add(authenticatorSpec); |
| 955 |
|
| 956 |
for (long sid : biometricSids) { |
| 957 |
AuthenticatorSpec authSpec = new AuthenticatorSpec(); |
| 958 |
authSpec.authenticatorType = HardwareAuthenticatorType.FINGERPRINT; |
| 959 |
authSpec.authenticatorId = sid; |
| 960 |
authenticatorSpecs.add(authSpec); |
| 961 |
} |
| 962 |
|
| 963 |
try { |
| 964 |
securityLevel.importWrappedKey( |
| 965 |
wrappedKey, wrappingkey, |
| 966 |
entry.getWrappedKeyBytes(), |
| 967 |
null , |
| 968 |
args, |
| 969 |
authenticatorSpecs.toArray(new AuthenticatorSpec[0])); |
| 970 |
} catch (android.security.KeyStoreException e) { |
| 971 |
switch (e.getErrorCode()) { |
| 972 |
case KeymasterDefs.KM_ERROR_UNIMPLEMENTED: { |
| 973 |
throw new SecureKeyImportUnavailableException("Could not import wrapped key"); |
| 974 |
} |
| 975 |
default: |
| 976 |
throw new KeyStoreException("Failed to import wrapped key. Keystore error " |
| 977 |
+ "code: " + e.getErrorCode(), e); |
| 978 |
} |
| 979 |
} |
| 980 |
} |
| 981 |
|
| 982 |
@Override |
| 983 |
public void engineSetKeyEntry(String alias, byte[] userKey, Certificate[] chain) |
| 984 |
throws KeyStoreException { |
| 985 |
throw new KeyStoreException("Operation not supported because key encoding is unknown"); |
| 986 |
} |
| 987 |
|
| 988 |
|
| 989 |
|
| 990 |
|
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
|
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
|
| 1005 |
@Override |
| 1006 |
public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { |
| 1007 |
if (isKeyEntry(alias)) { |
| 1008 |
throw new KeyStoreException("Entry exists and is not a trusted certificate"); |
| 1009 |
} |
| 1010 |
|
| 1011 |
|
| 1012 |
if (cert == null) { |
| 1013 |
throw new NullPointerException("cert == null"); |
| 1014 |
} |
| 1015 |
|
| 1016 |
final byte[] encoded; |
| 1017 |
try { |
| 1018 |
encoded = cert.getEncoded(); |
| 1019 |
} catch (CertificateEncodingException e) { |
| 1020 |
throw new KeyStoreException(e); |
| 1021 |
} |
| 1022 |
|
| 1023 |
try { |
| 1024 |
mKeyStore.updateSubcomponents(makeKeyDescriptor(alias), |
| 1025 |
null , |
| 1026 |
encoded); |
| 1027 |
} catch (android.security.KeyStoreException e) { |
| 1028 |
throw new KeyStoreException("Couldn't insert certificate.", e); |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
@Override |
| 1033 |
public void engineDeleteEntry(String alias) throws KeyStoreException { |
| 1034 |
KeyDescriptor descriptor = makeKeyDescriptor(alias); |
| 1035 |
try { |
| 1036 |
mKeyStore.deleteKey(descriptor); |
| 1037 |
} catch (android.security.KeyStoreException e) { |
| 1038 |
if (e.getErrorCode() != ResponseCode.KEY_NOT_FOUND) { |
| 1039 |
throw new KeyStoreException("Failed to delete entry: " + alias, e); |
| 1040 |
} |
| 1041 |
} |
| 1042 |
} |
| 1043 |
|
| 1044 |
private KeyDescriptor[] getAliasesBatch(String startPastAlias) { |
| 1045 |
try { |
| 1046 |
return mKeyStore.listBatch( |
| 1047 |
getTargetDomain(), |
| 1048 |
mNamespace, |
| 1049 |
startPastAlias |
| 1050 |
); |
| 1051 |
} catch (android.security.KeyStoreException e) { |
| 1052 |
Log.e(TAG, "Failed to list keystore entries.", e); |
| 1053 |
return new KeyDescriptor[0]; |
| 1054 |
} |
| 1055 |
} |
| 1056 |
|
| 1057 |
@Override |
| 1058 |
public Enumeration<String> engineAliases() { |
| 1059 |
return new KeyEntriesEnumerator(); |
| 1060 |
} |
| 1061 |
|
| 1062 |
@Override |
| 1063 |
public boolean engineContainsAlias(String alias) { |
| 1064 |
if (alias == null) { |
| 1065 |
throw new NullPointerException("alias == null"); |
| 1066 |
} |
| 1067 |
|
| 1068 |
return getKeyMetadata(alias) != null; |
| 1069 |
} |
| 1070 |
@Override |
| 1071 |
public int engineSize() { |
| 1072 |
try { |
| 1073 |
return mKeyStore.getNumberOfEntries( |
| 1074 |
getTargetDomain(), |
| 1075 |
mNamespace |
| 1076 |
); |
| 1077 |
} catch (android.security.KeyStoreException e) { |
| 1078 |
Log.e(TAG, "Failed to get the number of keystore entries.", e); |
| 1079 |
return 0; |
| 1080 |
} |
| 1081 |
} |
| 1082 |
@Override |
| 1083 |
public boolean engineIsKeyEntry(String alias) { |
| 1084 |
return isKeyEntry(alias); |
| 1085 |
} |
| 1086 |
|
| 1087 |
private boolean isKeyEntry(String alias) { |
| 1088 |
if (alias == null) { |
| 1089 |
throw new NullPointerException("alias == null"); |
| 1090 |
} |
| 1091 |
|
| 1092 |
KeyEntryResponse response = getKeyMetadata(alias); |
| 1093 |
|
| 1094 |
|
| 1095 |
return response != null && response.iSecurityLevel != null; |
| 1096 |
} |
| 1097 |
|
| 1098 |
|
| 1099 |
@Override |
| 1100 |
public boolean engineIsCertificateEntry(String alias) { |
| 1101 |
if (alias == null) { |
| 1102 |
throw new NullPointerException("alias == null"); |
| 1103 |
} |
| 1104 |
KeyEntryResponse response = getKeyMetadata(alias); |
| 1105 |
|
| 1106 |
|
| 1107 |
|
| 1108 |
|
| 1109 |
return response != null |
| 1110 |
&& response.metadata.certificateChain != null |
| 1111 |
&& response.iSecurityLevel == null; |
| 1112 |
} |
| 1113 |
|
| 1114 |
@Override |
| 1115 |
public String engineGetCertificateAlias(Certificate cert) { |
| 1116 |
if (cert == null) { |
| 1117 |
return null; |
| 1118 |
} |
| 1119 |
if (!"X.509".equalsIgnoreCase(cert.getType())) { |
| 1120 |
Log.e(TAG, "In engineGetCertificateAlias: only X.509 certificates are supported."); |
| 1121 |
return null; |
| 1122 |
} |
| 1123 |
byte[] targetCertBytes; |
| 1124 |
try { |
| 1125 |
targetCertBytes = cert.getEncoded(); |
| 1126 |
} catch (CertificateEncodingException e) { |
| 1127 |
Log.e(TAG, "While trying to get the alias for a certificate.", e); |
| 1128 |
return null; |
| 1129 |
} |
| 1130 |
if (targetCertBytes == null) { |
| 1131 |
return null; |
| 1132 |
} |
| 1133 |
|
| 1134 |
KeyDescriptor[] keyDescriptors = null; |
| 1135 |
try { |
| 1136 |
keyDescriptors = mKeyStore.list( |
| 1137 |
getTargetDomain(), |
| 1138 |
mNamespace |
| 1139 |
); |
| 1140 |
} catch (android.security.KeyStoreException e) { |
| 1141 |
Log.w(TAG, "Failed to get list of keystore entries.", e); |
| 1142 |
} |
| 1143 |
|
| 1144 |
String caAlias = null; |
| 1145 |
for (KeyDescriptor d : keyDescriptors) { |
| 1146 |
KeyEntryResponse response = getKeyMetadata(d.alias); |
| 1147 |
if (response == null) { |
| 1148 |
continue; |
| 1149 |
} |
| 1150 |
|
| 1151 |
|
| 1152 |
|
| 1153 |
|
| 1154 |
|
| 1155 |
|
| 1156 |
|
| 1157 |
|
| 1158 |
if (response.metadata.certificate != null) { |
| 1159 |
if (Arrays.equals(response.metadata.certificate, targetCertBytes)) { |
| 1160 |
return d.alias; |
| 1161 |
} |
| 1162 |
} else if (response.metadata.certificateChain != null && caAlias == null) { |
| 1163 |
if (Arrays.equals(response.metadata.certificateChain, targetCertBytes)) { |
| 1164 |
caAlias = d.alias; |
| 1165 |
} |
| 1166 |
} |
| 1167 |
} |
| 1168 |
return caAlias; |
| 1169 |
} |
| 1170 |
|
| 1171 |
|
| 1172 |
|
| 1173 |
|
| 1174 |
|
| 1175 |
|
| 1176 |
@VisibleForTesting |
| 1177 |
public void initForTesting(KeyStore2 keystore) { |
| 1178 |
mKeyStore = keystore; |
| 1179 |
mNamespace = KeyProperties.NAMESPACE_APPLICATION; |
| 1180 |
} |
| 1181 |
|
| 1182 |
@Override |
| 1183 |
public void engineStore(OutputStream stream, char[] password) throws IOException, |
| 1184 |
NoSuchAlgorithmException, CertificateException { |
| 1185 |
throw new UnsupportedOperationException("Can not serialize AndroidKeyStore to OutputStream"); |
| 1186 |
} |
| 1187 |
|
| 1188 |
@Override |
| 1189 |
public void engineLoad(InputStream stream, char[] password) throws IOException, |
| 1190 |
NoSuchAlgorithmException, CertificateException { |
| 1191 |
if (stream != null) { |
| 1192 |
throw new IllegalArgumentException("InputStream not supported"); |
| 1193 |
} |
| 1194 |
|
| 1195 |
if (password != null) { |
| 1196 |
throw new IllegalArgumentException("password not supported"); |
| 1197 |
} |
| 1198 |
|
| 1199 |
|
| 1200 |
mKeyStore = KeyStore2.getInstance(); |
| 1201 |
mNamespace = KeyProperties.NAMESPACE_APPLICATION; |
| 1202 |
} |
| 1203 |
|
| 1204 |
@Override |
| 1205 |
public void engineLoad(LoadStoreParameter param) throws IOException, |
| 1206 |
NoSuchAlgorithmException, CertificateException { |
| 1207 |
@KeyProperties.Namespace int namespace = KeyProperties.NAMESPACE_APPLICATION; |
| 1208 |
if (param != null) { |
| 1209 |
if (param instanceof AndroidKeyStoreLoadStoreParameter) { |
| 1210 |
namespace = ((AndroidKeyStoreLoadStoreParameter) param).getNamespace(); |
| 1211 |
} else { |
| 1212 |
throw new IllegalArgumentException( |
| 1213 |
"Unsupported param type: " + param.getClass()); |
| 1214 |
} |
| 1215 |
} |
| 1216 |
mKeyStore = KeyStore2.getInstance(); |
| 1217 |
mNamespace = namespace; |
| 1218 |
} |
| 1219 |
|
| 1220 |
@Override |
| 1221 |
public void engineSetEntry(String alias, Entry entry, ProtectionParameter param) |
| 1222 |
throws KeyStoreException { |
| 1223 |
if (entry == null) { |
| 1224 |
throw new KeyStoreException("entry == null"); |
| 1225 |
} |
| 1226 |
|
| 1227 |
if (entry instanceof java.security.KeyStore.TrustedCertificateEntry) { |
| 1228 |
java.security.KeyStore.TrustedCertificateEntry trE = |
| 1229 |
(java.security.KeyStore.TrustedCertificateEntry) entry; |
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
|
| 1234 |
engineDeleteEntry(alias); |
| 1235 |
engineSetCertificateEntry(alias, trE.getTrustedCertificate()); |
| 1236 |
return; |
| 1237 |
} |
| 1238 |
|
| 1239 |
if (entry instanceof PrivateKeyEntry) { |
| 1240 |
PrivateKeyEntry prE = (PrivateKeyEntry) entry; |
| 1241 |
setPrivateKeyEntry(alias, prE.getPrivateKey(), prE.getCertificateChain(), param); |
| 1242 |
} else if (entry instanceof SecretKeyEntry) { |
| 1243 |
SecretKeyEntry secE = (SecretKeyEntry) entry; |
| 1244 |
setSecretKeyEntry(alias, secE.getSecretKey(), param); |
| 1245 |
} else if (entry instanceof WrappedKeyEntry) { |
| 1246 |
WrappedKeyEntry wke = (WrappedKeyEntry) entry; |
| 1247 |
setWrappedKeyEntry(alias, wke, param); |
| 1248 |
} else { |
| 1249 |
throw new KeyStoreException( |
| 1250 |
"Entry must be a PrivateKeyEntry, SecretKeyEntry, WrappedKeyEntry " |
| 1251 |
+ "or TrustedCertificateEntry; was " + entry); |
| 1252 |
} |
| 1253 |
} |
| 1254 |
|
| 1255 |
private class KeyEntriesEnumerator implements Enumeration<String> { |
| 1256 |
private KeyDescriptor[] mCurrentBatch; |
| 1257 |
private int mCurrentEntry = 0; |
| 1258 |
private String mLastAlias = null; |
| 1259 |
private KeyEntriesEnumerator() { |
| 1260 |
getAndValidateNextBatch(); |
| 1261 |
} |
| 1262 |
|
| 1263 |
private void getAndValidateNextBatch() { |
| 1264 |
mCurrentBatch = getAliasesBatch(mLastAlias); |
| 1265 |
mCurrentEntry = 0; |
| 1266 |
} |
| 1267 |
|
| 1268 |
public boolean hasMoreElements() { |
| 1269 |
return (mCurrentBatch != null) && (mCurrentBatch.length > 0); |
| 1270 |
} |
| 1271 |
|
| 1272 |
public String nextElement() { |
| 1273 |
if ((mCurrentBatch == null) || (mCurrentBatch.length == 0)) { |
| 1274 |
throw new NoSuchElementException("Error while fetching entries."); |
| 1275 |
} |
| 1276 |
final KeyDescriptor currentEntry = mCurrentBatch[mCurrentEntry]; |
| 1277 |
mLastAlias = currentEntry.alias; |
| 1278 |
|
| 1279 |
mCurrentEntry++; |
| 1280 |
|
| 1281 |
if (mCurrentEntry >= mCurrentBatch.length) { |
| 1282 |
getAndValidateNextBatch(); |
| 1283 |
} |
| 1284 |
|
| 1285 |
return mLastAlias; |
| 1286 |
} |
| 1287 |
} |
| 1288 |
} |