1 /*
2 **
3 ** Copyright 2017, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 #include <keymaster/legacy_support/keymaster1_legacy_support.h>
19 
20 #include <android-base/logging.h>
21 
22 #include <assert.h>
23 
24 #include <algorithm>
25 #include <vector>
26 
27 namespace keymaster {
28 
make_vector(const T * array,size_t len)29 template <typename T> std::vector<T> make_vector(const T* array, size_t len) {
30     return std::vector<T>(array, array + len);
31 }
32 
33 // This helper class implements just enough of the C++ standard collection interface to be able to
34 // accept push_back calls, and it does nothing but count them.  It's useful when you want to count
35 // insertions but not actually store anything.  It's used in digest_set_is_full below to count the
36 // size of a set intersection.
37 struct PushbackCounter {
38     struct value_type {
39         // NOLINTNEXTLINE(google-explicit-constructor)
value_typekeymaster::PushbackCounter::value_type40         template <typename T> value_type(const T&) {}
41     };
push_backkeymaster::PushbackCounter42     void push_back(const value_type&) { ++count; }
43     size_t count = 0;
44 };
45 
46 static std::vector<keymaster_digest_t> full_digest_list = {
47     KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
48     KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512};
49 
digest_set_is_full(Iter begin,Iter end)50 template <typename Iter> static bool digest_set_is_full(Iter begin, Iter end) {
51     PushbackCounter counter;
52     std::set_intersection(begin, end, full_digest_list.begin(), full_digest_list.end(),
53                           std::back_inserter(counter));
54     return counter.count == full_digest_list.size();
55 }
56 
add_digests(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,Keymaster1LegacySupport::DigestMap * map,bool * supports_all)57 static keymaster_error_t add_digests(const keymaster1_device_t* dev, keymaster_algorithm_t algorithm,
58                                      keymaster_purpose_t purpose,
59                                      Keymaster1LegacySupport::DigestMap* map, bool* supports_all) {
60     auto key = std::make_pair(algorithm, purpose);
61 
62     keymaster_digest_t* digests;
63     size_t digests_length;
64     keymaster_error_t error =
65         dev->get_supported_digests(dev, algorithm, purpose, &digests, &digests_length);
66     if (error != KM_ERROR_OK) {
67         LOG(ERROR) << "Error " << error << " getting supported digests from keymaster1 device";
68         return error;
69     }
70     std::unique_ptr<keymaster_digest_t, Malloc_Delete> digests_deleter(digests);
71 
72     auto digest_vec = make_vector(digests, digests_length);
73     *supports_all = digest_set_is_full(digest_vec.begin(), digest_vec.end());
74     (*map)[key] = std::move(digest_vec);
75     return error;
76 }
77 
map_digests(const keymaster1_device_t * dev,Keymaster1LegacySupport::DigestMap * map,bool * supports_all)78 static keymaster_error_t map_digests(const keymaster1_device_t* dev,
79                                      Keymaster1LegacySupport::DigestMap* map,
80                                      bool* supports_all) {
81     map->clear();
82     *supports_all = true;
83 
84     keymaster_algorithm_t sig_algorithms[] = {KM_ALGORITHM_RSA, KM_ALGORITHM_EC, KM_ALGORITHM_HMAC};
85     keymaster_purpose_t sig_purposes[] = {KM_PURPOSE_SIGN, KM_PURPOSE_VERIFY};
86     for (auto algorithm : sig_algorithms)
87         for (auto purpose : sig_purposes) {
88             bool alg_purpose_supports_all;
89             keymaster_error_t error =
90                 add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
91             if (error != KM_ERROR_OK)
92                 return error;
93             *supports_all &= alg_purpose_supports_all;
94         }
95 
96     keymaster_algorithm_t crypt_algorithms[] = {KM_ALGORITHM_RSA};
97     keymaster_purpose_t crypt_purposes[] = {KM_PURPOSE_ENCRYPT, KM_PURPOSE_DECRYPT};
98     for (auto algorithm : crypt_algorithms)
99         for (auto purpose : crypt_purposes) {
100             bool alg_purpose_supports_all;
101             keymaster_error_t error =
102                 add_digests(dev, algorithm, purpose, map, &alg_purpose_supports_all);
103             if (error != KM_ERROR_OK)
104                 return error;
105             *supports_all &= alg_purpose_supports_all;
106         }
107 
108     return KM_ERROR_OK;
109 }
110 
Keymaster1LegacySupport(const keymaster1_device_t * dev)111 Keymaster1LegacySupport::Keymaster1LegacySupport(const keymaster1_device_t* dev) {
112     map_digests(dev, &device_digests_, &supports_all_);
113 }
114 
contains(const Collection & c,const Value & v)115 template <typename Collection, typename Value> bool contains(const Collection& c, const Value& v) {
116     return std::find(c.begin(), c.end(), v) != c.end();
117 }
118 
119 template <typename T>
findUnsupportedDigest(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_digest_t digest,const T & params,const Keymaster1LegacySupport::DigestMap & digest_map)120 static bool findUnsupportedDigest(keymaster_algorithm_t algorithm,
121                                   keymaster_purpose_t purpose,
122                                   keymaster_digest_t digest,
123                                   const T& params,
124                                   const Keymaster1LegacySupport::DigestMap& digest_map) {
125     auto supported_digests = digest_map.find(std::make_pair(algorithm, purpose));
126     if (supported_digests == digest_map.end())
127         // Invalid algorith/purpose pair (e.g. EC encrypt).  Let the error be handled by HW module.
128         return false;
129 
130     if (digest != KM_DIGEST_NONE && !contains(supported_digests->second, digest)) {
131         LOG(WARNING) << "Digest " << digest << " requested but not supported by KM1 hal";
132         return true;
133     }
134 
135     for (auto& entry : params)
136         if (entry.tag == TAG_DIGEST)
137             if (!contains(supported_digests->second, entry.enumerated)) {
138                 LOG(WARNING) << "Digest " << entry.enumerated << " requested but not supported by KM1 hal";
139                 return true;
140             }
141     return false;
142 }
143 
144 template <typename T>
requiresSoftwareDigesting(keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_digest_t digest,const T & params,const Keymaster1LegacySupport::DigestMap & digest_map)145 bool requiresSoftwareDigesting(keymaster_algorithm_t algorithm, keymaster_purpose_t purpose,
146                                keymaster_digest_t digest,
147                                const T& params,
148                                const Keymaster1LegacySupport::DigestMap& digest_map) {
149     switch (algorithm) {
150     case KM_ALGORITHM_AES:
151     case KM_ALGORITHM_TRIPLE_DES:
152         LOG(WARNING) << "Not performing software digesting for symmetric cipher keys";
153         return false;
154     case KM_ALGORITHM_HMAC:
155     case KM_ALGORITHM_RSA:
156     case KM_ALGORITHM_EC:
157         break;
158     }
159 
160     if (!findUnsupportedDigest(algorithm, purpose, digest, params, digest_map)) {
161         LOG(DEBUG) << "Requested digest(s) supported for algorithm " << algorithm << " and purpose " << purpose;
162         return false;
163     }
164 
165     return true;
166 }
RequiresSoftwareDigesting(const AuthorizationSet & key_description) const167 bool Keymaster1LegacySupport::RequiresSoftwareDigesting(
168         const AuthorizationSet& key_description) const {
169 
170     keymaster_algorithm_t algorithm;
171     if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
172         // The hardware module will return an error during keygen.
173         return false;
174     }
175 
176     if (supports_all_) return false;
177 
178     bool has_purpose = false;
179     for (auto& entry : key_description)
180         if (entry.tag == TAG_PURPOSE) {
181             has_purpose = true;
182             keymaster_purpose_t purpose = static_cast<keymaster_purpose_t>(entry.enumerated);
183             if (requiresSoftwareDigesting(algorithm, purpose, KM_DIGEST_NONE, key_description,
184                                           device_digests_))
185                 return true;
186         }
187 
188     return !has_purpose;
189 }
190 
RequiresSoftwareDigesting(const keymaster_digest_t digest,const AuthProxy & key_description) const191 bool Keymaster1LegacySupport::RequiresSoftwareDigesting(const keymaster_digest_t digest,
192         const AuthProxy& key_description) const {
193 
194     keymaster_algorithm_t algorithm;
195     if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm)) {
196         // The hardware module will return an error during keygen.
197         return false;
198     }
199 
200     if (supports_all_) return false;
201 
202     bool has_purpose = false;
203     for (auto& entry : key_description) {
204         if (entry.tag == TAG_PURPOSE) {
205             has_purpose = true;
206             keymaster_purpose_t purpose = static_cast<keymaster_purpose_t>(entry.enumerated);
207             if (requiresSoftwareDigesting(algorithm, purpose, digest, key_description,
208                                           device_digests_))
209                 return true;
210         }
211     }
212 
213     /*
214      * If the key does not have a purpose it is unusable, i.e., for private key operations.
215      * The public key operations which don't need purpose authorization may as well be done
216      * in software. This also addresses a bug by which begin operation on keys without purpose and
217      * unauthorized digest which is also not supported by the wrapped KM1 device fail with
218      * KM_UNSUPPORTED_DIGEST although they should not fail during the begin operation.
219      * If it has a purpose and we reach this point we did not find unsupported digests, and
220      * therefore do not required software digesting.
221      */
222     return !has_purpose;
223 }
224 
225 template<>
226 keymaster_error_t
GenerateKey(const AuthorizationSet & key_description,KeymasterKeyBlob * key_blob,AuthorizationSet * hw_enforced,AuthorizationSet * sw_enforced) const227 Keymaster1ArbitrationFactory<EcdsaKeymaster1KeyFactory>::GenerateKey(
228         const AuthorizationSet& key_description,
229         KeymasterKeyBlob* key_blob, AuthorizationSet* hw_enforced,
230         AuthorizationSet* sw_enforced) const {
231     if (legacy_support_.RequiresSoftwareDigesting(key_description)) {
232         return software_digest_factory_.GenerateKey(key_description, key_blob, hw_enforced,
233                                              sw_enforced);
234     } else {
235         AuthorizationSet mutable_key_description = key_description;
236         keymaster_ec_curve_t curve;
237         if (key_description.GetTagValue(TAG_EC_CURVE, &curve)) {
238             // Keymaster1 doesn't know about EC curves. We need to translate to key size.
239             uint32_t key_size_from_curve;
240             keymaster_error_t error = EcCurveToKeySize(curve, &key_size_from_curve);
241             if (error != KM_ERROR_OK) {
242                 return error;
243             }
244 
245             uint32_t key_size_from_desc;
246             if (key_description.GetTagValue(TAG_KEY_SIZE, &key_size_from_desc)) {
247                 if (key_size_from_desc != key_size_from_curve) {
248                     return KM_ERROR_INVALID_ARGUMENT;
249                 }
250             } else {
251                 mutable_key_description.push_back(TAG_KEY_SIZE, key_size_from_curve);
252             }
253         }
254 
255         return passthrough_factory_.GenerateKey(mutable_key_description, key_blob, hw_enforced,
256                                                 sw_enforced);
257     }
258 }
259 
260 template<>
261 keymaster_error_t
LoadKey(KeymasterKeyBlob && key_material,const AuthorizationSet & additional_params,AuthorizationSet && hw_enforced,AuthorizationSet && sw_enforced,UniquePtr<Key> * key) const262 Keymaster1ArbitrationFactory<EcdsaKeymaster1KeyFactory>::LoadKey(KeymasterKeyBlob&& key_material,
263         const AuthorizationSet& additional_params,
264         AuthorizationSet&& hw_enforced,
265         AuthorizationSet&& sw_enforced,
266         UniquePtr<Key>* key) const {
267     keymaster_digest_t digest;
268     if (!additional_params.GetTagValue(TAG_DIGEST, &digest)) {
269         digest = KM_DIGEST_NONE;
270     }
271     bool requires_software_digesting = legacy_support_.RequiresSoftwareDigesting(digest,
272                                                            AuthProxy(hw_enforced, sw_enforced));
273     auto rc = software_digest_factory_.LoadKey(move(key_material), additional_params,
274                                                move(hw_enforced), move(sw_enforced), key);
275     if (rc != KM_ERROR_OK) return rc;
276     if (!requires_software_digesting) {
277         (*key)->key_factory() = & passthrough_factory_;
278     }
279     return KM_ERROR_OK;
280 }
281 
282 template<>
283 keymaster_error_t
LoadKey(KeymasterKeyBlob && key_material,const AuthorizationSet & additional_params,AuthorizationSet && hw_enforced,AuthorizationSet && sw_enforced,UniquePtr<Key> * key) const284 Keymaster1ArbitrationFactory<RsaKeymaster1KeyFactory>::LoadKey(KeymasterKeyBlob&& key_material,
285         const AuthorizationSet& additional_params,
286         AuthorizationSet&& hw_enforced,
287         AuthorizationSet&& sw_enforced,
288         UniquePtr<Key>* key) const {
289     keymaster_digest_t digest;
290     if (!additional_params.GetTagValue(TAG_DIGEST, &digest)) {
291         digest = KM_DIGEST_NONE;
292     }
293     bool requires_software_digesting = legacy_support_.RequiresSoftwareDigesting(digest,
294                                                            AuthProxy(hw_enforced, sw_enforced));
295     auto rc = software_digest_factory_.LoadKey(move(key_material), additional_params,
296                                                move(hw_enforced), move(sw_enforced), key);
297     if (rc != KM_ERROR_OK) return rc;
298     if (!requires_software_digesting) {
299         (*key)->key_factory() = & passthrough_factory_;
300     }
301     return KM_ERROR_OK;
302 }
303 
304 
305 } // namespace keymaster
306