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