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 <keymaster/keymaster_context.h>
20 #include <keymaster/km_openssl/openssl_err.h>
21 #include <keymaster/km_openssl/openssl_utils.h>
22 #include <keymaster/km_openssl/rsa_key.h>
23 #include <keymaster/km_openssl/rsa_operation.h>
24 #include <keymaster/new.h>
25 
26 namespace keymaster {
27 
28 const int kMaximumRsaKeySize = 4096;  // OpenSSL fails above 4096.
29 const int kMinimumRsaKeySize = 16;    // OpenSSL goes into an infinite loop if key size < 10
30 const int kMinimumRsaExponent = 3;
31 
32 static RsaSigningOperationFactory sign_factory;
33 static RsaVerificationOperationFactory verify_factory;
34 static RsaEncryptionOperationFactory encrypt_factory;
35 static RsaDecryptionOperationFactory decrypt_factory;
36 
GetOperationFactory(keymaster_purpose_t purpose) const37 OperationFactory* RsaKeyFactory::GetOperationFactory(keymaster_purpose_t purpose) const {
38     switch (purpose) {
39     case KM_PURPOSE_SIGN:
40         return &sign_factory;
41     case KM_PURPOSE_VERIFY:
42         return &verify_factory;
43     case KM_PURPOSE_ENCRYPT:
44         return &encrypt_factory;
45     case KM_PURPOSE_DECRYPT:
46         return &decrypt_factory;
47     default:
48         return nullptr;
49     }
50 }
51 
GenerateKey(const AuthorizationSet & key_description,KeymasterKeyBlob * key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const52 keymaster_error_t RsaKeyFactory::GenerateKey(const AuthorizationSet& key_description,
53                                              KeymasterKeyBlob* key_blob,
54                                              AuthorizationSet* hw_enforced,
55                                              AuthorizationSet* sw_enforced) const {
56     if (!key_blob || !hw_enforced || !sw_enforced)
57         return KM_ERROR_OUTPUT_PARAMETER_NULL;
58 
59     const AuthorizationSet& authorizations(key_description);
60 
61     uint64_t public_exponent;
62     if (!authorizations.GetTagValue(TAG_RSA_PUBLIC_EXPONENT, &public_exponent)) {
63         LOG_E("No public exponent specified for RSA key generation", 0);
64         return KM_ERROR_INVALID_ARGUMENT;
65     }
66     if (public_exponent < kMinimumRsaExponent || public_exponent % 2 != 1) {
67         LOG_E("Invalid public exponent specified for RSA key generation", 0);
68         return KM_ERROR_INVALID_ARGUMENT;
69     }
70 
71     uint32_t key_size;
72     if (!authorizations.GetTagValue(TAG_KEY_SIZE, &key_size)) {
73         LOG_E("No key size specified for RSA key generation", 0);
74         return KM_ERROR_UNSUPPORTED_KEY_SIZE;
75     }
76     if (key_size % 8 != 0 || key_size > kMaximumRsaKeySize || key_size < kMinimumRsaKeySize) {
77         LOG_E("Invalid key size of %u bits specified for RSA key generation", key_size);
78         return KM_ERROR_UNSUPPORTED_KEY_SIZE;
79     }
80 
81     UniquePtr<BIGNUM, BIGNUM_Delete> exponent(BN_new());
82     UniquePtr<RSA, RsaKey::RSA_Delete> rsa_key(RSA_new());
83     UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey(EVP_PKEY_new());
84     if (exponent.get() == nullptr || rsa_key.get() == nullptr || pkey.get() == nullptr)
85         return KM_ERROR_MEMORY_ALLOCATION_FAILED;
86 
87     if (!BN_set_word(exponent.get(), public_exponent) ||
88         !RSA_generate_key_ex(rsa_key.get(), key_size, exponent.get(), nullptr /* callback */))
89         return TranslateLastOpenSslError();
90 
91     if (EVP_PKEY_set1_RSA(pkey.get(), rsa_key.get()) != 1)
92         return TranslateLastOpenSslError();
93 
94     KeymasterKeyBlob key_material;
95     keymaster_error_t error = EvpKeyToKeyMaterial(pkey.get(), &key_material);
96     if (error != KM_ERROR_OK)
97         return error;
98 
99     return blob_maker_.CreateKeyBlob(authorizations, KM_ORIGIN_GENERATED, key_material, key_blob,
100                                      hw_enforced, sw_enforced);
101 }
102 
ImportKey(const AuthorizationSet & key_description,keymaster_key_format_t input_key_material_format,const KeymasterKeyBlob & input_key_material,KeymasterKeyBlob * output_key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const103 keymaster_error_t RsaKeyFactory::ImportKey(const AuthorizationSet& key_description,
104                                            keymaster_key_format_t input_key_material_format,
105                                            const KeymasterKeyBlob& input_key_material,
106                                            KeymasterKeyBlob* output_key_blob,
107                                            AuthorizationSet* hw_enforced,
108                                            AuthorizationSet* sw_enforced) const {
109     if (!output_key_blob || !hw_enforced || !sw_enforced)
110         return KM_ERROR_OUTPUT_PARAMETER_NULL;
111 
112     AuthorizationSet authorizations;
113     uint64_t public_exponent;
114     uint32_t key_size;
115     keymaster_error_t error =
116         UpdateImportKeyDescription(key_description, input_key_material_format, input_key_material,
117                                    &authorizations, &public_exponent, &key_size);
118     if (error != KM_ERROR_OK)
119         return error;
120     return blob_maker_.CreateKeyBlob(authorizations, KM_ORIGIN_IMPORTED, input_key_material,
121                                      output_key_blob, hw_enforced, sw_enforced);
122 }
123 
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) const124 keymaster_error_t RsaKeyFactory::UpdateImportKeyDescription(const AuthorizationSet& key_description,
125                                                             keymaster_key_format_t key_format,
126                                                             const KeymasterKeyBlob& key_material,
127                                                             AuthorizationSet* updated_description,
128                                                             uint64_t* public_exponent,
129                                                             uint32_t* key_size) const {
130     if (!updated_description || !public_exponent || !key_size)
131         return KM_ERROR_OUTPUT_PARAMETER_NULL;
132 
133     UniquePtr<EVP_PKEY, EVP_PKEY_Delete> pkey;
134     keymaster_error_t error =
135         KeyMaterialToEvpKey(key_format, key_material, keymaster_key_type(), &pkey);
136     if (error != KM_ERROR_OK)
137         return error;
138 
139     UniquePtr<RSA, RsaKey::RSA_Delete> rsa_key(EVP_PKEY_get1_RSA(pkey.get()));
140     if (!rsa_key.get())
141         return TranslateLastOpenSslError();
142 
143     updated_description->Reinitialize(key_description);
144 
145     *public_exponent = BN_get_word(rsa_key->e);
146     if (*public_exponent == 0xffffffffL)
147         return KM_ERROR_INVALID_KEY_BLOB;
148     if (!updated_description->GetTagValue(TAG_RSA_PUBLIC_EXPONENT, public_exponent))
149         updated_description->push_back(TAG_RSA_PUBLIC_EXPONENT, *public_exponent);
150     if (*public_exponent != BN_get_word(rsa_key->e)) {
151         LOG_E("Imported public exponent (%u) does not match specified public exponent (%u)",
152               *public_exponent, BN_get_word(rsa_key->e));
153         return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
154     }
155 
156     *key_size = RSA_size(rsa_key.get()) * 8;
157     if (!updated_description->GetTagValue(TAG_KEY_SIZE, key_size))
158         updated_description->push_back(TAG_KEY_SIZE, *key_size);
159     if (RSA_size(rsa_key.get()) * 8 != *key_size) {
160         LOG_E("Imported key size (%u bits) does not match specified key size (%u bits)",
161               RSA_size(rsa_key.get()) * 8, *key_size);
162         return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
163     }
164 
165     keymaster_algorithm_t algorithm = KM_ALGORITHM_RSA;
166     if (!updated_description->GetTagValue(TAG_ALGORITHM, &algorithm))
167         updated_description->push_back(TAG_ALGORITHM, KM_ALGORITHM_RSA);
168     if (algorithm != KM_ALGORITHM_RSA)
169         return KM_ERROR_IMPORT_PARAMETER_MISMATCH;
170 
171     return KM_ERROR_OK;
172 }
173 
CreateEmptyKey(AuthorizationSet && hw_enforced,AuthorizationSet && sw_enforced,UniquePtr<AsymmetricKey> * key) const174 keymaster_error_t RsaKeyFactory::CreateEmptyKey(AuthorizationSet&& hw_enforced,
175                                                 AuthorizationSet&& sw_enforced,
176                                                 UniquePtr<AsymmetricKey>* key) const {
177     key->reset(new (std::nothrow) RsaKey(move(hw_enforced), move(sw_enforced), this));
178     if (!(*key)) return KM_ERROR_MEMORY_ALLOCATION_FAILED;
179     return KM_ERROR_OK;
180 }
181 
182 }  // namespace keymaster
183