• 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 #include "android_keymaster_test_utils.h"
18 
19 #include <algorithm>
20 
21 #include <openssl/rand.h>
22 
23 #include <keymaster/android_keymaster_messages.h>
24 #include <keymaster/android_keymaster_utils.h>
25 
26 using std::copy_if;
27 using std::find_if;
28 using std::is_permutation;
29 using std::ostream;
30 using std::string;
31 using std::vector;
32 
operator <<(std::ostream & os,const keymaster_key_param_t & param)33 std::ostream& operator<<(std::ostream& os, const keymaster_key_param_t& param) {
34     os << "Tag: " << keymaster_tag_mask_type(param.tag);
35     switch (keymaster_tag_get_type(param.tag)) {
36     case KM_INVALID:
37         os << " Invalid";
38         break;
39     case KM_UINT_REP:
40         os << " (Rep)";
41     /* Falls through */
42     case KM_UINT:
43         os << " Int: " << param.integer;
44         break;
45     case KM_ENUM_REP:
46         os << " (Rep)";
47     /* Falls through */
48     case KM_ENUM:
49         os << " Enum: " << param.enumerated;
50         break;
51     case KM_ULONG_REP:
52         os << " (Rep)";
53     /* Falls through */
54     case KM_ULONG:
55         os << " Long: " << param.long_integer;
56         break;
57     case KM_DATE:
58         os << " Date: " << param.date_time;
59         break;
60     case KM_BOOL:
61         os << " Bool: " << param.boolean;
62         break;
63     case KM_BIGNUM:
64         os << " Bignum: ";
65         break;
66     case KM_BYTES:
67         os << " Bytes: ";
68         break;
69     }
70     return os;
71 }
72 
operator ==(const keymaster_key_param_t & a,const keymaster_key_param_t & b)73 bool operator==(const keymaster_key_param_t& a, const keymaster_key_param_t& b) {
74     if (a.tag != b.tag) {
75         return false;
76     }
77 
78     switch (keymaster_tag_get_type(a.tag)) {
79     case KM_INVALID:
80         return true;
81     case KM_UINT_REP:
82     case KM_UINT:
83         return a.integer == b.integer;
84     case KM_ENUM_REP:
85     case KM_ENUM:
86         return a.enumerated == b.enumerated;
87     case KM_ULONG:
88     case KM_ULONG_REP:
89         return a.long_integer == b.long_integer;
90     case KM_DATE:
91         return a.date_time == b.date_time;
92     case KM_BOOL:
93         return a.boolean == b.boolean;
94     case KM_BIGNUM:
95     case KM_BYTES:
96         if ((a.blob.data == NULL || b.blob.data == NULL) && a.blob.data != b.blob.data)
97             return false;
98         return a.blob.data_length == b.blob.data_length &&
99                (memcmp(a.blob.data, b.blob.data, a.blob.data_length) == 0);
100     }
101 
102     return false;
103 }
104 
105 static char hex_value[256] = {
106     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
107     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
108     0, 1,  2,  3,  4,  5,  6,  7, 8, 9, 0, 0, 0, 0, 0, 0,  // '0'..'9'
109     0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0,  // 'A'..'F'
110     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0,
111     0, 0,  0,  0,  0,  0,  0,  0,  // 'a'..'f'
112     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
113     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
114     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
115     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
116     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0,
117     0, 0,  0,  0,  0,  0,  0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0,  0,  0,  0,  0,  0};
118 
hex2str(string a)119 string hex2str(string a) {
120     string b;
121     size_t num = a.size() / 2;
122     b.resize(num);
123     for (size_t i = 0; i < num; i++) {
124         b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
125     }
126     return b;
127 }
128 
129 namespace keymaster {
130 
operator ==(const AuthorizationSet & a,const AuthorizationSet & b)131 bool operator==(const AuthorizationSet& a, const AuthorizationSet& b) {
132     if (a.size() != b.size())
133         return false;
134 
135     for (size_t i = 0; i < a.size(); ++i)
136         if (!(a[i] == b[i]))
137             return false;
138     return true;
139 }
140 
operator !=(const AuthorizationSet & a,const AuthorizationSet & b)141 bool operator!=(const AuthorizationSet& a, const AuthorizationSet& b) {
142     return !(a == b);
143 }
144 
operator <<(std::ostream & os,const AuthorizationSet & set)145 std::ostream& operator<<(std::ostream& os, const AuthorizationSet& set) {
146     if (set.size() == 0)
147         os << "(Empty)" << std::endl;
148     for (size_t i = 0; i < set.size(); ++i) {
149         os << set[i] << std::endl;
150     }
151     return os;
152 }
153 
154 namespace test {
155 
Keymaster1Test()156 Keymaster1Test::Keymaster1Test() : op_handle_(OP_HANDLE_SENTINEL), characteristics_(NULL) {
157     blob_.key_material = NULL;
158     RAND_seed("foobar", 6);
159     blob_.key_material = 0;
160     device_ = GetParam()->CreateDevice();
161 }
162 
~Keymaster1Test()163 Keymaster1Test::~Keymaster1Test() {
164     FreeCharacteristics();
165     FreeKeyBlob();
166     device_->common.close(reinterpret_cast<hw_device_t*>(device_));
167 }
168 
device()169 keymaster1_device_t* Keymaster1Test::device() {
170     return device_;
171 }
172 
GenerateKey(const AuthorizationSetBuilder & builder)173 keymaster_error_t Keymaster1Test::GenerateKey(const AuthorizationSetBuilder& builder) {
174     AuthorizationSet params(builder.build());
175     params.push_back(UserAuthParams());
176     params.push_back(ClientParams());
177 
178     FreeKeyBlob();
179     FreeCharacteristics();
180     return device()->generate_key(device(), &params, &blob_, &characteristics_);
181 }
182 
ImportKey(const AuthorizationSetBuilder & builder,keymaster_key_format_t format,const string & key_material)183 keymaster_error_t Keymaster1Test::ImportKey(const AuthorizationSetBuilder& builder,
184                                             keymaster_key_format_t format,
185                                             const string& key_material) {
186     AuthorizationSet params(builder.build());
187     params.push_back(UserAuthParams());
188     params.push_back(ClientParams());
189 
190     FreeKeyBlob();
191     FreeCharacteristics();
192     keymaster_blob_t key = {reinterpret_cast<const uint8_t*>(key_material.c_str()),
193                             key_material.length()};
194     return device()->import_key(device(), &params, format, &key, &blob_, &characteristics_);
195 }
196 
UserAuthParams()197 AuthorizationSet Keymaster1Test::UserAuthParams() {
198     AuthorizationSet set;
199     set.push_back(TAG_USER_ID, 7);
200     set.push_back(TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD);
201     set.push_back(TAG_AUTH_TIMEOUT, 300);
202     return set;
203 }
204 
ClientParams()205 AuthorizationSet Keymaster1Test::ClientParams() {
206     AuthorizationSet set;
207     set.push_back(TAG_APPLICATION_ID, "app_id", 6);
208     return set;
209 }
210 
BeginOperation(keymaster_purpose_t purpose)211 keymaster_error_t Keymaster1Test::BeginOperation(keymaster_purpose_t purpose) {
212     AuthorizationSet in_params(client_params());
213     keymaster_key_param_set_t out_params;
214     keymaster_error_t error =
215         device()->begin(device(), purpose, &blob_, &in_params, &out_params, &op_handle_);
216     EXPECT_EQ(0U, out_params.length);
217     EXPECT_TRUE(out_params.params == nullptr);
218     return error;
219 }
220 
BeginOperation(keymaster_purpose_t purpose,const AuthorizationSet & input_set,AuthorizationSet * output_set)221 keymaster_error_t Keymaster1Test::BeginOperation(keymaster_purpose_t purpose,
222                                                  const AuthorizationSet& input_set,
223                                                  AuthorizationSet* output_set) {
224     keymaster_key_param_set_t out_params;
225     keymaster_error_t error =
226         device()->begin(device(), purpose, &blob_, &input_set, &out_params, &op_handle_);
227     if (error == KM_ERROR_OK) {
228         if (output_set) {
229             output_set->Reinitialize(out_params);
230         } else {
231             EXPECT_EQ(0U, out_params.length);
232             EXPECT_TRUE(out_params.params == nullptr);
233         }
234         keymaster_free_param_set(&out_params);
235     }
236     return error;
237 }
238 
UpdateOperation(const string & message,string * output,size_t * input_consumed)239 keymaster_error_t Keymaster1Test::UpdateOperation(const string& message, string* output,
240                                                   size_t* input_consumed) {
241     EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
242     keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
243     keymaster_blob_t out_tmp;
244     keymaster_key_param_set_t out_params;
245     keymaster_error_t error = device()->update(device(), op_handle_, nullptr /* params */, &input,
246                                                input_consumed, &out_params, &out_tmp);
247     if (error == KM_ERROR_OK && out_tmp.data)
248         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
249     free(const_cast<uint8_t*>(out_tmp.data));
250     return error;
251 }
252 
UpdateOperation(const AuthorizationSet & additional_params,const string & message,AuthorizationSet * output_params,string * output,size_t * input_consumed)253 keymaster_error_t Keymaster1Test::UpdateOperation(const AuthorizationSet& additional_params,
254                                                   const string& message,
255                                                   AuthorizationSet* output_params, string* output,
256                                                   size_t* input_consumed) {
257     EXPECT_NE(op_handle_, OP_HANDLE_SENTINEL);
258     keymaster_blob_t input = {reinterpret_cast<const uint8_t*>(message.c_str()), message.length()};
259     keymaster_blob_t out_tmp;
260     keymaster_key_param_set_t out_params;
261     keymaster_error_t error = device()->update(device(), op_handle_, &additional_params, &input,
262                                                input_consumed, &out_params, &out_tmp);
263     if (error == KM_ERROR_OK && out_tmp.data)
264         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
265     free((void*)out_tmp.data);
266     if (output_params)
267         output_params->Reinitialize(out_params);
268     keymaster_free_param_set(&out_params);
269     return error;
270 }
271 
FinishOperation(string * output)272 keymaster_error_t Keymaster1Test::FinishOperation(string* output) {
273     return FinishOperation("", output);
274 }
275 
FinishOperation(const string & signature,string * output)276 keymaster_error_t Keymaster1Test::FinishOperation(const string& signature, string* output) {
277     AuthorizationSet additional_params;
278     AuthorizationSet output_params;
279     return FinishOperation(additional_params, signature, &output_params, output);
280 }
281 
FinishOperation(const AuthorizationSet & additional_params,const string & signature,AuthorizationSet * output_params,string * output)282 keymaster_error_t Keymaster1Test::FinishOperation(const AuthorizationSet& additional_params,
283                                                   const string& signature,
284                                                   AuthorizationSet* output_params, string* output) {
285     keymaster_blob_t sig = {reinterpret_cast<const uint8_t*>(signature.c_str()),
286                             signature.length()};
287     keymaster_blob_t out_tmp;
288     keymaster_key_param_set_t out_params;
289     keymaster_error_t error =
290         device()->finish(device(), op_handle_, &additional_params, &sig, &out_params, &out_tmp);
291     if (error != KM_ERROR_OK) {
292         EXPECT_TRUE(out_tmp.data == nullptr);
293         EXPECT_TRUE(out_params.params == nullptr);
294         return error;
295     }
296 
297     if (out_tmp.data)
298         output->append(reinterpret_cast<const char*>(out_tmp.data), out_tmp.data_length);
299     free((void*)out_tmp.data);
300     if (output_params)
301         output_params->Reinitialize(out_params);
302     keymaster_free_param_set(&out_params);
303     return error;
304 }
305 
AbortOperation()306 keymaster_error_t Keymaster1Test::AbortOperation() {
307     return device()->abort(device(), op_handle_);
308 }
309 
ProcessMessage(keymaster_purpose_t purpose,const string & message)310 string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message) {
311     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
312 
313     string result;
314     size_t input_consumed;
315     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
316     EXPECT_EQ(message.size(), input_consumed);
317     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&result));
318     return result;
319 }
320 
ProcessMessage(keymaster_purpose_t purpose,const string & message,const AuthorizationSet & begin_params,const AuthorizationSet & update_params,AuthorizationSet * begin_out_params)321 string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
322                                       const AuthorizationSet& begin_params,
323                                       const AuthorizationSet& update_params,
324                                       AuthorizationSet* begin_out_params) {
325     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, begin_out_params));
326 
327     string result;
328     size_t input_consumed;
329     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, nullptr /* output_params */,
330                                            &result, &input_consumed));
331     EXPECT_EQ(message.size(), input_consumed);
332     EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, "", &result));
333     return result;
334 }
335 
ProcessMessage(keymaster_purpose_t purpose,const string & message,const string & signature,const AuthorizationSet & begin_params,const AuthorizationSet & update_params,AuthorizationSet * output_params)336 string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
337                                       const string& signature, const AuthorizationSet& begin_params,
338                                       const AuthorizationSet& update_params,
339                                       AuthorizationSet* output_params) {
340     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params, output_params));
341 
342     string result;
343     size_t input_consumed;
344     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, nullptr /* output_params */,
345                                            &result, &input_consumed));
346     EXPECT_EQ(message.size(), input_consumed);
347     EXPECT_EQ(KM_ERROR_OK, FinishOperation(update_params, signature, &result));
348     return result;
349 }
350 
ProcessMessage(keymaster_purpose_t purpose,const string & message,const string & signature)351 string Keymaster1Test::ProcessMessage(keymaster_purpose_t purpose, const string& message,
352                                       const string& signature) {
353     EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, client_params(), NULL /* output_params */));
354 
355     string result;
356     size_t input_consumed;
357     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
358     EXPECT_EQ(message.size(), input_consumed);
359     EXPECT_EQ(KM_ERROR_OK, FinishOperation(signature, &result));
360     return result;
361 }
362 
SignMessage(const string & message,string * signature,keymaster_digest_t digest)363 void Keymaster1Test::SignMessage(const string& message, string* signature,
364                                  keymaster_digest_t digest) {
365     SCOPED_TRACE("SignMessage");
366     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
367     input_params.push_back(TAG_DIGEST, digest);
368     AuthorizationSet update_params;
369     AuthorizationSet output_params;
370     *signature =
371         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
372     EXPECT_GT(signature->size(), 0U);
373 }
374 
SignMessage(const string & message,string * signature,keymaster_digest_t digest,keymaster_padding_t padding)375 void Keymaster1Test::SignMessage(const string& message, string* signature,
376                                  keymaster_digest_t digest, keymaster_padding_t padding) {
377     SCOPED_TRACE("SignMessage");
378     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
379     input_params.push_back(TAG_DIGEST, digest);
380     input_params.push_back(TAG_PADDING, padding);
381     AuthorizationSet update_params;
382     AuthorizationSet output_params;
383     *signature =
384         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
385     EXPECT_GT(signature->size(), 0U);
386 }
387 
MacMessage(const string & message,string * signature,size_t mac_length)388 void Keymaster1Test::MacMessage(const string& message, string* signature, size_t mac_length) {
389     SCOPED_TRACE("SignMessage");
390     AuthorizationSet input_params(AuthorizationSet(client_params_, array_length(client_params_)));
391     input_params.push_back(TAG_MAC_LENGTH, mac_length);
392     AuthorizationSet update_params;
393     AuthorizationSet output_params;
394     *signature =
395         ProcessMessage(KM_PURPOSE_SIGN, message, input_params, update_params, &output_params);
396     EXPECT_GT(signature->size(), 0U);
397 }
398 
VerifyMessage(const string & message,const string & signature,keymaster_digest_t digest)399 void Keymaster1Test::VerifyMessage(const string& message, const string& signature,
400                                    keymaster_digest_t digest) {
401     SCOPED_TRACE("VerifyMessage");
402     AuthorizationSet input_params(client_params());
403     input_params.push_back(TAG_DIGEST, digest);
404     AuthorizationSet update_params;
405     AuthorizationSet output_params;
406     ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
407                    &output_params);
408 }
409 
VerifyMessage(const string & message,const string & signature,keymaster_digest_t digest,keymaster_padding_t padding)410 void Keymaster1Test::VerifyMessage(const string& message, const string& signature,
411                                    keymaster_digest_t digest, keymaster_padding_t padding) {
412     SCOPED_TRACE("VerifyMessage");
413     AuthorizationSet input_params(client_params());
414     input_params.push_back(TAG_DIGEST, digest);
415     input_params.push_back(TAG_PADDING, padding);
416     AuthorizationSet update_params;
417     AuthorizationSet output_params;
418     ProcessMessage(KM_PURPOSE_VERIFY, message, signature, input_params, update_params,
419                    &output_params);
420 }
421 
VerifyMac(const string & message,const string & signature)422 void Keymaster1Test::VerifyMac(const string& message, const string& signature) {
423     SCOPED_TRACE("VerifyMac");
424     ProcessMessage(KM_PURPOSE_VERIFY, message, signature);
425 }
426 
EncryptMessage(const string & message,keymaster_padding_t padding,string * generated_nonce)427 string Keymaster1Test::EncryptMessage(const string& message, keymaster_padding_t padding,
428                                       string* generated_nonce) {
429     SCOPED_TRACE("EncryptMessage");
430     AuthorizationSet begin_params(client_params()), output_params;
431     begin_params.push_back(TAG_PADDING, padding);
432     AuthorizationSet update_params;
433     string ciphertext =
434         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
435     if (generated_nonce) {
436         keymaster_blob_t nonce_blob;
437         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
438         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
439     } else {
440         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
441     }
442     return ciphertext;
443 }
444 
EncryptMessage(const string & message,keymaster_digest_t digest,keymaster_padding_t padding,string * generated_nonce)445 string Keymaster1Test::EncryptMessage(const string& message, keymaster_digest_t digest,
446                                       keymaster_padding_t padding, string* generated_nonce) {
447     AuthorizationSet update_params;
448     return EncryptMessage(update_params, message, digest, padding, generated_nonce);
449 }
450 
EncryptMessage(const string & message,keymaster_block_mode_t block_mode,keymaster_padding_t padding,string * generated_nonce)451 string Keymaster1Test::EncryptMessage(const string& message, keymaster_block_mode_t block_mode,
452                                       keymaster_padding_t padding, string* generated_nonce) {
453     AuthorizationSet update_params;
454     return EncryptMessage(update_params, message, block_mode, padding, generated_nonce);
455 }
456 
EncryptMessage(const AuthorizationSet & update_params,const string & message,keymaster_digest_t digest,keymaster_padding_t padding,string * generated_nonce)457 string Keymaster1Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
458                                       keymaster_digest_t digest, keymaster_padding_t padding,
459                                       string* generated_nonce) {
460     SCOPED_TRACE("EncryptMessage");
461     AuthorizationSet begin_params(client_params()), output_params;
462     begin_params.push_back(TAG_PADDING, padding);
463     begin_params.push_back(TAG_DIGEST, digest);
464     string ciphertext =
465         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
466     if (generated_nonce) {
467         keymaster_blob_t nonce_blob;
468         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
469         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
470     } else {
471         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
472     }
473     return ciphertext;
474 }
475 
EncryptMessage(const AuthorizationSet & update_params,const string & message,keymaster_block_mode_t block_mode,keymaster_padding_t padding,string * generated_nonce)476 string Keymaster1Test::EncryptMessage(const AuthorizationSet& update_params, const string& message,
477                                       keymaster_block_mode_t block_mode,
478                                       keymaster_padding_t padding, string* generated_nonce) {
479     SCOPED_TRACE("EncryptMessage");
480     AuthorizationSet begin_params(client_params()), output_params;
481     begin_params.push_back(TAG_PADDING, padding);
482     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
483     string ciphertext =
484         ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, &output_params);
485     if (generated_nonce) {
486         keymaster_blob_t nonce_blob;
487         EXPECT_TRUE(output_params.GetTagValue(TAG_NONCE, &nonce_blob));
488         *generated_nonce = make_string(nonce_blob.data, nonce_blob.data_length);
489     } else {
490         EXPECT_EQ(-1, output_params.find(TAG_NONCE));
491     }
492     return ciphertext;
493 }
494 
EncryptMessageWithParams(const string & message,const AuthorizationSet & begin_params,const AuthorizationSet & update_params,AuthorizationSet * output_params)495 string Keymaster1Test::EncryptMessageWithParams(const string& message,
496                                                 const AuthorizationSet& begin_params,
497                                                 const AuthorizationSet& update_params,
498                                                 AuthorizationSet* output_params) {
499     SCOPED_TRACE("EncryptMessageWithParams");
500     return ProcessMessage(KM_PURPOSE_ENCRYPT, message, begin_params, update_params, output_params);
501 }
502 
DecryptMessage(const string & ciphertext,keymaster_padding_t padding)503 string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_padding_t padding) {
504     SCOPED_TRACE("DecryptMessage");
505     AuthorizationSet begin_params(client_params());
506     begin_params.push_back(TAG_PADDING, padding);
507     AuthorizationSet update_params;
508     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
509 }
510 
DecryptMessage(const string & ciphertext,keymaster_digest_t digest,keymaster_padding_t padding)511 string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
512                                       keymaster_padding_t padding) {
513     SCOPED_TRACE("DecryptMessage");
514     AuthorizationSet begin_params(client_params());
515     begin_params.push_back(TAG_PADDING, padding);
516     begin_params.push_back(TAG_DIGEST, digest);
517     AuthorizationSet update_params;
518     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
519 }
520 
DecryptMessage(const string & ciphertext,keymaster_block_mode_t block_mode,keymaster_padding_t padding)521 string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
522                                       keymaster_padding_t padding) {
523     SCOPED_TRACE("DecryptMessage");
524     AuthorizationSet begin_params(client_params());
525     begin_params.push_back(TAG_PADDING, padding);
526     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
527     AuthorizationSet update_params;
528     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
529 }
530 
DecryptMessage(const string & ciphertext,keymaster_digest_t digest,keymaster_padding_t padding,const string & nonce)531 string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_digest_t digest,
532                                       keymaster_padding_t padding, const string& nonce) {
533     SCOPED_TRACE("DecryptMessage");
534     AuthorizationSet begin_params(client_params());
535     begin_params.push_back(TAG_PADDING, padding);
536     begin_params.push_back(TAG_DIGEST, digest);
537     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
538     AuthorizationSet update_params;
539     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
540 }
541 
DecryptMessage(const string & ciphertext,keymaster_block_mode_t block_mode,keymaster_padding_t padding,const string & nonce)542 string Keymaster1Test::DecryptMessage(const string& ciphertext, keymaster_block_mode_t block_mode,
543                                       keymaster_padding_t padding, const string& nonce) {
544     SCOPED_TRACE("DecryptMessage");
545     AuthorizationSet begin_params(client_params());
546     begin_params.push_back(TAG_PADDING, padding);
547     begin_params.push_back(TAG_BLOCK_MODE, block_mode);
548     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
549     AuthorizationSet update_params;
550     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
551 }
552 
DecryptMessage(const AuthorizationSet & update_params,const string & ciphertext,keymaster_digest_t digest,keymaster_padding_t padding,const string & nonce)553 string Keymaster1Test::DecryptMessage(const AuthorizationSet& update_params,
554                                       const string& ciphertext, keymaster_digest_t digest,
555                                       keymaster_padding_t padding, const string& nonce) {
556     SCOPED_TRACE("DecryptMessage");
557     AuthorizationSet begin_params(client_params());
558     begin_params.push_back(TAG_PADDING, padding);
559     begin_params.push_back(TAG_DIGEST, digest);
560     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
561     return ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, begin_params, update_params);
562 }
563 
GetCharacteristics()564 keymaster_error_t Keymaster1Test::GetCharacteristics() {
565     FreeCharacteristics();
566     return device()->get_key_characteristics(device(), &blob_, &client_id_, NULL /* app_data */,
567                                              &characteristics_);
568 }
569 
ExportKey(keymaster_key_format_t format,string * export_data)570 keymaster_error_t Keymaster1Test::ExportKey(keymaster_key_format_t format, string* export_data) {
571     keymaster_blob_t export_tmp;
572     keymaster_error_t error = device()->export_key(device(), format, &blob_, &client_id_,
573                                                    NULL /* app_data */, &export_tmp);
574 
575     if (error != KM_ERROR_OK)
576         return error;
577 
578     *export_data = string(reinterpret_cast<const char*>(export_tmp.data), export_tmp.data_length);
579     free((void*)export_tmp.data);
580     return error;
581 }
582 
CheckHmacTestVector(string key,string message,keymaster_digest_t digest,string expected_mac)583 void Keymaster1Test::CheckHmacTestVector(string key, string message, keymaster_digest_t digest,
584                                          string expected_mac) {
585     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
586                                          .HmacKey(key.size() * 8)
587                                          .Authorization(TAG_MIN_MAC_LENGTH, expected_mac.size() * 8)
588                                          .Digest(digest),
589                                      KM_KEY_FORMAT_RAW, key));
590     string signature;
591     MacMessage(message, &signature, expected_mac.size() * 8);
592     EXPECT_EQ(expected_mac, signature) << "Test vector didn't match for digest " << (int)digest;
593 }
594 
CheckAesCtrTestVector(const string & key,const string & nonce,const string & message,const string & expected_ciphertext)595 void Keymaster1Test::CheckAesCtrTestVector(const string& key, const string& nonce,
596                                            const string& message,
597                                            const string& expected_ciphertext) {
598     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
599                                          .AesEncryptionKey(key.size() * 8)
600                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
601                                          .Authorization(TAG_CALLER_NONCE)
602                                          .Padding(KM_PAD_NONE),
603                                      KM_KEY_FORMAT_RAW, key));
604 
605     AuthorizationSet begin_params(client_params()), update_params, output_params;
606     begin_params.push_back(TAG_NONCE, nonce.data(), nonce.size());
607     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
608     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
609     string ciphertext =
610         EncryptMessageWithParams(message, begin_params, update_params, &output_params);
611     EXPECT_EQ(expected_ciphertext, ciphertext);
612 }
613 
hw_enforced()614 AuthorizationSet Keymaster1Test::hw_enforced() {
615     EXPECT_TRUE(characteristics_ != NULL);
616     return AuthorizationSet(characteristics_->hw_enforced);
617 }
618 
sw_enforced()619 AuthorizationSet Keymaster1Test::sw_enforced() {
620     EXPECT_TRUE(characteristics_ != NULL);
621     return AuthorizationSet(characteristics_->sw_enforced);
622 }
623 
FreeCharacteristics()624 void Keymaster1Test::FreeCharacteristics() {
625     keymaster_free_characteristics(characteristics_);
626     free(characteristics_);
627     characteristics_ = NULL;
628 }
629 
FreeKeyBlob()630 void Keymaster1Test::FreeKeyBlob() {
631     free(const_cast<uint8_t*>(blob_.key_material));
632     blob_.key_material = NULL;
633 }
634 
corrupt_key_blob()635 void Keymaster1Test::corrupt_key_blob() {
636     assert(blob_.key_material);
637     uint8_t* tmp = const_cast<uint8_t*>(blob_.key_material);
638     ++tmp[blob_.key_material_size / 2];
639 }
640 
641 class Sha256OnlyWrapper {
642   public:
Sha256OnlyWrapper(const keymaster1_device_t * wrapped_device)643     Sha256OnlyWrapper(const keymaster1_device_t* wrapped_device) : wrapped_device_(wrapped_device) {
644 
645         new_module = *wrapped_device_->common.module;
646         new_module_name = std::string("SHA 256-only ") + wrapped_device_->common.module->name;
647         new_module.name = new_module_name.c_str();
648 
649         memset(&device_, 0, sizeof(device_));
650         device_.common.module = &new_module;
651 
652         device_.common.close = close_device;
653         device_.get_supported_algorithms = get_supported_algorithms;
654         device_.get_supported_block_modes = get_supported_block_modes;
655         device_.get_supported_padding_modes = get_supported_padding_modes;
656         device_.get_supported_digests = get_supported_digests;
657         device_.get_supported_import_formats = get_supported_import_formats;
658         device_.get_supported_export_formats = get_supported_export_formats;
659         device_.add_rng_entropy = add_rng_entropy;
660         device_.generate_key = generate_key;
661         device_.get_key_characteristics = get_key_characteristics;
662         device_.import_key = import_key;
663         device_.export_key = export_key;
664         device_.begin = begin;
665         device_.update = update;
666         device_.finish = finish;
667         device_.abort = abort;
668     }
669 
keymaster_device()670     keymaster1_device_t* keymaster_device() { return &device_; }
671 
is_supported(keymaster_digest_t digest)672     static bool is_supported(keymaster_digest_t digest) {
673         return digest == KM_DIGEST_NONE || digest == KM_DIGEST_SHA_2_256;
674     }
675 
all_digests_supported(const keymaster_key_param_set_t * params)676     static bool all_digests_supported(const keymaster_key_param_set_t* params) {
677         for (size_t i = 0; i < params->length; ++i)
678             if (params->params[i].tag == TAG_DIGEST)
679                 if (!is_supported(static_cast<keymaster_digest_t>(params->params[i].enumerated)))
680                     return false;
681         return true;
682     }
683 
684     static const keymaster_key_param_t*
get_algorithm_param(const keymaster_key_param_set_t * params)685     get_algorithm_param(const keymaster_key_param_set_t* params) {
686         keymaster_key_param_t* end = params->params + params->length;
687         auto alg_ptr = std::find_if(params->params, end, [](keymaster_key_param_t& p) {
688             return p.tag == KM_TAG_ALGORITHM;
689         });
690         if (alg_ptr == end)
691             return nullptr;
692         return alg_ptr;
693     }
694 
close_device(hw_device_t * dev)695     static int close_device(hw_device_t* dev) {
696         Sha256OnlyWrapper* wrapper = reinterpret_cast<Sha256OnlyWrapper*>(dev);
697         const keymaster1_device_t* wrapped_device = wrapper->wrapped_device_;
698         delete wrapper;
699         return wrapped_device->common.close(const_cast<hw_device_t*>(&wrapped_device->common));
700     }
701 
unwrap(const keymaster1_device_t * dev)702     static const keymaster1_device_t* unwrap(const keymaster1_device_t* dev) {
703         return reinterpret_cast<const Sha256OnlyWrapper*>(dev)->wrapped_device_;
704     }
705 
get_supported_algorithms(const struct keymaster1_device * dev,keymaster_algorithm_t ** algorithms,size_t * algorithms_length)706     static keymaster_error_t get_supported_algorithms(const struct keymaster1_device* dev,
707                                                       keymaster_algorithm_t** algorithms,
708                                                       size_t* algorithms_length) {
709         return unwrap(dev)->get_supported_algorithms(unwrap(dev), algorithms, algorithms_length);
710     }
get_supported_block_modes(const struct keymaster1_device * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_block_mode_t ** modes,size_t * modes_length)711     static keymaster_error_t get_supported_block_modes(const struct keymaster1_device* dev,
712                                                        keymaster_algorithm_t algorithm,
713                                                        keymaster_purpose_t purpose,
714                                                        keymaster_block_mode_t** modes,
715                                                        size_t* modes_length) {
716         return unwrap(dev)
717             ->get_supported_block_modes(unwrap(dev), algorithm, purpose, modes, modes_length);
718     }
get_supported_padding_modes(const struct keymaster1_device * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_padding_t ** modes,size_t * modes_length)719     static keymaster_error_t get_supported_padding_modes(const struct keymaster1_device* dev,
720                                                          keymaster_algorithm_t algorithm,
721                                                          keymaster_purpose_t purpose,
722                                                          keymaster_padding_t** modes,
723                                                          size_t* modes_length) {
724         return unwrap(dev)
725             ->get_supported_padding_modes(unwrap(dev), algorithm, purpose, modes, modes_length);
726     }
727 
get_supported_digests(const keymaster1_device_t * dev,keymaster_algorithm_t algorithm,keymaster_purpose_t purpose,keymaster_digest_t ** digests,size_t * digests_length)728     static keymaster_error_t get_supported_digests(const keymaster1_device_t* dev,
729                                                    keymaster_algorithm_t algorithm,
730                                                    keymaster_purpose_t purpose,
731                                                    keymaster_digest_t** digests,
732                                                    size_t* digests_length) {
733         keymaster_error_t error = unwrap(dev)->get_supported_digests(
734             unwrap(dev), algorithm, purpose, digests, digests_length);
735         if (error != KM_ERROR_OK)
736             return error;
737 
738         std::vector<keymaster_digest_t> filtered_digests;
739         std::copy_if(*digests, *digests + *digests_length, std::back_inserter(filtered_digests),
740                      [](keymaster_digest_t digest) { return is_supported(digest); });
741 
742         free(*digests);
743         *digests_length = filtered_digests.size();
744         *digests = reinterpret_cast<keymaster_digest_t*>(
745             malloc(*digests_length * sizeof(keymaster_digest_t)));
746         std::copy(filtered_digests.begin(), filtered_digests.end(), *digests);
747 
748         return KM_ERROR_OK;
749     }
750 
get_supported_import_formats(const struct keymaster1_device * dev,keymaster_algorithm_t algorithm,keymaster_key_format_t ** formats,size_t * formats_length)751     static keymaster_error_t get_supported_import_formats(const struct keymaster1_device* dev,
752                                                           keymaster_algorithm_t algorithm,
753                                                           keymaster_key_format_t** formats,
754                                                           size_t* formats_length) {
755         return unwrap(dev)
756             ->get_supported_import_formats(unwrap(dev), algorithm, formats, formats_length);
757     }
get_supported_export_formats(const struct keymaster1_device * dev,keymaster_algorithm_t algorithm,keymaster_key_format_t ** formats,size_t * formats_length)758     static keymaster_error_t get_supported_export_formats(const struct keymaster1_device* dev,
759                                                           keymaster_algorithm_t algorithm,
760                                                           keymaster_key_format_t** formats,
761                                                           size_t* formats_length) {
762         return unwrap(dev)
763             ->get_supported_export_formats(unwrap(dev), algorithm, formats, formats_length);
764     }
add_rng_entropy(const struct keymaster1_device * dev,const uint8_t * data,size_t data_length)765     static keymaster_error_t add_rng_entropy(const struct keymaster1_device* dev,
766                                              const uint8_t* data, size_t data_length) {
767         return unwrap(dev)->add_rng_entropy(unwrap(dev), data, data_length);
768     }
769 
generate_key(const keymaster1_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t ** characteristics)770     static keymaster_error_t generate_key(const keymaster1_device_t* dev,
771                                           const keymaster_key_param_set_t* params,
772                                           keymaster_key_blob_t* key_blob,
773                                           keymaster_key_characteristics_t** characteristics) {
774         auto alg_ptr = get_algorithm_param(params);
775         if (!alg_ptr)
776             return KM_ERROR_UNSUPPORTED_ALGORITHM;
777         if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
778             return KM_ERROR_UNSUPPORTED_DIGEST;
779 
780         return unwrap(dev)->generate_key(unwrap(dev), params, key_blob, characteristics);
781     }
782 
783     static keymaster_error_t
get_key_characteristics(const struct keymaster1_device * dev,const keymaster_key_blob_t * key_blob,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_key_characteristics_t ** characteristics)784     get_key_characteristics(const struct keymaster1_device* dev,
785                             const keymaster_key_blob_t* key_blob, const keymaster_blob_t* client_id,
786                             const keymaster_blob_t* app_data,
787                             keymaster_key_characteristics_t** characteristics) {
788         return unwrap(dev)
789             ->get_key_characteristics(unwrap(dev), key_blob, client_id, app_data, characteristics);
790     }
791 
792     static keymaster_error_t
import_key(const keymaster1_device_t * dev,const keymaster_key_param_set_t * params,keymaster_key_format_t key_format,const keymaster_blob_t * key_data,keymaster_key_blob_t * key_blob,keymaster_key_characteristics_t ** characteristics)793     import_key(const keymaster1_device_t* dev, const keymaster_key_param_set_t* params,
794                keymaster_key_format_t key_format, const keymaster_blob_t* key_data,
795                keymaster_key_blob_t* key_blob, keymaster_key_characteristics_t** characteristics) {
796         auto alg_ptr = get_algorithm_param(params);
797         if (!alg_ptr)
798             return KM_ERROR_UNSUPPORTED_ALGORITHM;
799         if (alg_ptr->enumerated == KM_ALGORITHM_HMAC && !all_digests_supported(params))
800             return KM_ERROR_UNSUPPORTED_DIGEST;
801 
802         return unwrap(dev)
803             ->import_key(unwrap(dev), params, key_format, key_data, key_blob, characteristics);
804     }
805 
export_key(const struct keymaster1_device * dev,keymaster_key_format_t export_format,const keymaster_key_blob_t * key_to_export,const keymaster_blob_t * client_id,const keymaster_blob_t * app_data,keymaster_blob_t * export_data)806     static keymaster_error_t export_key(const struct keymaster1_device* dev,  //
807                                         keymaster_key_format_t export_format,
808                                         const keymaster_key_blob_t* key_to_export,
809                                         const keymaster_blob_t* client_id,
810                                         const keymaster_blob_t* app_data,
811                                         keymaster_blob_t* export_data) {
812         return unwrap(dev)->export_key(unwrap(dev), export_format, key_to_export, client_id,
813                                        app_data, export_data);
814     }
815 
begin(const keymaster1_device_t * dev,keymaster_purpose_t purpose,const keymaster_key_blob_t * key,const keymaster_key_param_set_t * in_params,keymaster_key_param_set_t * out_params,keymaster_operation_handle_t * operation_handle)816     static keymaster_error_t begin(const keymaster1_device_t* dev,  //
817                                    keymaster_purpose_t purpose, const keymaster_key_blob_t* key,
818                                    const keymaster_key_param_set_t* in_params,
819                                    keymaster_key_param_set_t* out_params,
820                                    keymaster_operation_handle_t* operation_handle) {
821         if (!all_digests_supported(in_params))
822             return KM_ERROR_UNSUPPORTED_DIGEST;
823         return unwrap(dev)
824             ->begin(unwrap(dev), purpose, key, in_params, out_params, operation_handle);
825     }
826 
update(const keymaster1_device_t * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * in_params,const keymaster_blob_t * input,size_t * input_consumed,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)827     static keymaster_error_t update(const keymaster1_device_t* dev,
828                                     keymaster_operation_handle_t operation_handle,
829                                     const keymaster_key_param_set_t* in_params,
830                                     const keymaster_blob_t* input, size_t* input_consumed,
831                                     keymaster_key_param_set_t* out_params,
832                                     keymaster_blob_t* output) {
833         return unwrap(dev)->update(unwrap(dev), operation_handle, in_params, input, input_consumed,
834                                    out_params, output);
835     }
836 
finish(const struct keymaster1_device * dev,keymaster_operation_handle_t operation_handle,const keymaster_key_param_set_t * in_params,const keymaster_blob_t * signature,keymaster_key_param_set_t * out_params,keymaster_blob_t * output)837     static keymaster_error_t finish(const struct keymaster1_device* dev,  //
838                                     keymaster_operation_handle_t operation_handle,
839                                     const keymaster_key_param_set_t* in_params,
840                                     const keymaster_blob_t* signature,
841                                     keymaster_key_param_set_t* out_params,
842                                     keymaster_blob_t* output) {
843         return unwrap(dev)
844             ->finish(unwrap(dev), operation_handle, in_params, signature, out_params, output);
845     }
846 
abort(const struct keymaster1_device * dev,keymaster_operation_handle_t operation_handle)847     static keymaster_error_t abort(const struct keymaster1_device* dev,
848                                    keymaster_operation_handle_t operation_handle) {
849         return unwrap(dev)->abort(unwrap(dev), operation_handle);
850     }
851 
852   private:
853     keymaster1_device_t device_;
854     const keymaster1_device_t* wrapped_device_;
855     hw_module_t new_module;
856     string new_module_name;
857 };
858 
make_device_sha256_only(keymaster1_device_t * device)859 keymaster1_device_t* make_device_sha256_only(keymaster1_device_t* device) {
860     return (new Sha256OnlyWrapper(device))->keymaster_device();
861 }
862 
863 }  // namespace test
864 }  // namespace keymaster
865