• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_km0_hardware(keymaster_algorithm_t algorithm) const = 0;
162     virtual int keymaster0_calls() const = 0;
minimal_digest_set()163     virtual int minimal_digest_set() const { return false; }
164 };
165 
166 // Use a shared_ptr because it's copyable.
167 typedef std::shared_ptr<Keymaster1TestInstanceCreator> InstanceCreatorPtr;
168 
169 const uint64_t OP_HANDLE_SENTINEL = 0xFFFFFFFFFFFFFFFF;
170 class Keymaster1Test : public testing::TestWithParam<InstanceCreatorPtr> {
171   protected:
172     Keymaster1Test();
173     ~Keymaster1Test();
174 
175     keymaster1_device_t* device();
176 
177     keymaster_error_t GenerateKey(const AuthorizationSetBuilder& builder);
178 
179     keymaster_error_t ImportKey(const AuthorizationSetBuilder& builder,
180                                 keymaster_key_format_t format, const std::string& key_material);
181 
182     keymaster_error_t ExportKey(keymaster_key_format_t format, std::string* export_data);
183 
184     keymaster_error_t GetCharacteristics();
185 
186     keymaster_error_t BeginOperation(keymaster_purpose_t purpose);
187     keymaster_error_t BeginOperation(keymaster_purpose_t purpose, const AuthorizationSet& input_set,
188                                      AuthorizationSet* output_set = NULL);
189 
190     keymaster_error_t UpdateOperation(const std::string& message, std::string* output,
191                                       size_t* input_consumed);
192     keymaster_error_t UpdateOperation(const AuthorizationSet& additional_params,
193                                       const std::string& message, AuthorizationSet* output_params,
194                                       std::string* output, size_t* input_consumed);
195 
196     keymaster_error_t FinishOperation(std::string* output);
197     keymaster_error_t FinishOperation(const std::string& signature, std::string* output);
FinishOperation(const AuthorizationSet & additional_params,const std::string & signature,std::string * output)198     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
199                                       const std::string& signature, std::string* output) {
200         return FinishOperation(additional_params, signature, nullptr /* output_params */, output);
201     }
202     keymaster_error_t FinishOperation(const AuthorizationSet& additional_params,
203                                       const std::string& signature, AuthorizationSet* output_params,
204                                       std::string* output);
205 
206     keymaster_error_t AbortOperation();
207 
208     keymaster_error_t GetVersion(uint8_t* major, uint8_t* minor, uint8_t* subminor);
209 
210     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message);
211     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
212                                const AuthorizationSet& begin_params,
213                                const AuthorizationSet& update_params,
214                                AuthorizationSet* output_params = NULL);
215     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
216                                const std::string& signature, const AuthorizationSet& begin_params,
217                                const AuthorizationSet& update_params,
218                                AuthorizationSet* output_params = NULL);
219     std::string ProcessMessage(keymaster_purpose_t purpose, const std::string& message,
220                                const std::string& signature);
221 
222     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest);
223     void SignMessage(const std::string& message, std::string* signature, keymaster_digest_t digest,
224                      keymaster_padding_t padding);
225     void MacMessage(const std::string& message, std::string* signature, size_t mac_length);
226 
227     void VerifyMessage(const std::string& message, const std::string& signature,
228                        keymaster_digest_t digest);
229     void VerifyMessage(const std::string& message, const std::string& signature,
230                        keymaster_digest_t digest, keymaster_padding_t padding);
231     void VerifyMac(const std::string& message, const std::string& signature);
232 
233     std::string EncryptMessage(const std::string& message, keymaster_padding_t padding,
234                                std::string* generated_nonce = NULL);
235     std::string EncryptMessage(const std::string& message, keymaster_digest_t digest,
236                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
237     std::string EncryptMessage(const std::string& message, keymaster_block_mode_t block_mode,
238                                keymaster_padding_t padding, std::string* generated_nonce = NULL);
239     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
240                                keymaster_digest_t digest, keymaster_padding_t padding,
241                                std::string* generated_nonce = NULL);
242     std::string EncryptMessage(const AuthorizationSet& update_params, const std::string& message,
243                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
244                                std::string* generated_nonce = NULL);
245     std::string EncryptMessageWithParams(const std::string& message,
246                                          const AuthorizationSet& begin_params,
247                                          const AuthorizationSet& update_params,
248                                          AuthorizationSet* output_params);
249 
250     std::string DecryptMessage(const std::string& ciphertext, keymaster_padding_t padding);
251     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
252                                keymaster_padding_t padding);
253     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
254                                keymaster_padding_t padding);
255     std::string DecryptMessage(const std::string& ciphertext, keymaster_digest_t digest,
256                                keymaster_padding_t padding, const std::string& nonce);
257     std::string DecryptMessage(const std::string& ciphertext, keymaster_block_mode_t block_mode,
258                                keymaster_padding_t padding, const std::string& nonce);
259     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
260                                keymaster_digest_t digest, keymaster_padding_t padding,
261                                const std::string& nonce);
262     std::string DecryptMessage(const AuthorizationSet& update_params, const std::string& ciphertext,
263                                keymaster_block_mode_t block_mode, keymaster_padding_t padding,
264                                const std::string& nonce);
265 
266     void CheckHmacTestVector(std::string key, std::string message, keymaster_digest_t digest,
267                              std::string expected_mac);
268     void CheckAesOcbTestVector(const std::string& key, const std::string& nonce,
269                                const std::string& associated_data, const std::string& message,
270                                const std::string& expected_ciphertext);
271     void CheckAesCtrTestVector(const std::string& key, const std::string& nonce,
272                                const std::string& message, const std::string& expected_ciphertext);
273     AuthorizationSet UserAuthParams();
274     AuthorizationSet ClientParams();
275 
276     template <typename T>
ResponseContains(const std::vector<T> & expected,const T * values,size_t len)277     bool ResponseContains(const std::vector<T>& expected, const T* values, size_t len) {
278         return expected.size() == len &&
279                std::is_permutation(values, values + len, expected.begin());
280     }
281 
ResponseContains(T expected,const T * values,size_t len)282     template <typename T> bool ResponseContains(T expected, const T* values, size_t len) {
283         return (len == 1 && *values == expected);
284     }
285 
286     AuthorizationSet hw_enforced();
287     AuthorizationSet sw_enforced();
288 
289     void FreeCharacteristics();
290     void FreeKeyBlob();
291 
292     void corrupt_key_blob();
293 
set_key_blob(const uint8_t * key,size_t key_length)294     void set_key_blob(const uint8_t* key, size_t key_length) {
295         FreeKeyBlob();
296         blob_.key_material = key;
297         blob_.key_material_size = key_length;
298     }
299 
client_params()300     AuthorizationSet client_params() {
301         return AuthorizationSet(client_params_, sizeof(client_params_) / sizeof(client_params_[0]));
302     }
303 
304   private:
305     keymaster1_device_t* device_;
306     keymaster_blob_t client_id_ = {.data = reinterpret_cast<const uint8_t*>("app_id"),
307                                    .data_length = 6};
308     keymaster_key_param_t client_params_[1] = {
309         Authorization(TAG_APPLICATION_ID, client_id_.data, client_id_.data_length)};
310 
311     uint64_t op_handle_;
312 
313     keymaster_key_blob_t blob_;
314     keymaster_key_characteristics_t* characteristics_;
315 };
316 
317 struct Keymaster0CountingWrapper : public keymaster0_device_t {
Keymaster0CountingWrapperKeymaster0CountingWrapper318     Keymaster0CountingWrapper(keymaster0_device_t* device) : device_(device), counter_(0) {
319         common = device_->common;
320         common.close = counting_close_device;
321         client_version = device_->client_version;
322         flags = device_->flags;
323         context = this;
324 
325         generate_keypair = counting_generate_keypair;
326         import_keypair = counting_import_keypair;
327         get_keypair_public = counting_get_keypair_public;
328         delete_keypair = counting_delete_keypair;
329         delete_all = counting_delete_all;
330         sign_data = counting_sign_data;
331         verify_data = counting_verify_data;
332     }
333 
countKeymaster0CountingWrapper334     int count() { return counter_; }
335 
336     // The blobs generated by the underlying softkeymaster start with "PK#8".  Tweak the prefix so
337     // they don't get identified as softkeymaster blobs.
munge_blobKeymaster0CountingWrapper338     static void munge_blob(uint8_t* blob, size_t blob_length) {
339         if (blob && blob_length > 0 && *blob == 'P')
340             *blob = 'Q';  // Mind your Ps and Qs!
341     }
342 
343     // Copy and un-modfy the blob.  The caller must clean up the return value.
unmunge_blobKeymaster0CountingWrapper344     static uint8_t* unmunge_blob(const uint8_t* blob, size_t blob_length) {
345         uint8_t* dup_blob = dup_buffer(blob, blob_length);
346         if (dup_blob && blob_length > 0 && *dup_blob == 'Q')
347             *dup_blob = 'P';
348         return dup_blob;
349     }
350 
deviceKeymaster0CountingWrapper351     static keymaster0_device_t* device(const keymaster0_device_t* dev) {
352         Keymaster0CountingWrapper* wrapper =
353             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
354         return wrapper->device_;
355     }
356 
incrementKeymaster0CountingWrapper357     static void increment(const keymaster0_device_t* dev) {
358         Keymaster0CountingWrapper* wrapper =
359             reinterpret_cast<Keymaster0CountingWrapper*>(dev->context);
360         wrapper->counter_++;
361     }
362 
counting_close_deviceKeymaster0CountingWrapper363     static int counting_close_device(hw_device_t* dev) {
364         keymaster0_device_t* k0_dev = reinterpret_cast<keymaster0_device_t*>(dev);
365         increment(k0_dev);
366         Keymaster0CountingWrapper* wrapper =
367             reinterpret_cast<Keymaster0CountingWrapper*>(k0_dev->context);
368         int retval =
369             wrapper->device_->common.close(reinterpret_cast<hw_device_t*>(wrapper->device_));
370         delete wrapper;
371         return retval;
372     }
373 
counting_generate_keypairKeymaster0CountingWrapper374     static int counting_generate_keypair(const struct keymaster0_device* dev,
375                                          const keymaster_keypair_t key_type, const void* key_params,
376                                          uint8_t** key_blob, size_t* key_blob_length) {
377         increment(dev);
378         int result = device(dev)->generate_keypair(device(dev), key_type, key_params, key_blob,
379                                                    key_blob_length);
380         if (result == 0)
381             munge_blob(*key_blob, *key_blob_length);
382         return result;
383     }
384 
counting_import_keypairKeymaster0CountingWrapper385     static int counting_import_keypair(const struct keymaster0_device* dev, const uint8_t* key,
386                                        const size_t key_length, uint8_t** key_blob,
387                                        size_t* key_blob_length) {
388         increment(dev);
389         int result =
390             device(dev)->import_keypair(device(dev), key, key_length, key_blob, key_blob_length);
391         if (result == 0)
392             munge_blob(*key_blob, *key_blob_length);
393         return result;
394     }
395 
counting_get_keypair_publicKeymaster0CountingWrapper396     static int counting_get_keypair_public(const struct keymaster0_device* dev,
397                                            const uint8_t* key_blob, const size_t key_blob_length,
398                                            uint8_t** x509_data, size_t* x509_data_length) {
399         increment(dev);
400         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
401         return device(dev)->get_keypair_public(device(dev), dup_blob.get(), key_blob_length,
402                                                x509_data, x509_data_length);
403     }
404 
counting_delete_keypairKeymaster0CountingWrapper405     static int counting_delete_keypair(const struct keymaster0_device* dev, const uint8_t* key_blob,
406                                        const size_t key_blob_length) {
407         increment(dev);
408         if (device(dev)->delete_keypair) {
409             std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
410             return device(dev)->delete_keypair(device(dev), dup_blob.get(), key_blob_length);
411         }
412         return 0;
413     }
414 
counting_delete_allKeymaster0CountingWrapper415     static int counting_delete_all(const struct keymaster0_device* dev) {
416         increment(dev);
417         if (device(dev)->delete_all)
418             return device(dev)->delete_all(device(dev));
419         return 0;
420     }
421 
counting_sign_dataKeymaster0CountingWrapper422     static int counting_sign_data(const struct keymaster0_device* dev, const void* signing_params,
423                                   const uint8_t* key_blob, const size_t key_blob_length,
424                                   const uint8_t* data, const size_t data_length,
425                                   uint8_t** signed_data, size_t* signed_data_length) {
426         increment(dev);
427         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
428         return device(dev)->sign_data(device(dev), signing_params, dup_blob.get(), key_blob_length,
429                                       data, data_length, signed_data, signed_data_length);
430     }
431 
counting_verify_dataKeymaster0CountingWrapper432     static int counting_verify_data(const struct keymaster0_device* dev, const void* signing_params,
433                                     const uint8_t* key_blob, const size_t key_blob_length,
434                                     const uint8_t* signed_data, const size_t signed_data_length,
435                                     const uint8_t* signature, const size_t signature_length) {
436         increment(dev);
437         std::unique_ptr<uint8_t[]> dup_blob(unmunge_blob(key_blob, key_blob_length));
438         return device(dev)->verify_data(device(dev), signing_params, dup_blob.get(),
439                                         key_blob_length, signed_data, signed_data_length, signature,
440                                         signature_length);
441     }
442 
443   private:
444     keymaster0_device_t* device_;
445     int counter_;
446 };
447 
448 
449 /**
450  * This function takes a keymaster1_device_t and wraps it in an adapter that supports only
451  * KM_DIGEST_SHA_2_256.
452  */
453 keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device);
454 
455 }  // namespace test
456 }  // namespace keymaster
457 
458 #endif  // SYSTEM_KEYMASTER_ANDROID_KEYMASTER_TEST_UTILS_H_
459