xref: /aosp_15_r20/system/keymaster/km_openssl/rsa_key_factory.cpp (revision 789431f29546679ab5188a97751fb38e3018d44d)
1 /*
2  * Copyright 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <keymaster/km_openssl/rsa_key_factory.h>
18 
19 #include <inttypes.h>
20 #include <utility>
21 
22 #include <keymaster/keymaster_context.h>
23 #include <keymaster/km_openssl/openssl_err.h>
24 #include <keymaster/km_openssl/openssl_utils.h>
25 #include <keymaster/km_openssl/rsa_key.h>
26 #include <keymaster/km_openssl/rsa_operation.h>
27 
28 namespace keymaster {
29 
30 const int kMaximumRsaKeySize = 4096;  // OpenSSL fails above 4096.
31 const int kMinimumRsaKeySize = 16;    // OpenSSL goes into an infinite loop if key size < 10
32 const int kMinimumRsaExponent = 3;
33 
34 static RsaSigningOperationFactory sign_factory;
35 static RsaVerificationOperationFactory verify_factory;
36 static RsaEncryptionOperationFactory encrypt_factory;
37 static RsaDecryptionOperationFactory decrypt_factory;
38 
GetOperationFactory(keymaster_purpose_t purpose) const39 OperationFactory* RsaKeyFactory::GetOperationFactory(keymaster_purpose_t purpose) const {
40     switch (purpose) {
41     case KM_PURPOSE_SIGN:
42         return &sign_factory;
43     case KM_PURPOSE_VERIFY:
44         return &verify_factory;
45     case KM_PURPOSE_ENCRYPT:
46         return &encrypt_factory;
47     case KM_PURPOSE_DECRYPT:
48         return &decrypt_factory;
49     default:
50         return nullptr;
51     }
52 }
53 
GenerateKey(const AuthorizationSet & key_description,UniquePtr<Key> attest_key,const KeymasterBlob & issuer_subject,KeymasterKeyBlob * key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced,CertificateChain * cert_chain) const54 keymaster_error_t RsaKeyFactory::GenerateKey(const AuthorizationSet& key_description,
55                                              UniquePtr<Key> attest_key,  //
56                                              const KeymasterBlob& issuer_subject,
57                                              KeymasterKeyBlob* key_blob,
58                                              AuthorizationSet* hw_enforced,
59                                              AuthorizationSet* sw_enforced,
60                                              CertificateChain* cert_chain) const {
61     if (!key_blob || !hw_enforced || !sw_enforced) return KM_ERROR_OUTPUT_PARAMETER_NULL;
62 
63     uint64_t public_exponent;
64     if (!key_description.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &public_exponent)) {
65         LOG_E("No public exponent specified for RSA key generation");
66         return KM_ERROR_INVALID_ARGUMENT;
67     }
68     if (public_exponent < kMinimumRsaExponent || public_exponent % 2 != 1) {
69         LOG_E("Invalid public exponent specified for RSA key generation");
70         return KM_ERROR_INVALID_ARGUMENT;
71     }
72 
73     uint32_t key_size;
74     if (!key_description.GetTagValue(TAG_KEY_SIZE, &key_size)) {
75         LOG_E("No key size specified for RSA key generation");
76         return KM_ERROR_UNSUPPORTED_KEY_SIZE;
77     }
78     if (key_size % 8 != 0 || key_size > kMaximumRsaKeySize || key_size < kMinimumRsaKeySize) {
79         LOG_E("Invalid key size of %" PRIu32 " bits specified for RSA key generation", key_size);
80         return KM_ERROR_UNSUPPORTED_KEY_SIZE;
81     }
82 
83     BIGNUM_Ptr exponent(BN_new());
84     RSA_Ptr rsa_key(RSA_new());
85     EVP_PKEY_Ptr pkey(EVP_PKEY_new());
86     if (exponent.get() == nullptr || rsa_key.get() == nullptr || pkey.get() == nullptr) {
87         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
88     }
89 
90     if (!BN_set_word(exponent.get(), public_exponent) ||
91         !RSA_generate_key_ex(rsa_key.get(), key_size, exponent.get(), nullptr /* callback */))
92         return TranslateLastOpenSslError();
93 
94     if (EVP_PKEY_set1_RSA(pkey.get(), rsa_key.get()) != 1) return TranslateLastOpenSslError();
95 
96     KeymasterKeyBlob key_material;
97     keymaster_error_t error = EvpKeyToKeyMaterial(pkey.get(), &key_material);
98     if (error != KM_ERROR_OK) return error;
99 
100     error = blob_maker_.CreateKeyBlob(key_description, KM_ORIGIN_GENERATED, key_material, key_blob,
101                                       hw_enforced, sw_enforced);
102     if (error != KM_ERROR_OK) return error;
103 
104     if (context_.GetKmVersion() < KmVersion::KEYMINT_1) return KM_ERROR_OK;
105     if (!cert_chain) return KM_ERROR_UNEXPECTED_NULL_POINTER;
106 
107     RsaKey key(*hw_enforced, *sw_enforced, this, std::move(rsa_key));
108     if (key_description.Contains(TAG_ATTESTATION_CHALLENGE)) {
109         *cert_chain = context_.GenerateAttestation(key, key_description, std::move(attest_key),
110                                                    issuer_subject, &error);
111     } else if (attest_key.get() != nullptr) {
112         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
113     } else {
114         bool fake_signature = key_size < 1024 || !IsCertSigningKey(key_description);
115         *cert_chain =
116             context_.GenerateSelfSignedCertificate(key, key_description, fake_signature, &error);
117     }
118 
119     return error;
120 }
121 
ImportKey(const AuthorizationSet & key_description,keymaster_key_format_t input_key_material_format,const KeymasterKeyBlob & input_key_material,UniquePtr<Key> attest_key,const KeymasterBlob & issuer_subject,KeymasterKeyBlob * output_key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced,CertificateChain * cert_chain) const122 keymaster_error_t RsaKeyFactory::ImportKey(const AuthorizationSet& key_description,  //
123                                            keymaster_key_format_t input_key_material_format,
124                                            const KeymasterKeyBlob& input_key_material,
125                                            UniquePtr<Key> attest_key,  //
126                                            const KeymasterBlob& issuer_subject,
127                                            KeymasterKeyBlob* output_key_blob,
128                                            AuthorizationSet* hw_enforced,
129                                            AuthorizationSet* sw_enforced,
130                                            CertificateChain* cert_chain) const {
131     if (!output_key_blob || !hw_enforced || !sw_enforced) return KM_ERROR_OUTPUT_PARAMETER_NULL;
132 
133     AuthorizationSet authorizations;
134     uint64_t public_exponent;
135     uint32_t key_size;
136     keymaster_error_t error =
137         UpdateImportKeyDescription(key_description, input_key_material_format, input_key_material,
138                                    &authorizations, &public_exponent, &key_size);
139     if (error != KM_ERROR_OK) return error;
140     error = blob_maker_.CreateKeyBlob(authorizations, KM_ORIGIN_IMPORTED, input_key_material,
141                                       output_key_blob, hw_enforced, sw_enforced);
142     if (error != KM_ERROR_OK) return error;
143 
144     if (context_.GetKmVersion() < KmVersion::KEYMINT_1) return KM_ERROR_OK;
145     if (!cert_chain) return KM_ERROR_UNEXPECTED_NULL_POINTER;
146 
147     EVP_PKEY_Ptr pkey;
148     error = KeyMaterialToEvpKey(KM_KEY_FORMAT_PKCS8, input_key_material, KM_ALGORITHM_RSA, &pkey);
149     if (error != KM_ERROR_OK) return error;
150 
151     RSA_Ptr rsa_key(EVP_PKEY_get1_RSA(pkey.get()));
152     if (!rsa_key.get()) return KM_ERROR_INVALID_ARGUMENT;
153 
154     RsaKey key(*hw_enforced, *sw_enforced, this, std::move(rsa_key));
155     if (key_description.Contains(KM_TAG_ATTESTATION_CHALLENGE)) {
156         *cert_chain = context_.GenerateAttestation(key, key_description, std::move(attest_key),
157                                                    issuer_subject, &error);
158     } else if (attest_key.get() != nullptr) {
159         return KM_ERROR_ATTESTATION_CHALLENGE_MISSING;
160     } else {
161         bool fake_signature = key_size < 1024 || !IsCertSigningKey(key_description);
162         *cert_chain =
163             context_.GenerateSelfSignedCertificate(key, key_description, fake_signature, &error);
164     }
165 
166     return error;
167 }
168 
UpdateImportKeyDescription(const AuthorizationSet & key_description,keymaster_key_format_t key_format,const KeymasterKeyBlob & key_material,AuthorizationSet * updated_description,uint64_t * public_exponent,uint32_t * key_size) const169 keymaster_error_t RsaKeyFactory::UpdateImportKeyDescription(const AuthorizationSet& key_description,
170                                                             keymaster_key_format_t key_format,
171                                                             const KeymasterKeyBlob& key_material,
172                                                             AuthorizationSet* updated_description,
173                                                             uint64_t* public_exponent,
174                                                             uint32_t* key_size) const {
175     if (!updated_description || !public_exponent || !key_size)
176         return KM_ERROR_OUTPUT_PARAMETER_NULL;
177 
178     EVP_PKEY_Ptr pkey;
179     keymaster_error_t error =
180         KeyMaterialToEvpKey(key_format, key_material, keymaster_key_type(), &pkey);
181     if (error != KM_ERROR_OK) return error;
182 
183     RSA_Ptr rsa_key(EVP_PKEY_get1_RSA(pkey.get()));
184     if (!rsa_key.get()) return TranslateLastOpenSslError();
185 
186     updated_description->Reinitialize(key_description);
187 
188     uint64_t e;
189     if (!BN_get_u64(RSA_get0_e(rsa_key.get()), &e)) return KM_ERROR_INVALID_KEY_BLOB;
190     if (!updated_description->GetTagValue(TAG_RSA_PUBLIC_EXPONENT, public_exponent)) {
191         *public_exponent = e;
192         updated_description->push_back(TAG_RSA_PUBLIC_EXPONENT, *public_exponent);
193     }
194     if (*public_exponent != e) {
195         LOG_E("Imported public exponent (%" PRIu64 ") does not match specified "
196               "public exponent (%" PRIu64 ")",
197               *public_exponent, e);
198         return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
199     }
200 
201     *key_size = RSA_size(rsa_key.get()) * 8;
202     if (!updated_description->GetTagValue(TAG_KEY_SIZE, key_size))
203         updated_description->push_back(TAG_KEY_SIZE, *key_size);
204     if (RSA_size(rsa_key.get()) * 8 != *key_size) {
205         LOG_E("Imported key size (%u bits) does not match specified key size (%u bits)",
206               RSA_size(rsa_key.get()) * 8, *key_size);
207         return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
208     }
209 
210     keymaster_algorithm_t algorithm = KM_ALGORITHM_RSA;
211     if (!updated_description->GetTagValue(TAG_ALGORITHM, &algorithm))
212         updated_description->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
213     if (algorithm != KM_ALGORITHM_RSA) return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
214 
215     return KM_ERROR_OK;
216 }
217 
CreateEmptyKey(AuthorizationSet && hw_enforced,AuthorizationSet && sw_enforced,UniquePtr<AsymmetricKey> * key) const218 keymaster_error_t RsaKeyFactory::CreateEmptyKey(AuthorizationSet&& hw_enforced,
219                                                 AuthorizationSet&& sw_enforced,
220                                                 UniquePtr<AsymmetricKey>* key) const {
221     key->reset(new (std::nothrow) RsaKey(std::move(hw_enforced), std::move(sw_enforced), this));
222     if (!(*key)) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
223     return KM_ERROR_OK;
224 }
225 
226 }  // namespace keymaster
227