Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2012 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 | |
Alex Klyubin | dcdaf87 | 2015-05-13 15:57:09 -0700 | [diff] [blame] | 17 | package android.security.keystore; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 18 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 19 | import android.annotation.Nullable; |
Alex Klyubin | dcdaf87 | 2015-05-13 15:57:09 -0700 | [diff] [blame] | 20 | import android.security.Credentials; |
Rubin Xu | 59ced28 | 2017-01-30 23:39:12 +0000 | [diff] [blame] | 21 | import android.security.GateKeeper; |
Alex Klyubin | dcdaf87 | 2015-05-13 15:57:09 -0700 | [diff] [blame] | 22 | import android.security.KeyPairGeneratorSpec; |
| 23 | import android.security.KeyStore; |
Frank Salim | ea5e038 | 2018-01-23 22:42:29 -0800 | [diff] [blame] | 24 | import android.security.KeyStoreException; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 25 | import android.security.keymaster.KeyCharacteristics; |
| 26 | import android.security.keymaster.KeymasterArguments; |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 27 | import android.security.keymaster.KeymasterCertificateChain; |
Alex Klyubin | 4350bab | 2015-06-08 10:14:58 -0700 | [diff] [blame] | 28 | import android.security.keymaster.KeymasterDefs; |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 29 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 30 | import com.android.org.bouncycastle.asn1.ASN1EncodableVector; |
| 31 | import com.android.org.bouncycastle.asn1.ASN1InputStream; |
| 32 | import com.android.org.bouncycastle.asn1.ASN1Integer; |
| 33 | import com.android.org.bouncycastle.asn1.ASN1ObjectIdentifier; |
| 34 | import com.android.org.bouncycastle.asn1.DERBitString; |
| 35 | import com.android.org.bouncycastle.asn1.DERInteger; |
| 36 | import com.android.org.bouncycastle.asn1.DERNull; |
| 37 | import com.android.org.bouncycastle.asn1.DERSequence; |
| 38 | import com.android.org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; |
| 39 | import com.android.org.bouncycastle.asn1.x509.AlgorithmIdentifier; |
| 40 | import com.android.org.bouncycastle.asn1.x509.Certificate; |
| 41 | import com.android.org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; |
| 42 | import com.android.org.bouncycastle.asn1.x509.TBSCertificate; |
| 43 | import com.android.org.bouncycastle.asn1.x509.Time; |
| 44 | import com.android.org.bouncycastle.asn1.x509.V3TBSCertificateGenerator; |
| 45 | import com.android.org.bouncycastle.asn1.x9.X9ObjectIdentifiers; |
| 46 | import com.android.org.bouncycastle.jce.X509Principal; |
| 47 | import com.android.org.bouncycastle.jce.provider.X509CertificateObject; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 48 | import com.android.org.bouncycastle.x509.X509V3CertificateGenerator; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 49 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 50 | import libcore.util.EmptyArray; |
| 51 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 52 | import java.io.ByteArrayOutputStream; |
| 53 | import java.io.IOException; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 54 | import java.math.BigInteger; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 55 | import java.security.InvalidAlgorithmParameterException; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 56 | import java.security.KeyPair; |
| 57 | import java.security.KeyPairGenerator; |
| 58 | import java.security.KeyPairGeneratorSpi; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 59 | import java.security.PrivateKey; |
Alex Klyubin | 4350bab | 2015-06-08 10:14:58 -0700 | [diff] [blame] | 60 | import java.security.ProviderException; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 61 | import java.security.PublicKey; |
| 62 | import java.security.SecureRandom; |
Alex Klyubin | 4a0ff7c | 2015-06-09 13:25:20 -0700 | [diff] [blame] | 63 | import java.security.UnrecoverableKeyException; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 64 | import java.security.cert.CertificateEncodingException; |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 65 | import java.security.cert.CertificateParsingException; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 66 | import java.security.cert.X509Certificate; |
| 67 | import java.security.spec.AlgorithmParameterSpec; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 68 | import java.security.spec.ECGenParameterSpec; |
Kenny Root | f64386f | 2013-08-16 14:03:29 -0700 | [diff] [blame] | 69 | import java.security.spec.RSAKeyGenParameterSpec; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 70 | import java.util.ArrayList; |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 71 | import java.util.Collection; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 72 | import java.util.Collections; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 73 | import java.util.HashMap; |
| 74 | import java.util.HashSet; |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 75 | import java.util.Iterator; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 76 | import java.util.List; |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 77 | import java.util.Locale; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 78 | import java.util.Map; |
| 79 | import java.util.Set; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 80 | |
| 81 | /** |
| 82 | * Provides a way to create instances of a KeyPair which will be placed in the |
| 83 | * Android keystore service usable only by the application that called it. This |
| 84 | * can be used in conjunction with |
| 85 | * {@link java.security.KeyStore#getInstance(String)} using the |
| 86 | * {@code "AndroidKeyStore"} type. |
| 87 | * <p> |
| 88 | * This class can not be directly instantiated and must instead be used via the |
| 89 | * {@link KeyPairGenerator#getInstance(String) |
Alex Klyubin | e21f023 | 2015-05-19 09:41:17 -0700 | [diff] [blame] | 90 | * KeyPairGenerator.getInstance("AndroidKeyStore")} API. |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 91 | * |
Alex Klyubin | e21f023 | 2015-05-19 09:41:17 -0700 | [diff] [blame] | 92 | * @hide |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 93 | */ |
Alex Klyubin | e21f023 | 2015-05-19 09:41:17 -0700 | [diff] [blame] | 94 | public abstract class AndroidKeyStoreKeyPairGeneratorSpi extends KeyPairGeneratorSpi { |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 95 | |
Alex Klyubin | e21f023 | 2015-05-19 09:41:17 -0700 | [diff] [blame] | 96 | public static class RSA extends AndroidKeyStoreKeyPairGeneratorSpi { |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 97 | public RSA() { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 98 | super(KeymasterDefs.KM_ALGORITHM_RSA); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 99 | } |
| 100 | } |
| 101 | |
Alex Klyubin | e21f023 | 2015-05-19 09:41:17 -0700 | [diff] [blame] | 102 | public static class EC extends AndroidKeyStoreKeyPairGeneratorSpi { |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 103 | public EC() { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 104 | super(KeymasterDefs.KM_ALGORITHM_EC); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 105 | } |
| 106 | } |
| 107 | |
| 108 | /* |
| 109 | * These must be kept in sync with system/security/keystore/defaults.h |
| 110 | */ |
| 111 | |
| 112 | /* EC */ |
| 113 | private static final int EC_DEFAULT_KEY_SIZE = 256; |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 114 | |
| 115 | /* RSA */ |
| 116 | private static final int RSA_DEFAULT_KEY_SIZE = 2048; |
| 117 | private static final int RSA_MIN_KEY_SIZE = 512; |
| 118 | private static final int RSA_MAX_KEY_SIZE = 8192; |
| 119 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 120 | private static final Map<String, Integer> SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE = |
| 121 | new HashMap<String, Integer>(); |
| 122 | private static final List<String> SUPPORTED_EC_NIST_CURVE_NAMES = new ArrayList<String>(); |
Alex Klyubin | bf5c91c | 2015-06-17 10:51:19 -0700 | [diff] [blame] | 123 | private static final List<Integer> SUPPORTED_EC_NIST_CURVE_SIZES = new ArrayList<Integer>(); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 124 | static { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 125 | // Aliases for NIST P-224 |
| 126 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-224", 224); |
| 127 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp224r1", 224); |
| 128 | |
Alex Klyubin | bf5c91c | 2015-06-17 10:51:19 -0700 | [diff] [blame] | 129 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 130 | // Aliases for NIST P-256 |
| 131 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-256", 256); |
| 132 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp256r1", 256); |
| 133 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("prime256v1", 256); |
| 134 | |
| 135 | // Aliases for NIST P-384 |
| 136 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-384", 384); |
| 137 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp384r1", 384); |
| 138 | |
| 139 | // Aliases for NIST P-521 |
| 140 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("p-521", 521); |
| 141 | SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.put("secp521r1", 521); |
| 142 | |
| 143 | SUPPORTED_EC_NIST_CURVE_NAMES.addAll(SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.keySet()); |
| 144 | Collections.sort(SUPPORTED_EC_NIST_CURVE_NAMES); |
Alex Klyubin | bf5c91c | 2015-06-17 10:51:19 -0700 | [diff] [blame] | 145 | |
| 146 | SUPPORTED_EC_NIST_CURVE_SIZES.addAll( |
| 147 | new HashSet<Integer>(SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.values())); |
| 148 | Collections.sort(SUPPORTED_EC_NIST_CURVE_SIZES); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 149 | } |
Alex Klyubin | 4a0ff7c | 2015-06-09 13:25:20 -0700 | [diff] [blame] | 150 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 151 | private final int mOriginalKeymasterAlgorithm; |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 152 | |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 153 | private KeyStore mKeyStore; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 154 | |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 155 | private KeyGenParameterSpec mSpec; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 156 | |
| 157 | private String mEntryAlias; |
Alex Klyubin | 3876b1b | 2015-09-09 14:55:03 -0700 | [diff] [blame] | 158 | private int mEntryUid; |
Alex Klyubin | 96481c3 | 2015-05-15 10:47:18 -0700 | [diff] [blame] | 159 | private boolean mEncryptionAtRestRequired; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 160 | private @KeyProperties.KeyAlgorithmEnum String mJcaKeyAlgorithm; |
| 161 | private int mKeymasterAlgorithm = -1; |
| 162 | private int mKeySizeBits; |
| 163 | private SecureRandom mRng; |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 164 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 165 | private int[] mKeymasterPurposes; |
| 166 | private int[] mKeymasterBlockModes; |
| 167 | private int[] mKeymasterEncryptionPaddings; |
| 168 | private int[] mKeymasterSignaturePaddings; |
| 169 | private int[] mKeymasterDigests; |
| 170 | |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 171 | private BigInteger mRSAPublicExponent; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 172 | |
| 173 | protected AndroidKeyStoreKeyPairGeneratorSpi(int keymasterAlgorithm) { |
| 174 | mOriginalKeymasterAlgorithm = keymasterAlgorithm; |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 175 | } |
| 176 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 177 | @SuppressWarnings("deprecation") |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 178 | @Override |
| 179 | public void initialize(int keysize, SecureRandom random) { |
| 180 | throw new IllegalArgumentException( |
| 181 | KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName() |
| 182 | + " required to initialize this KeyPairGenerator"); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 183 | } |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 184 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 185 | @SuppressWarnings("deprecation") |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 186 | @Override |
| 187 | public void initialize(AlgorithmParameterSpec params, SecureRandom random) |
| 188 | throws InvalidAlgorithmParameterException { |
| 189 | resetAll(); |
| 190 | |
| 191 | boolean success = false; |
| 192 | try { |
| 193 | if (params == null) { |
| 194 | throw new InvalidAlgorithmParameterException( |
| 195 | "Must supply params of type " + KeyGenParameterSpec.class.getName() |
| 196 | + " or " + KeyPairGeneratorSpec.class.getName()); |
| 197 | } |
| 198 | |
| 199 | KeyGenParameterSpec spec; |
| 200 | boolean encryptionAtRestRequired = false; |
| 201 | int keymasterAlgorithm = mOriginalKeymasterAlgorithm; |
| 202 | if (params instanceof KeyGenParameterSpec) { |
| 203 | spec = (KeyGenParameterSpec) params; |
| 204 | } else if (params instanceof KeyPairGeneratorSpec) { |
| 205 | // Legacy/deprecated spec |
| 206 | KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params; |
| 207 | try { |
| 208 | KeyGenParameterSpec.Builder specBuilder; |
| 209 | String specKeyAlgorithm = legacySpec.getKeyType(); |
| 210 | if (specKeyAlgorithm != null) { |
| 211 | // Spec overrides the generator's default key algorithm |
| 212 | try { |
| 213 | keymasterAlgorithm = |
| 214 | KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm( |
| 215 | specKeyAlgorithm); |
| 216 | } catch (IllegalArgumentException e) { |
| 217 | throw new InvalidAlgorithmParameterException( |
| 218 | "Invalid key type in parameters", e); |
| 219 | } |
| 220 | } |
| 221 | switch (keymasterAlgorithm) { |
| 222 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 223 | specBuilder = new KeyGenParameterSpec.Builder( |
| 224 | legacySpec.getKeystoreAlias(), |
| 225 | KeyProperties.PURPOSE_SIGN |
| 226 | | KeyProperties.PURPOSE_VERIFY); |
Alex Klyubin | dcf3d35 | 2015-06-11 14:44:46 -0700 | [diff] [blame] | 227 | // Authorized to be used with any digest (including no digest). |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 228 | // MD5 was never offered for Android Keystore for ECDSA. |
| 229 | specBuilder.setDigests( |
| 230 | KeyProperties.DIGEST_NONE, |
| 231 | KeyProperties.DIGEST_SHA1, |
| 232 | KeyProperties.DIGEST_SHA224, |
| 233 | KeyProperties.DIGEST_SHA256, |
| 234 | KeyProperties.DIGEST_SHA384, |
| 235 | KeyProperties.DIGEST_SHA512); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 236 | break; |
| 237 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 238 | specBuilder = new KeyGenParameterSpec.Builder( |
| 239 | legacySpec.getKeystoreAlias(), |
| 240 | KeyProperties.PURPOSE_ENCRYPT |
| 241 | | KeyProperties.PURPOSE_DECRYPT |
| 242 | | KeyProperties.PURPOSE_SIGN |
| 243 | | KeyProperties.PURPOSE_VERIFY); |
Alex Klyubin | dcf3d35 | 2015-06-11 14:44:46 -0700 | [diff] [blame] | 244 | // Authorized to be used with any digest (including no digest). |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 245 | specBuilder.setDigests( |
| 246 | KeyProperties.DIGEST_NONE, |
| 247 | KeyProperties.DIGEST_MD5, |
| 248 | KeyProperties.DIGEST_SHA1, |
| 249 | KeyProperties.DIGEST_SHA224, |
| 250 | KeyProperties.DIGEST_SHA256, |
| 251 | KeyProperties.DIGEST_SHA384, |
| 252 | KeyProperties.DIGEST_SHA512); |
Alex Klyubin | 2e3aaa7 | 2015-06-17 13:58:00 -0700 | [diff] [blame] | 253 | // Authorized to be used with any encryption and signature padding |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 254 | // schemes (including no padding). |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 255 | specBuilder.setEncryptionPaddings( |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 256 | KeyProperties.ENCRYPTION_PADDING_NONE, |
| 257 | KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, |
| 258 | KeyProperties.ENCRYPTION_PADDING_RSA_OAEP); |
| 259 | specBuilder.setSignaturePaddings( |
| 260 | KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, |
| 261 | KeyProperties.SIGNATURE_PADDING_RSA_PSS); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 262 | // Disable randomized encryption requirement to support encryption |
| 263 | // padding NONE above. |
| 264 | specBuilder.setRandomizedEncryptionRequired(false); |
| 265 | break; |
| 266 | default: |
| 267 | throw new ProviderException( |
| 268 | "Unsupported algorithm: " + mKeymasterAlgorithm); |
| 269 | } |
| 270 | |
| 271 | if (legacySpec.getKeySize() != -1) { |
| 272 | specBuilder.setKeySize(legacySpec.getKeySize()); |
| 273 | } |
| 274 | if (legacySpec.getAlgorithmParameterSpec() != null) { |
| 275 | specBuilder.setAlgorithmParameterSpec( |
| 276 | legacySpec.getAlgorithmParameterSpec()); |
| 277 | } |
| 278 | specBuilder.setCertificateSubject(legacySpec.getSubjectDN()); |
| 279 | specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber()); |
| 280 | specBuilder.setCertificateNotBefore(legacySpec.getStartDate()); |
| 281 | specBuilder.setCertificateNotAfter(legacySpec.getEndDate()); |
| 282 | encryptionAtRestRequired = legacySpec.isEncryptionRequired(); |
| 283 | specBuilder.setUserAuthenticationRequired(false); |
| 284 | |
| 285 | spec = specBuilder.build(); |
| 286 | } catch (NullPointerException | IllegalArgumentException e) { |
| 287 | throw new InvalidAlgorithmParameterException(e); |
| 288 | } |
| 289 | } else { |
| 290 | throw new InvalidAlgorithmParameterException( |
| 291 | "Unsupported params class: " + params.getClass().getName() |
| 292 | + ". Supported: " + KeyGenParameterSpec.class.getName() |
| 293 | + ", " + KeyPairGeneratorSpec.class.getName()); |
| 294 | } |
| 295 | |
| 296 | mEntryAlias = spec.getKeystoreAlias(); |
Alex Klyubin | 3876b1b | 2015-09-09 14:55:03 -0700 | [diff] [blame] | 297 | mEntryUid = spec.getUid(); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 298 | mSpec = spec; |
| 299 | mKeymasterAlgorithm = keymasterAlgorithm; |
| 300 | mEncryptionAtRestRequired = encryptionAtRestRequired; |
| 301 | mKeySizeBits = spec.getKeySize(); |
| 302 | initAlgorithmSpecificParameters(); |
| 303 | if (mKeySizeBits == -1) { |
| 304 | mKeySizeBits = getDefaultKeySize(keymasterAlgorithm); |
| 305 | } |
| 306 | checkValidKeySize(keymasterAlgorithm, mKeySizeBits); |
| 307 | |
| 308 | if (spec.getKeystoreAlias() == null) { |
| 309 | throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided"); |
| 310 | } |
| 311 | |
| 312 | String jcaKeyAlgorithm; |
| 313 | try { |
| 314 | jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm( |
| 315 | keymasterAlgorithm); |
| 316 | mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes()); |
| 317 | mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes()); |
| 318 | mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster( |
| 319 | spec.getEncryptionPaddings()); |
Alex Klyubin | fdbc02a | 2015-06-29 14:39:29 -0700 | [diff] [blame] | 320 | if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) |
| 321 | && (spec.isRandomizedEncryptionRequired())) { |
| 322 | for (int keymasterPadding : mKeymasterEncryptionPaddings) { |
| 323 | if (!KeymasterUtils |
| 324 | .isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto( |
| 325 | keymasterPadding)) { |
| 326 | throw new InvalidAlgorithmParameterException( |
| 327 | "Randomized encryption (IND-CPA) required but may be violated" |
| 328 | + " by padding scheme: " |
| 329 | + KeyProperties.EncryptionPadding.fromKeymaster( |
| 330 | keymasterPadding) |
| 331 | + ". See " + KeyGenParameterSpec.class.getName() |
| 332 | + " documentation."); |
| 333 | } |
| 334 | } |
| 335 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 336 | mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster( |
| 337 | spec.getSignaturePaddings()); |
| 338 | if (spec.isDigestsSpecified()) { |
| 339 | mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests()); |
| 340 | } else { |
| 341 | mKeymasterDigests = EmptyArray.INT; |
| 342 | } |
Alex Klyubin | b6e6286 | 2015-07-06 10:31:07 -0700 | [diff] [blame] | 343 | |
| 344 | // Check that user authentication related parameters are acceptable. This method |
| 345 | // will throw an IllegalStateException if there are issues (e.g., secure lock screen |
| 346 | // not set up). |
Brian Young | 5437b81 | 2018-02-23 18:04:20 +0000 | [diff] [blame] | 347 | KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec); |
Alex Klyubin | b6e6286 | 2015-07-06 10:31:07 -0700 | [diff] [blame] | 348 | } catch (IllegalArgumentException | IllegalStateException e) { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 349 | throw new InvalidAlgorithmParameterException(e); |
| 350 | } |
| 351 | |
| 352 | mJcaKeyAlgorithm = jcaKeyAlgorithm; |
| 353 | mRng = random; |
| 354 | mKeyStore = KeyStore.getInstance(); |
| 355 | success = true; |
| 356 | } finally { |
| 357 | if (!success) { |
| 358 | resetAll(); |
| 359 | } |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | private void resetAll() { |
| 364 | mEntryAlias = null; |
Alex Klyubin | 3876b1b | 2015-09-09 14:55:03 -0700 | [diff] [blame] | 365 | mEntryUid = KeyStore.UID_SELF; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 366 | mJcaKeyAlgorithm = null; |
| 367 | mKeymasterAlgorithm = -1; |
| 368 | mKeymasterPurposes = null; |
| 369 | mKeymasterBlockModes = null; |
| 370 | mKeymasterEncryptionPaddings = null; |
| 371 | mKeymasterSignaturePaddings = null; |
| 372 | mKeymasterDigests = null; |
| 373 | mKeySizeBits = 0; |
| 374 | mSpec = null; |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 375 | mRSAPublicExponent = null; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 376 | mEncryptionAtRestRequired = false; |
| 377 | mRng = null; |
| 378 | mKeyStore = null; |
| 379 | } |
| 380 | |
| 381 | private void initAlgorithmSpecificParameters() throws InvalidAlgorithmParameterException { |
| 382 | AlgorithmParameterSpec algSpecificSpec = mSpec.getAlgorithmParameterSpec(); |
| 383 | switch (mKeymasterAlgorithm) { |
| 384 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 385 | { |
| 386 | BigInteger publicExponent = null; |
| 387 | if (algSpecificSpec instanceof RSAKeyGenParameterSpec) { |
| 388 | RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec) algSpecificSpec; |
| 389 | if (mKeySizeBits == -1) { |
| 390 | mKeySizeBits = rsaSpec.getKeysize(); |
| 391 | } else if (mKeySizeBits != rsaSpec.getKeysize()) { |
| 392 | throw new InvalidAlgorithmParameterException("RSA key size must match " |
| 393 | + " between " + mSpec + " and " + algSpecificSpec |
| 394 | + ": " + mKeySizeBits + " vs " + rsaSpec.getKeysize()); |
| 395 | } |
| 396 | publicExponent = rsaSpec.getPublicExponent(); |
| 397 | } else if (algSpecificSpec != null) { |
| 398 | throw new InvalidAlgorithmParameterException( |
| 399 | "RSA may only use RSAKeyGenParameterSpec"); |
| 400 | } |
| 401 | if (publicExponent == null) { |
| 402 | publicExponent = RSAKeyGenParameterSpec.F4; |
| 403 | } |
| 404 | if (publicExponent.compareTo(BigInteger.ZERO) < 1) { |
| 405 | throw new InvalidAlgorithmParameterException( |
| 406 | "RSA public exponent must be positive: " + publicExponent); |
| 407 | } |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 408 | if (publicExponent.compareTo(KeymasterArguments.UINT64_MAX_VALUE) > 0) { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 409 | throw new InvalidAlgorithmParameterException( |
| 410 | "Unsupported RSA public exponent: " + publicExponent |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 411 | + ". Maximum supported value: " + KeymasterArguments.UINT64_MAX_VALUE); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 412 | } |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 413 | mRSAPublicExponent = publicExponent; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 414 | break; |
| 415 | } |
| 416 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 417 | if (algSpecificSpec instanceof ECGenParameterSpec) { |
| 418 | ECGenParameterSpec ecSpec = (ECGenParameterSpec) algSpecificSpec; |
| 419 | String curveName = ecSpec.getName(); |
| 420 | Integer ecSpecKeySizeBits = SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.get( |
| 421 | curveName.toLowerCase(Locale.US)); |
| 422 | if (ecSpecKeySizeBits == null) { |
| 423 | throw new InvalidAlgorithmParameterException( |
| 424 | "Unsupported EC curve name: " + curveName |
| 425 | + ". Supported: " + SUPPORTED_EC_NIST_CURVE_NAMES); |
| 426 | } |
| 427 | if (mKeySizeBits == -1) { |
| 428 | mKeySizeBits = ecSpecKeySizeBits; |
| 429 | } else if (mKeySizeBits != ecSpecKeySizeBits) { |
| 430 | throw new InvalidAlgorithmParameterException("EC key size must match " |
| 431 | + " between " + mSpec + " and " + algSpecificSpec |
| 432 | + ": " + mKeySizeBits + " vs " + ecSpecKeySizeBits); |
| 433 | } |
| 434 | } else if (algSpecificSpec != null) { |
| 435 | throw new InvalidAlgorithmParameterException( |
| 436 | "EC may only use ECGenParameterSpec"); |
| 437 | } |
| 438 | break; |
| 439 | default: |
| 440 | throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm); |
| 441 | } |
| 442 | } |
| 443 | |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 444 | @Override |
| 445 | public KeyPair generateKeyPair() { |
| 446 | if (mKeyStore == null || mSpec == null) { |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 447 | throw new IllegalStateException("Not initialized"); |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 448 | } |
| 449 | |
Frank Salim | ea5e038 | 2018-01-23 22:42:29 -0800 | [diff] [blame] | 450 | int flags = (mEncryptionAtRestRequired) ? KeyStore.FLAG_ENCRYPTED : 0; |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 451 | if (((flags & KeyStore.FLAG_ENCRYPTED) != 0) |
Kenny Root | 2eeda72 | 2013-04-10 11:30:58 -0700 | [diff] [blame] | 452 | && (mKeyStore.state() != KeyStore.State.UNLOCKED)) { |
| 453 | throw new IllegalStateException( |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 454 | "Encryption at rest using secure lock screen credential requested for key pair" |
| 455 | + ", but the user has not yet entered the credential"); |
Kenny Root | 2eeda72 | 2013-04-10 11:30:58 -0700 | [diff] [blame] | 456 | } |
| 457 | |
Frank Salim | ea5e038 | 2018-01-23 22:42:29 -0800 | [diff] [blame] | 458 | if (mSpec.isStrongBoxBacked()) { |
| 459 | flags |= KeyStore.FLAG_STRONGBOX; |
| 460 | } |
| 461 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 462 | byte[] additionalEntropy = |
| 463 | KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng( |
| 464 | mRng, (mKeySizeBits + 7) / 8); |
| 465 | |
| 466 | Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias, mEntryUid); |
| 467 | final String privateKeyAlias = Credentials.USER_PRIVATE_KEY + mEntryAlias; |
| 468 | boolean success = false; |
| 469 | try { |
| 470 | generateKeystoreKeyPair( |
| 471 | privateKeyAlias, constructKeyGenerationArguments(), additionalEntropy, flags); |
| 472 | KeyPair keyPair = loadKeystoreKeyPair(privateKeyAlias); |
| 473 | |
| 474 | storeCertificateChain(flags, createCertificateChain(privateKeyAlias, keyPair)); |
| 475 | |
| 476 | success = true; |
| 477 | return keyPair; |
Frank Salim | b631503 | 2018-03-15 17:33:16 -0700 | [diff] [blame] | 478 | } catch (ProviderException e) { |
| 479 | if ((mSpec.getPurposes() & KeyProperties.PURPOSE_WRAP_KEY) != 0) { |
| 480 | throw new SecureKeyImportUnavailableException(e); |
| 481 | } else { |
| 482 | throw e; |
| 483 | } |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 484 | } finally { |
| 485 | if (!success) { |
| 486 | Credentials.deleteAllTypesForAlias(mKeyStore, mEntryAlias, mEntryUid); |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | private Iterable<byte[]> createCertificateChain(final String privateKeyAlias, KeyPair keyPair) |
| 492 | throws ProviderException { |
| 493 | byte[] challenge = mSpec.getAttestationChallenge(); |
| 494 | if (challenge != null) { |
| 495 | KeymasterArguments args = new KeymasterArguments(); |
| 496 | args.addBytes(KeymasterDefs.KM_TAG_ATTESTATION_CHALLENGE, challenge); |
| 497 | return getAttestationChain(privateKeyAlias, keyPair, args); |
| 498 | } |
| 499 | |
| 500 | // Very short certificate chain in the non-attestation case. |
| 501 | return Collections.singleton(generateSelfSignedCertificateBytes(keyPair)); |
| 502 | } |
| 503 | |
| 504 | private void generateKeystoreKeyPair(final String privateKeyAlias, KeymasterArguments args, |
| 505 | byte[] additionalEntropy, final int flags) throws ProviderException { |
| 506 | KeyCharacteristics resultingKeyCharacteristics = new KeyCharacteristics(); |
| 507 | int errorCode = mKeyStore.generateKey(privateKeyAlias, args, additionalEntropy, |
| 508 | mEntryUid, flags, resultingKeyCharacteristics); |
| 509 | if (errorCode != KeyStore.NO_ERROR) { |
Frank Salim | ea5e038 | 2018-01-23 22:42:29 -0800 | [diff] [blame] | 510 | if (errorCode == KeyStore.HARDWARE_TYPE_UNAVAILABLE) { |
| 511 | throw new StrongBoxUnavailableException("Failed to generate key pair"); |
| 512 | } else { |
| 513 | throw new ProviderException( |
| 514 | "Failed to generate key pair", KeyStore.getKeyStoreException(errorCode)); |
| 515 | } |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 516 | } |
| 517 | } |
| 518 | |
| 519 | private KeyPair loadKeystoreKeyPair(final String privateKeyAlias) throws ProviderException { |
| 520 | try { |
| 521 | KeyPair result = AndroidKeyStoreProvider.loadAndroidKeyStoreKeyPairFromKeystore( |
| 522 | mKeyStore, privateKeyAlias, mEntryUid); |
| 523 | if (!mJcaKeyAlgorithm.equalsIgnoreCase(result.getPrivate().getAlgorithm())) { |
| 524 | throw new ProviderException( |
| 525 | "Generated key pair algorithm does not match requested algorithm: " |
| 526 | + result.getPrivate().getAlgorithm() + " vs " + mJcaKeyAlgorithm); |
| 527 | } |
| 528 | return result; |
Max Bires | b2cc3dc | 2018-11-02 10:50:40 -0700 | [diff] [blame^] | 529 | } catch (UnrecoverableKeyException | KeyPermanentlyInvalidatedException e) { |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 530 | throw new ProviderException("Failed to load generated key pair from keystore", e); |
| 531 | } |
| 532 | } |
| 533 | |
| 534 | private KeymasterArguments constructKeyGenerationArguments() { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 535 | KeymasterArguments args = new KeymasterArguments(); |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 536 | args.addUnsignedInt(KeymasterDefs.KM_TAG_KEY_SIZE, mKeySizeBits); |
| 537 | args.addEnum(KeymasterDefs.KM_TAG_ALGORITHM, mKeymasterAlgorithm); |
| 538 | args.addEnums(KeymasterDefs.KM_TAG_PURPOSE, mKeymasterPurposes); |
| 539 | args.addEnums(KeymasterDefs.KM_TAG_BLOCK_MODE, mKeymasterBlockModes); |
| 540 | args.addEnums(KeymasterDefs.KM_TAG_PADDING, mKeymasterEncryptionPaddings); |
| 541 | args.addEnums(KeymasterDefs.KM_TAG_PADDING, mKeymasterSignaturePaddings); |
| 542 | args.addEnums(KeymasterDefs.KM_TAG_DIGEST, mKeymasterDigests); |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 543 | |
Brian Young | 5437b81 | 2018-02-23 18:04:20 +0000 | [diff] [blame] | 544 | KeymasterUtils.addUserAuthArgs(args, mSpec); |
Alex Klyubin | d6c7799 | 2015-06-23 12:06:27 -0700 | [diff] [blame] | 545 | args.addDateIfNotNull(KeymasterDefs.KM_TAG_ACTIVE_DATETIME, mSpec.getKeyValidityStart()); |
| 546 | args.addDateIfNotNull(KeymasterDefs.KM_TAG_ORIGINATION_EXPIRE_DATETIME, |
| 547 | mSpec.getKeyValidityForOriginationEnd()); |
| 548 | args.addDateIfNotNull(KeymasterDefs.KM_TAG_USAGE_EXPIRE_DATETIME, |
| 549 | mSpec.getKeyValidityForConsumptionEnd()); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 550 | addAlgorithmSpecificParameters(args); |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 551 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 552 | if (mSpec.isUniqueIdIncluded()) |
| 553 | args.addBoolean(KeymasterDefs.KM_TAG_INCLUDE_UNIQUE_ID); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 554 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 555 | return args; |
| 556 | } |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 557 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 558 | private void storeCertificateChain(final int flags, Iterable<byte[]> iterable) |
| 559 | throws ProviderException { |
| 560 | Iterator<byte[]> iter = iterable.iterator(); |
| 561 | storeCertificate( |
| 562 | Credentials.USER_CERTIFICATE, iter.next(), flags, "Failed to store certificate"); |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 563 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 564 | if (!iter.hasNext()) { |
| 565 | return; |
Alex Klyubin | 4bbfeb4 | 2015-06-04 10:42:59 -0700 | [diff] [blame] | 566 | } |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 567 | |
| 568 | ByteArrayOutputStream certificateConcatenationStream = new ByteArrayOutputStream(); |
| 569 | while (iter.hasNext()) { |
| 570 | byte[] data = iter.next(); |
| 571 | certificateConcatenationStream.write(data, 0, data.length); |
| 572 | } |
| 573 | |
| 574 | storeCertificate(Credentials.CA_CERTIFICATE, certificateConcatenationStream.toByteArray(), |
| 575 | flags, "Failed to store attestation CA certificate"); |
| 576 | } |
| 577 | |
| 578 | private void storeCertificate(String prefix, byte[] certificateBytes, final int flags, |
| 579 | String failureMessage) throws ProviderException { |
| 580 | int insertErrorCode = mKeyStore.insert( |
| 581 | prefix + mEntryAlias, |
| 582 | certificateBytes, |
| 583 | mEntryUid, |
| 584 | flags); |
| 585 | if (insertErrorCode != KeyStore.NO_ERROR) { |
| 586 | throw new ProviderException(failureMessage, |
| 587 | KeyStore.getKeyStoreException(insertErrorCode)); |
| 588 | } |
| 589 | } |
| 590 | |
| 591 | private byte[] generateSelfSignedCertificateBytes(KeyPair keyPair) throws ProviderException { |
| 592 | try { |
| 593 | return generateSelfSignedCertificate(keyPair.getPrivate(), keyPair.getPublic()) |
| 594 | .getEncoded(); |
| 595 | } catch (IOException | CertificateParsingException e) { |
| 596 | throw new ProviderException("Failed to generate self-signed certificate", e); |
| 597 | } catch (CertificateEncodingException e) { |
| 598 | throw new ProviderException( |
| 599 | "Failed to obtain encoded form of self-signed certificate", e); |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | private Iterable<byte[]> getAttestationChain(String privateKeyAlias, |
| 604 | KeyPair keyPair, KeymasterArguments args) |
| 605 | throws ProviderException { |
| 606 | KeymasterCertificateChain outChain = new KeymasterCertificateChain(); |
| 607 | int errorCode = mKeyStore.attestKey(privateKeyAlias, args, outChain); |
| 608 | if (errorCode != KeyStore.NO_ERROR) { |
| 609 | throw new ProviderException("Failed to generate attestation certificate chain", |
| 610 | KeyStore.getKeyStoreException(errorCode)); |
| 611 | } |
| 612 | Collection<byte[]> chain = outChain.getCertificates(); |
| 613 | if (chain.size() < 2) { |
| 614 | throw new ProviderException("Attestation certificate chain contained " |
| 615 | + chain.size() + " entries. At least two are required."); |
| 616 | } |
| 617 | return chain; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 618 | } |
| 619 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 620 | private void addAlgorithmSpecificParameters(KeymasterArguments keymasterArgs) { |
| 621 | switch (mKeymasterAlgorithm) { |
| 622 | case KeymasterDefs.KM_ALGORITHM_RSA: |
Alex Klyubin | ae6cb7a | 2015-06-22 18:09:35 -0700 | [diff] [blame] | 623 | keymasterArgs.addUnsignedLong( |
| 624 | KeymasterDefs.KM_TAG_RSA_PUBLIC_EXPONENT, mRSAPublicExponent); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 625 | break; |
| 626 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 627 | break; |
| 628 | default: |
| 629 | throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm); |
| 630 | } |
| 631 | } |
| 632 | |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 633 | private X509Certificate generateSelfSignedCertificate(PrivateKey privateKey, |
| 634 | PublicKey publicKey) throws CertificateParsingException, IOException { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 635 | String signatureAlgorithm = |
| 636 | getCertificateSignatureAlgorithm(mKeymasterAlgorithm, mKeySizeBits, mSpec); |
| 637 | if (signatureAlgorithm == null) { |
| 638 | // Key cannot be used to sign a certificate |
| 639 | return generateSelfSignedCertificateWithFakeSignature(publicKey); |
| 640 | } else { |
| 641 | // Key can be used to sign a certificate |
Alex Klyubin | 856aebe | 2015-06-23 10:54:44 -0700 | [diff] [blame] | 642 | try { |
| 643 | return generateSelfSignedCertificateWithValidSignature( |
| 644 | privateKey, publicKey, signatureAlgorithm); |
| 645 | } catch (Exception e) { |
| 646 | // Failed to generate the self-signed certificate with valid signature. Fall back |
| 647 | // to generating a self-signed certificate with a fake signature. This is done for |
| 648 | // all exception types because we prefer key pair generation to succeed and end up |
| 649 | // producing a self-signed certificate with an invalid signature to key pair |
| 650 | // generation failing. |
| 651 | return generateSelfSignedCertificateWithFakeSignature(publicKey); |
| 652 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 653 | } |
| 654 | } |
| 655 | |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 656 | @SuppressWarnings("deprecation") |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 657 | private X509Certificate generateSelfSignedCertificateWithValidSignature( |
Alex Klyubin | 856aebe | 2015-06-23 10:54:44 -0700 | [diff] [blame] | 658 | PrivateKey privateKey, PublicKey publicKey, String signatureAlgorithm) throws Exception { |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 659 | final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); |
| 660 | certGen.setPublicKey(publicKey); |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 661 | certGen.setSerialNumber(mSpec.getCertificateSerialNumber()); |
| 662 | certGen.setSubjectDN(mSpec.getCertificateSubject()); |
| 663 | certGen.setIssuerDN(mSpec.getCertificateSubject()); |
| 664 | certGen.setNotBefore(mSpec.getCertificateNotBefore()); |
| 665 | certGen.setNotAfter(mSpec.getCertificateNotAfter()); |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 666 | certGen.setSignatureAlgorithm(signatureAlgorithm); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 667 | return certGen.generate(privateKey); |
| 668 | } |
| 669 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 670 | @SuppressWarnings("deprecation") |
| 671 | private X509Certificate generateSelfSignedCertificateWithFakeSignature( |
Shawn Willden | 8d8c747 | 2016-02-02 08:27:39 -0700 | [diff] [blame] | 672 | PublicKey publicKey) throws IOException, CertificateParsingException { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 673 | V3TBSCertificateGenerator tbsGenerator = new V3TBSCertificateGenerator(); |
| 674 | ASN1ObjectIdentifier sigAlgOid; |
| 675 | AlgorithmIdentifier sigAlgId; |
| 676 | byte[] signature; |
| 677 | switch (mKeymasterAlgorithm) { |
| 678 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 679 | sigAlgOid = X9ObjectIdentifiers.ecdsa_with_SHA256; |
| 680 | sigAlgId = new AlgorithmIdentifier(sigAlgOid); |
| 681 | ASN1EncodableVector v = new ASN1EncodableVector(); |
| 682 | v.add(new DERInteger(0)); |
| 683 | v.add(new DERInteger(0)); |
| 684 | signature = new DERSequence().getEncoded(); |
| 685 | break; |
| 686 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 687 | sigAlgOid = PKCSObjectIdentifiers.sha256WithRSAEncryption; |
| 688 | sigAlgId = new AlgorithmIdentifier(sigAlgOid, DERNull.INSTANCE); |
| 689 | signature = new byte[1]; |
| 690 | break; |
| 691 | default: |
| 692 | throw new ProviderException("Unsupported key algorithm: " + mKeymasterAlgorithm); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 693 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 694 | |
| 695 | try (ASN1InputStream publicKeyInfoIn = new ASN1InputStream(publicKey.getEncoded())) { |
| 696 | tbsGenerator.setSubjectPublicKeyInfo( |
| 697 | SubjectPublicKeyInfo.getInstance(publicKeyInfoIn.readObject())); |
| 698 | } |
| 699 | tbsGenerator.setSerialNumber(new ASN1Integer(mSpec.getCertificateSerialNumber())); |
| 700 | X509Principal subject = |
| 701 | new X509Principal(mSpec.getCertificateSubject().getEncoded()); |
| 702 | tbsGenerator.setSubject(subject); |
| 703 | tbsGenerator.setIssuer(subject); |
| 704 | tbsGenerator.setStartDate(new Time(mSpec.getCertificateNotBefore())); |
| 705 | tbsGenerator.setEndDate(new Time(mSpec.getCertificateNotAfter())); |
| 706 | tbsGenerator.setSignature(sigAlgId); |
| 707 | TBSCertificate tbsCertificate = tbsGenerator.generateTBSCertificate(); |
| 708 | |
| 709 | ASN1EncodableVector result = new ASN1EncodableVector(); |
| 710 | result.add(tbsCertificate); |
| 711 | result.add(sigAlgId); |
| 712 | result.add(new DERBitString(signature)); |
| 713 | return new X509CertificateObject(Certificate.getInstance(new DERSequence(result))); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 714 | } |
| 715 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 716 | private static int getDefaultKeySize(int keymasterAlgorithm) { |
| 717 | switch (keymasterAlgorithm) { |
| 718 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 719 | return EC_DEFAULT_KEY_SIZE; |
| 720 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 721 | return RSA_DEFAULT_KEY_SIZE; |
| 722 | default: |
| 723 | throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 724 | } |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 725 | } |
| 726 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 727 | private static void checkValidKeySize(int keymasterAlgorithm, int keySize) |
Alex Klyubin | 21a76df | 2015-01-14 13:35:32 -0800 | [diff] [blame] | 728 | throws InvalidAlgorithmParameterException { |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 729 | switch (keymasterAlgorithm) { |
| 730 | case KeymasterDefs.KM_ALGORITHM_EC: |
Alex Klyubin | bf5c91c | 2015-06-17 10:51:19 -0700 | [diff] [blame] | 731 | if (!SUPPORTED_EC_NIST_CURVE_SIZES.contains(keySize)) { |
| 732 | throw new InvalidAlgorithmParameterException("Unsupported EC key size: " |
| 733 | + keySize + " bits. Supported: " + SUPPORTED_EC_NIST_CURVE_SIZES); |
Kenny Root | f64386f | 2013-08-16 14:03:29 -0700 | [diff] [blame] | 734 | } |
| 735 | break; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 736 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 737 | if (keySize < RSA_MIN_KEY_SIZE || keySize > RSA_MAX_KEY_SIZE) { |
| 738 | throw new InvalidAlgorithmParameterException("RSA key size must be >= " |
| 739 | + RSA_MIN_KEY_SIZE + " and <= " + RSA_MAX_KEY_SIZE); |
| 740 | } |
| 741 | break; |
| 742 | default: |
| 743 | throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); |
Kenny Root | f64386f | 2013-08-16 14:03:29 -0700 | [diff] [blame] | 744 | } |
Kenny Root | f64386f | 2013-08-16 14:03:29 -0700 | [diff] [blame] | 745 | } |
| 746 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 747 | /** |
| 748 | * Returns the {@code Signature} algorithm to be used for signing a certificate using the |
| 749 | * specified key or {@code null} if the key cannot be used for signing a certificate. |
| 750 | */ |
| 751 | @Nullable |
| 752 | private static String getCertificateSignatureAlgorithm( |
| 753 | int keymasterAlgorithm, |
| 754 | int keySizeBits, |
| 755 | KeyGenParameterSpec spec) { |
| 756 | // Constraints: |
Alex Klyubin | f78dd67 | 2015-06-15 15:16:09 -0700 | [diff] [blame] | 757 | // 1. Key must be authorized for signing without user authentication. |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 758 | // 2. Signature digest must be one of key's authorized digests. |
Alex Klyubin | 6e90ade | 2015-06-22 13:21:59 -0700 | [diff] [blame] | 759 | // 3. For RSA keys, the digest output size must not exceed modulus size minus space overhead |
| 760 | // of RSA PKCS#1 signature padding scheme (about 30 bytes). |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 761 | // 4. For EC keys, the there is no point in using a digest whose output size is longer than |
| 762 | // key/field size because the digest will be truncated to that size. |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 763 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 764 | if ((spec.getPurposes() & KeyProperties.PURPOSE_SIGN) == 0) { |
| 765 | // Key not authorized for signing |
| 766 | return null; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 767 | } |
Alex Klyubin | f78dd67 | 2015-06-15 15:16:09 -0700 | [diff] [blame] | 768 | if (spec.isUserAuthenticationRequired()) { |
| 769 | // Key not authorized for use without user authentication |
| 770 | return null; |
| 771 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 772 | if (!spec.isDigestsSpecified()) { |
| 773 | // Key not authorized for any digests -- can't sign |
| 774 | return null; |
| 775 | } |
| 776 | switch (keymasterAlgorithm) { |
| 777 | case KeymasterDefs.KM_ALGORITHM_EC: |
| 778 | { |
| 779 | Set<Integer> availableKeymasterDigests = getAvailableKeymasterSignatureDigests( |
| 780 | spec.getDigests(), |
| 781 | AndroidKeyStoreBCWorkaroundProvider.getSupportedEcdsaSignatureDigests()); |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 782 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 783 | int bestKeymasterDigest = -1; |
| 784 | int bestDigestOutputSizeBits = -1; |
| 785 | for (int keymasterDigest : availableKeymasterDigests) { |
| 786 | int outputSizeBits = KeymasterUtils.getDigestOutputSizeBits(keymasterDigest); |
| 787 | if (outputSizeBits == keySizeBits) { |
| 788 | // Perfect match -- use this digest |
| 789 | bestKeymasterDigest = keymasterDigest; |
| 790 | bestDigestOutputSizeBits = outputSizeBits; |
| 791 | break; |
| 792 | } |
| 793 | // Not a perfect match -- check against the best digest so far |
| 794 | if (bestKeymasterDigest == -1) { |
| 795 | // First digest tested -- definitely the best so far |
| 796 | bestKeymasterDigest = keymasterDigest; |
| 797 | bestDigestOutputSizeBits = outputSizeBits; |
| 798 | } else { |
| 799 | // Prefer output size to be as close to key size as possible, with output |
| 800 | // sizes larger than key size preferred to those smaller than key size. |
| 801 | if (bestDigestOutputSizeBits < keySizeBits) { |
| 802 | // Output size of the best digest so far is smaller than key size. |
| 803 | // Anything larger is a win. |
| 804 | if (outputSizeBits > bestDigestOutputSizeBits) { |
| 805 | bestKeymasterDigest = keymasterDigest; |
| 806 | bestDigestOutputSizeBits = outputSizeBits; |
| 807 | } |
| 808 | } else { |
| 809 | // Output size of the best digest so far is larger than key size. |
| 810 | // Anything smaller is a win, as long as it's not smaller than key size. |
| 811 | if ((outputSizeBits < bestDigestOutputSizeBits) |
| 812 | && (outputSizeBits >= keySizeBits)) { |
| 813 | bestKeymasterDigest = keymasterDigest; |
| 814 | bestDigestOutputSizeBits = outputSizeBits; |
| 815 | } |
| 816 | } |
| 817 | } |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 818 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 819 | if (bestKeymasterDigest == -1) { |
| 820 | return null; |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 821 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 822 | return KeyProperties.Digest.fromKeymasterToSignatureAlgorithmDigest( |
| 823 | bestKeymasterDigest) + "WithECDSA"; |
Alex Klyubin | 3f8d4d8 | 2015-05-13 09:15:00 -0700 | [diff] [blame] | 824 | } |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 825 | case KeymasterDefs.KM_ALGORITHM_RSA: |
| 826 | { |
Alex Klyubin | 7c475cc | 2015-06-12 12:16:45 -0700 | [diff] [blame] | 827 | // Check whether this key is authorized for PKCS#1 signature padding. |
| 828 | // We use Bouncy Castle to generate self-signed RSA certificates. Bouncy Castle |
| 829 | // only supports RSA certificates signed using PKCS#1 padding scheme. The key needs |
| 830 | // to be authorized for PKCS#1 padding or padding NONE which means any padding. |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 831 | boolean pkcs1SignaturePaddingSupported = |
| 832 | com.android.internal.util.ArrayUtils.contains( |
| 833 | KeyProperties.SignaturePadding.allToKeymaster( |
| 834 | spec.getSignaturePaddings()), |
| 835 | KeymasterDefs.KM_PAD_RSA_PKCS1_1_5_SIGN); |
Alex Klyubin | 7c475cc | 2015-06-12 12:16:45 -0700 | [diff] [blame] | 836 | if (!pkcs1SignaturePaddingSupported) { |
| 837 | // Key not authorized for PKCS#1 signature padding -- can't sign |
| 838 | return null; |
| 839 | } |
| 840 | |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 841 | Set<Integer> availableKeymasterDigests = getAvailableKeymasterSignatureDigests( |
| 842 | spec.getDigests(), |
| 843 | AndroidKeyStoreBCWorkaroundProvider.getSupportedEcdsaSignatureDigests()); |
| 844 | |
Alex Klyubin | 6e90ade | 2015-06-22 13:21:59 -0700 | [diff] [blame] | 845 | // The amount of space available for the digest is less than modulus size by about |
| 846 | // 30 bytes because padding must be at least 11 bytes long (00 || 01 || PS || 00, |
| 847 | // where PS must be at least 8 bytes long), and then there's also the 15--19 bytes |
| 848 | // overhead (depending the on chosen digest) for encoding digest OID and digest |
| 849 | // value in DER. |
| 850 | int maxDigestOutputSizeBits = keySizeBits - 30 * 8; |
Alex Klyubin | 3ceb1a0 | 2015-06-05 15:51:06 -0700 | [diff] [blame] | 851 | int bestKeymasterDigest = -1; |
| 852 | int bestDigestOutputSizeBits = -1; |
| 853 | for (int keymasterDigest : availableKeymasterDigests) { |
| 854 | int outputSizeBits = KeymasterUtils.getDigestOutputSizeBits(keymasterDigest); |
| 855 | if (outputSizeBits > maxDigestOutputSizeBits) { |
| 856 | // Digest too long (signature generation will fail) -- skip |
| 857 | continue; |
| 858 | } |
| 859 | if (bestKeymasterDigest == -1) { |
| 860 | // First digest tested -- definitely the best so far |
| 861 | bestKeymasterDigest = keymasterDigest; |
| 862 | bestDigestOutputSizeBits = outputSizeBits; |
| 863 | } else { |
| 864 | // The longer the better |
| 865 | if (outputSizeBits > bestDigestOutputSizeBits) { |
| 866 | bestKeymasterDigest = keymasterDigest; |
| 867 | bestDigestOutputSizeBits = outputSizeBits; |
| 868 | } |
| 869 | } |
| 870 | } |
| 871 | if (bestKeymasterDigest == -1) { |
| 872 | return null; |
| 873 | } |
| 874 | return KeyProperties.Digest.fromKeymasterToSignatureAlgorithmDigest( |
| 875 | bestKeymasterDigest) + "WithRSA"; |
| 876 | } |
| 877 | default: |
| 878 | throw new ProviderException("Unsupported algorithm: " + keymasterAlgorithm); |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | private static Set<Integer> getAvailableKeymasterSignatureDigests( |
| 883 | @KeyProperties.DigestEnum String[] authorizedKeyDigests, |
| 884 | @KeyProperties.DigestEnum String[] supportedSignatureDigests) { |
| 885 | Set<Integer> authorizedKeymasterKeyDigests = new HashSet<Integer>(); |
| 886 | for (int keymasterDigest : KeyProperties.Digest.allToKeymaster(authorizedKeyDigests)) { |
| 887 | authorizedKeymasterKeyDigests.add(keymasterDigest); |
| 888 | } |
| 889 | Set<Integer> supportedKeymasterSignatureDigests = new HashSet<Integer>(); |
| 890 | for (int keymasterDigest |
| 891 | : KeyProperties.Digest.allToKeymaster(supportedSignatureDigests)) { |
| 892 | supportedKeymasterSignatureDigests.add(keymasterDigest); |
| 893 | } |
Alex Klyubin | e4928a2 | 2015-07-21 13:38:48 -0700 | [diff] [blame] | 894 | Set<Integer> result = new HashSet<Integer>(supportedKeymasterSignatureDigests); |
| 895 | result.retainAll(authorizedKeymasterKeyDigests); |
| 896 | return result; |
Kenny Root | db02671 | 2012-08-20 10:48:46 -0700 | [diff] [blame] | 897 | } |
| 898 | } |