1 /*
2  * Copyright 2014 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 #ifndef SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
18 #define SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
19 
20 /*
21  * Utilities used to help with testing.  Not used in production code.
22  */
23 
24 #include <stdarg.h>
25 
26 #include <algorithm>
27 #include <memory>
28 #include <ostream>
29 #include <string>
30 #include <vector>
31 
32 #include <gtest/gtest.h>
33 
34 #include <hardware/keymaster0.h>
35 #include <hardware/keymaster1.h>
36 #include <hardware/keymaster_defs.h>
37 #include <keymaster/android_keymaster_utils.h>
38 #include <keymaster/authorization_set.h>
39 #include <keymaster/logger.h>
40 
41 std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param);
42 bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b);
43 std::string hex2str(std::string);
44 
45 namespace keymaster {
46 
47 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b);
48 bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b);
49 
50 std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set);
51 
52 namespace test {
53 
54 template <keymaster_tag_t Tag, typename KeymasterEnum>
contains(const AuthorizationSet & set,TypedEnumTag<KM_ENUM,Tag,KeymasterEnum> tag,KeymasterEnum val)55 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM, Tag, KeymasterEnum> tag,
56               KeymasterEnum val) {
57     int pos = set.find(tag);
58     return pos != -1 && set[pos].enumerated == val;
59 }
60 
61 template <keymaster_tag_t Tag, typename KeymasterEnum>
contains(const AuthorizationSet & set,TypedEnumTag<KM_ENUM_REP,Tag,KeymasterEnum> tag,KeymasterEnum val)62 bool contains(const AuthorizationSet& set, TypedEnumTag<KM_ENUM_REP, Tag, KeymasterEnum> tag,
63               KeymasterEnum val) {
64     int pos = -1;
65     while ((pos = set.find(tag, pos)) != -1)
66         if (set[pos].enumerated == val)
67             return true;
68     return false;
69 }
70 
71 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_UINT,Tag> tag,uint32_t val)72 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT, Tag> tag, uint32_t val) {
73     int pos = set.find(tag);
74     return pos != -1 && set[pos].integer == val;
75 }
76 
77 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_UINT_REP,Tag> tag,uint32_t val)78 bool contains(const AuthorizationSet& set, TypedTag<KM_UINT_REP, Tag> tag, uint32_t val) {
79     int pos = -1;
80     while ((pos = set.find(tag, pos)) != -1)
81         if (set[pos].integer == val)
82             return true;
83     return false;
84 }
85 
86 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_ULONG,Tag> tag,uint64_t val)87 bool contains(const AuthorizationSet& set, TypedTag<KM_ULONG, Tag> tag, uint64_t val) {
88     int pos = set.find(tag);
89     return pos != -1 && set[pos].long_integer == val;
90 }
91 
92 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_BYTES,Tag> tag,const std::string & val)93 bool contains(const AuthorizationSet& set, TypedTag<KM_BYTES, Tag> tag, const std::string& val) {
94     int pos = set.find(tag);
95     return pos != -1 &&
96            std::string(reinterpret_cast<const char*>(set[pos].blob.data),
97                        set[pos].blob.data_length) == val;
98 }
99 
100 template <keymaster_tag_t Tag>
contains(const AuthorizationSet & set,TypedTag<KM_BIGNUM,Tag> tag,const std::string & val)101 bool contains(const AuthorizationSet& set, TypedTag<KM_BIGNUM, Tag> tag, const std::string& val) {
102     int pos = set.find(tag);
103     return pos != -1 &&
104            std::string(reinterpret_cast<const char*>(set[pos].blob.data),
105                        set[pos].blob.data_length) == val;
106 }
107 
contains(const AuthorizationSet & set,keymaster_tag_t tag)108 inline bool contains(const AuthorizationSet& set, keymaster_tag_t tag) {
109     return set.find(tag) != -1;
110 }
111 
112 class StdoutLogger : public Logger {
113   public:
StdoutLogger()114     StdoutLogger() { set_instance(this); }
115 
log_msg(LogLevel level,const char * fmt,va_list args)116     int log_msg(LogLevel level, const char* fmt, va_list args) const {
117         int output_len = 0;
118         switch (level) {
119         case DEBUG_LVL:
120             output_len = printf("DEBUG: ");
121             break;
122         case INFO_LVL:
123             output_len = printf("INFO: ");
124             break;
125         case WARNING_LVL:
126             output_len = printf("WARNING: ");
127             break;
128         case ERROR_LVL:
129             output_len = printf("ERROR: ");
130             break;
131         case SEVERE_LVL:
132             output_len = printf("SEVERE: ");
133             break;
134         }
135 
136         output_len += vprintf(fmt, args);
137         output_len += printf("\n");
138         return output_len;
139     }
140 };
141 
make_string(const uint8_t * data,size_t length)142 inline std::string make_string(const uint8_t* data, size_t length) {
143     return std::string(reinterpret_cast<const char*>(data), length);
144 }
145 
make_string(const uint8_t (& a)[N])146 template <size_t N> std::string make_string(const uint8_t(&a)[N]) {
147     return make_string(a, N);
148 }
149 
150 /**
151  * Keymaster1TestInstance is used to parameterize Keymaster1Tests.  Its main function is to create a
152  * keymaster1_device_t to which test calls can be directed.  It also provides a place to specify
153  * various bits of alternative behavior, in cases where different devices are expected to behave
154  * differently (any such cases are a potential bug, but sometimes they may make sense).
155  */
156 class Keymaster1TestInstanceCreator {
157   public:
~Keymaster1TestInstanceCreator()158     virtual ~Keymaster1TestInstanceCreator(){};
159     virtual keymaster1_device_t* CreateDevice() const = 0;
160 
161     virtual bool algorithm_in_hardware(keymaster_algorithm_t algorithm) const = 0;
162     virtual int keymaster0_calls() const = 0;
163 };
164 
165 // Use a shared_ptr because it's copyable.
166 typedef std::shared_ptr<Keymaster1TestInstanceCreator> InstanceCreatorPtr;
167 
168 const uint64_t OP_HANDLE_SENTINEL = 0xFFFFFFFFFFFFFFFF;
169 class Keymaster1Test : public testing::TestWithParam<InstanceCreatorPtr> {
170   protected:
171     Keymaster1Test();
172     ~Keymaster1Test();
173 
174     keymaster1_device_t* device();
175 
176     keymaster_error_t GenerateKey(const AuthorizationSetBuilder& builder);
177 
178     keymaster_error_t ImportKey(const AuthorizationSetBuilder& builder,
179                                 keymaster_key_format_t format, const std::string& key_material);
180 
181     keymaster_error_t ExportKey(keymaster_key_format_t format, std::string* export_data);
182 
183     keymaster_error_t GetCharacteristics();
184 
185     keymaster_error_t BeginOperation(keymaster_purpose_t purpose);
186     keymaster_error_t BeginOperation(keymaster_purpose_t purpose, const AuthorizationSet& input_set,
187                                      AuthorizationSet* output_set = NULL);
188 
189     keymaster_error_t UpdateOperation(const std::string& message, std::string* output,
190                                       size_t* input_consumed);
191     keymaster_error_t UpdateOperation(const AuthorizationSet& additional_params,
192                                       const std::string& message, AuthorizationSet* output_params,
193                                       std::string* output, size_t* input_consumed);
194 
195     keymaster_error_t FinishOperation(std::string* output);
196     keymaster_error_t FinishOperation(const std::string& signature, std::string* output);
FinishOperation(const AuthorizationSet & additional_params,const std::string & signature,std::string * output)197     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
198                                       const std::string& signature, std::string* output) {
199         return FinishOperation(additional_params, signature, nullptr /* output_params */, output);
200     }
201     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
202                                       const std::string& signature, AuthorizationSet* output_params,
203                                       std::string* output);
204 
205     keymaster_error_t AbortOperation();
206 
207     keymaster_error_t GetVersion(uint8_t* major, uint8_t* minor, uint8_t* subminor);
208 
209     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message);
210     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
211                                const AuthorizationSet& begin_params,
212                                const AuthorizationSet& update_params,
213                                AuthorizationSet* output_params = NULL);
214     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
215                                const std::string& signature, const AuthorizationSet& begin_params,
216                                const AuthorizationSet& update_params,
217                                AuthorizationSet* output_params = NULL);
218     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
219                                const std::string& signature);
220 
221     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest);
222     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest,
223                      keymaster_padding_t padding);
224     void MacMessage(const std::string& message, std::string* signature, size_t mac_length);
225 
226     void VerifyMessage(const std::string& message, const std::string& signature,
227                        keymaster_digest_t digest);
228     void VerifyMessage(const std::string& message, const std::string& signature,
229                        keymaster_digest_t digest, keymaster_padding_t padding);
230     void VerifyMac(const std::string& message, const std::string& signature);
231 
232     std::string EncryptMessage(const std::string& message, keymaster_padding_t padding,
233                                std::string* generated_nonce = NULL);
234     std::string EncryptMessage(const std::string& message, keymaster_digest_t digest,
235                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
236     std::string EncryptMessage(const std::string& message, keymaster_block_mode_t block_mode,
237                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
238     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
239                                keymaster_digest_t digest, keymaster_padding_t padding,
240                                std::string* generated_nonce = NULL);
241     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
242                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
243                                std::string* generated_nonce = NULL);
244     std::string EncryptMessageWithParams(const std::string& message,
245                                          const AuthorizationSet& begin_params,
246                                          const AuthorizationSet& update_params,
247                                          AuthorizationSet* output_params);
248 
249     std::string DecryptMessage(const std::string& ciphertext, keymaster_padding_t padding);
250     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
251                                keymaster_padding_t padding);
252     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
253                                keymaster_padding_t padding);
254     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
255                                keymaster_padding_t padding, const std::string& nonce);
256     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
257                                keymaster_padding_t padding, const std::string& nonce);
258     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
259                                keymaster_digest_t digest, keymaster_padding_t padding,
260                                const std::string& nonce);
261     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
262                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
263                                const std::string& nonce);
264 
265     void CheckHmacTestVector(std::string key, std::string message, keymaster_digest_t digest,
266                              std::string expected_mac);
267     void CheckAesOcbTestVector(const std::string& key, const std::string& nonce,
268                                const std::string& associated_data, const std::string& message,
269                                const std::string& expected_ciphertext);
270     void CheckAesCtrTestVector(const std::string& key, const std::string& nonce,
271                                const std::string& message, const std::string& expected_ciphertext);
272     AuthorizationSet UserAuthParams();
273     AuthorizationSet ClientParams();
274 
275     template <typename T>
ResponseContains(const std::vector<T> & expected,const T * values,size_t len)276     bool ResponseContains(const std::vector<T>& expected, const T* values, size_t len) {
277         return expected.size() == len &&
278                std::is_permutation(values, values + len, expected.begin());
279     }
280 
ResponseContains(T expected,const T * values,size_t len)281     template <typename T> bool ResponseContains(T expected, const T* values, size_t len) {
282         return (len == 1 && *values == expected);
283     }
284 
285     AuthorizationSet hw_enforced();
286     AuthorizationSet sw_enforced();
287 
288     void FreeCharacteristics();
289     void FreeKeyBlob();
290 
291     void corrupt_key_blob();
292 
set_key_blob(const uint8_t * key,size_t key_length)293     void set_key_blob(const uint8_t* key, size_t key_length) {
294         FreeKeyBlob();
295         blob_.key_material = key;
296         blob_.key_material_size = key_length;
297     }
298 
client_params()299     AuthorizationSet client_params() {
300         return AuthorizationSet(client_params_, sizeof(client_params_) / sizeof(client_params_[0]));
301     }
302 
303   private:
304     keymaster1_device_t* device_;
305     keymaster_blob_t client_id_ = {.data = reinterpret_cast<const uint8_t*>("app_id"),
306                                    .data_length = 6};
307     keymaster_key_param_t client_params_[1] = {
308         Authorization(TAG_APPLICATION_ID, client_id_.data, client_id_.data_length)};
309 
310     uint64_t op_handle_;
311 
312     keymaster_key_blob_t blob_;
313     keymaster_key_characteristics_t* characteristics_;
314 };
315 
316 struct Keymaster0CountingWrapper : public keymaster0_device_t {
Keymaster0CountingWrapperKeymaster0CountingWrapper317     Keymaster0CountingWrapper(keymaster0_device_t* device) : device_(device), counter_(0) {
318         common = device_->common;
319         common.close = counting_close_device;
320         client_version = device_->client_version;
321         flags = device_->flags;
322         context = this;
323 
324         generate_keypair = counting_generate_keypair;
325         import_keypair = counting_import_keypair;
326         get_keypair_public = counting_get_keypair_public;
327         delete_keypair = counting_delete_keypair;
328         delete_all = counting_delete_all;
329         sign_data = counting_sign_data;
330         verify_data = counting_verify_data;
331     }
332 
countKeymaster0CountingWrapper333     int count() { return counter_; }
334 
335     // The blobs generated by the underlying softkeymaster start with "PK#8".  Tweak the prefix so
336     // they don't get identified as softkeymaster blobs.
munge_blobKeymaster0CountingWrapper337     static void munge_blob(uint8_t* blob, size_t blob_length) {
338         if (blob && blob_length > 0 && *blob == 'P')
339             *blob = 'Q';  // Mind your Ps and Qs!
340     }
341 
342     // Copy and un-modfy the blob.  The caller must clean up the return value.
unmunge_blobKeymaster0CountingWrapper343     static uint8_t* unmunge_blob(const uint8_t* blob, size_t blob_length) {
344         uint8_t* dup_blob = dup_buffer(blob, blob_length);
345         if (dup_blob && blob_length > 0 && *dup_blob == 'Q')
346             *dup_blob = 'P';
347         return dup_blob;
348     }
349 
deviceKeymaster0CountingWrapper350     static keymaster0_device_t* device(const keymaster0_device_t* dev) {
351         Keymaster0CountingWrapper* wrapper =
352             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
353         return wrapper->device_;
354     }
355 
incrementKeymaster0CountingWrapper356     static void increment(const keymaster0_device_t* dev) {
357         Keymaster0CountingWrapper* wrapper =
358             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
359         wrapper->counter_++;
360     }
361 
counting_close_deviceKeymaster0CountingWrapper362     static int counting_close_device(hw_device_t* dev) {
363         keymaster0_device_t* k0_dev = reinterpret_cast<keymaster0_device_t*>(dev);
364         increment(k0_dev);
365         Keymaster0CountingWrapper* wrapper =
366             reinterpret_cast<Keymaster0CountingWrapper*>(k0_dev->context);
367         int retval =
368             wrapper->device_->common.close(reinterpret_cast<hw_device_t*>(wrapper->device_));
369         delete wrapper;
370         return retval;
371     }
372 
counting_generate_keypairKeymaster0CountingWrapper373     static int counting_generate_keypair(const struct keymaster0_device* dev,
374                                          const keymaster_keypair_t key_type, const void* key_params,
375                                          uint8_t** key_blob, size_t* key_blob_length) {
376         increment(dev);
377         int result = device(dev)->generate_keypair(device(dev), key_type, key_params, key_blob,
378                                                    key_blob_length);
379         if (result == 0)
380             munge_blob(*key_blob, *key_blob_length);
381         return result;
382     }
383 
counting_import_keypairKeymaster0CountingWrapper384     static int counting_import_keypair(const struct keymaster0_device* dev, const uint8_t* key,
385                                        const size_t key_length, uint8_t** key_blob,
386                                        size_t* key_blob_length) {
387         increment(dev);
388         int result =
389             device(dev)->import_keypair(device(dev), key, key_length, key_blob, key_blob_length);
390         if (result == 0)
391             munge_blob(*key_blob, *key_blob_length);
392         return result;
393     }
394 
counting_get_keypair_publicKeymaster0CountingWrapper395     static int counting_get_keypair_public(const struct keymaster0_device* dev,
396                                            const uint8_t* key_blob, const size_t key_blob_length,
397                                            uint8_t** x509_data, size_t* x509_data_length) {
398         increment(dev);
399         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
400         return device(dev)->get_keypair_public(device(dev), dup_blob.get(), key_blob_length,
401                                                x509_data, x509_data_length);
402     }
403 
counting_delete_keypairKeymaster0CountingWrapper404     static int counting_delete_keypair(const struct keymaster0_device* dev, const uint8_t* key_blob,
405                                        const size_t key_blob_length) {
406         increment(dev);
407         if (device(dev)->delete_keypair) {
408             std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
409             return device(dev)->delete_keypair(device(dev), dup_blob.get(), key_blob_length);
410         }
411         return 0;
412     }
413 
counting_delete_allKeymaster0CountingWrapper414     static int counting_delete_all(const struct keymaster0_device* dev) {
415         increment(dev);
416         if (device(dev)->delete_all)
417             return device(dev)->delete_all(device(dev));
418         return 0;
419     }
420 
counting_sign_dataKeymaster0CountingWrapper421     static int counting_sign_data(const struct keymaster0_device* dev, const void* signing_params,
422                                   const uint8_t* key_blob, const size_t key_blob_length,
423                                   const uint8_t* data, const size_t data_length,
424                                   uint8_t** signed_data, size_t* signed_data_length) {
425         increment(dev);
426         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
427         return device(dev)->sign_data(device(dev), signing_params, dup_blob.get(), key_blob_length,
428                                       data, data_length, signed_data, signed_data_length);
429     }
430 
counting_verify_dataKeymaster0CountingWrapper431     static int counting_verify_data(const struct keymaster0_device* dev, const void* signing_params,
432                                     const uint8_t* key_blob, const size_t key_blob_length,
433                                     const uint8_t* signed_data, const size_t signed_data_length,
434                                     const uint8_t* signature, const size_t signature_length) {
435         increment(dev);
436         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
437         return device(dev)->verify_data(device(dev), signing_params, dup_blob.get(),
438                                         key_blob_length, signed_data, signed_data_length, signature,
439                                         signature_length);
440     }
441 
442   private:
443     keymaster0_device_t* device_;
444     int counter_;
445 };
446 
447 }  // namespace test
448 }  // namespace keymaster
449 
450 #endif  // SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
451