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