• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 <fstream>
18 #include <memory>
19 #include <string>
20 #include <vector>
21 
22 #include <openssl/evp.h>
23 #include <openssl/x509.h>
24 
25 #include <hardware/keymaster0.h>
26 
27 #include <keymaster/android_keymaster.h>
28 #include <keymaster/attestation_record.h>
29 #include <keymaster/contexts/pure_soft_keymaster_context.h>
30 #include <keymaster/contexts/soft_keymaster_context.h>
31 #include <keymaster/key_factory.h>
32 #include <keymaster/km_openssl/hmac_key.h>
33 #include <keymaster/km_openssl/openssl_utils.h>
34 #include <keymaster/km_openssl/soft_keymaster_enforcement.h>
35 #include <keymaster/legacy_support/keymaster0_engine.h>
36 #include <keymaster/soft_keymaster_device.h>
37 
38 #include "android_keymaster_test_utils.h"
39 
40 using std::ifstream;
41 using std::istreambuf_iterator;
42 using std::ofstream;
43 using std::string;
44 using std::unique_ptr;
45 using std::vector;
46 
47 extern "C" {
48 int __android_log_print(int prio, const char* tag, const char* fmt);
__android_log_print(int prio,const char * tag,const char * fmt)49 int __android_log_print(int prio, const char* tag, const char* fmt) {
50     (void)prio, (void)tag, (void)fmt;
51     return 0;
52 }
53 }  // extern "C"
54 
55 namespace {
56 
57 // For some reason std::make_unique isn't available.  Define make_unique.
make_unique(Args &&...args)58 template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
59     return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
60 }
61 
62 }  // namespace
63 
64 namespace keymaster {
65 namespace test {
66 
67 const uint32_t kOsVersion = 060000;
68 const uint32_t kOsPatchLevel = 201603;
69 
70 StdoutLogger logger;
71 
make_vector(const T * array,size_t len)72 template <typename T> vector<T> make_vector(const T* array, size_t len) {
73     return vector<T>(array, array + len);
74 }
75 
76 /**
77  * KeymasterEnforcement class for use in testing.  It's permissive in the sense that it doesn't
78  * check cryptoperiods, but restrictive in the sense that the clock never advances (so rate-limited
79  * keys will only work once).
80  */
81 class TestKeymasterEnforcement : public SoftKeymasterEnforcement {
82   public:
TestKeymasterEnforcement()83     TestKeymasterEnforcement() : SoftKeymasterEnforcement(3, 3) {}
84 
activation_date_valid(uint64_t) const85     virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
expiration_date_passed(uint64_t) const86     virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
auth_token_timed_out(const hw_auth_token_t &,uint32_t) const87     virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
88                                       uint32_t /* timeout */) const {
89         return false;
90     }
get_current_time() const91     virtual uint32_t get_current_time() const { return 0; }
ValidateTokenSignature(const hw_auth_token_t &) const92     virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
93 };
94 
95 /**
96  * Variant of SoftKeymasterContext that provides a TestKeymasterEnforcement.
97  */
98 class TestKeymasterContext : public SoftKeymasterContext {
99   public:
TestKeymasterContext()100     TestKeymasterContext() {}
TestKeymasterContext(const string & root_of_trust)101     explicit TestKeymasterContext(const string& root_of_trust)
102         : SoftKeymasterContext(root_of_trust) {}
103 
enforcement_policy()104     KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
105 
106   private:
107     TestKeymasterEnforcement test_policy_;
108 };
109 
110 /**
111  * Test instance creator that builds a pure software keymaster2 implementation.
112  */
113 class SoftKeymasterTestInstanceCreator : public Keymaster2TestInstanceCreator {
114   public:
CreateDevice() const115     keymaster2_device_t* CreateDevice() const override {
116         std::cerr << "Creating software-only device" << std::endl;
117         context_ = new TestKeymasterContext;
118         SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
119         AuthorizationSet version_info(AuthorizationSetBuilder()
120                                           .Authorization(TAG_OS_VERSION, kOsVersion)
121                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
122         device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
123         return device->keymaster2_device();
124     }
125 
algorithm_in_km0_hardware(keymaster_algorithm_t) const126     bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
keymaster0_calls() const127     int keymaster0_calls() const override { return 0; }
is_keymaster1_hw() const128     bool is_keymaster1_hw() const override { return false; }
keymaster_context() const129     KeymasterContext* keymaster_context() const override { return context_; }
name() const130     string name() const override { return "Soft Keymaster2"; }
131 
132   private:
133     mutable TestKeymasterContext* context_;
134 };
135 
136 /**
137  * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
138  * instance, with minimal digest support.
139  */
140 class Sha256OnlyKeymaster1TestInstanceCreator : public Keymaster2TestInstanceCreator {
CreateDevice() const141     keymaster2_device_t* CreateDevice() const override {
142         std::cerr << "Creating keymaster1-backed device that supports only SHA256";
143 
144         // fake_device doesn't leak because device (below) takes ownership of it.
145         keymaster1_device_t* fake_device = make_device_sha256_only(
146             (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device());
147 
148         // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
149         context_ = new TestKeymasterContext;
150         SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
151         device->SetHardwareDevice(fake_device);
152 
153         AuthorizationSet version_info(AuthorizationSetBuilder()
154                                           .Authorization(TAG_OS_VERSION, kOsVersion)
155                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
156         device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
157         return device->keymaster2_device();
158     }
159 
algorithm_in_km0_hardware(keymaster_algorithm_t) const160     bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
keymaster0_calls() const161     int keymaster0_calls() const override { return 0; }
minimal_digest_set() const162     int minimal_digest_set() const override { return true; }
is_keymaster1_hw() const163     bool is_keymaster1_hw() const override { return true; }
keymaster_context() const164     KeymasterContext* keymaster_context() const override { return context_; }
name() const165     string name() const override { return "Wrapped fake keymaster1 w/minimal digests"; }
166 
167   private:
168     mutable TestKeymasterContext* context_;
169 };
170 
171 /**
172  * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
173  * instance, with full digest support
174  */
175 class Keymaster1TestInstanceCreator : public Keymaster2TestInstanceCreator {
CreateDevice() const176     keymaster2_device_t* CreateDevice() const override {
177         std::cerr << "Creating keymaster1-backed device";
178 
179         // fake_device doesn't leak because device (below) takes ownership of it.
180         keymaster1_device_t* fake_device =
181             (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device();
182 
183         // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
184         context_ = new TestKeymasterContext;
185         SoftKeymasterDevice* device = new SoftKeymasterDevice(context_);
186         device->SetHardwareDevice(fake_device);
187 
188         AuthorizationSet version_info(AuthorizationSetBuilder()
189                                           .Authorization(TAG_OS_VERSION, kOsVersion)
190                                           .Authorization(TAG_OS_PATCHLEVEL, kOsPatchLevel));
191         device->keymaster2_device()->configure(device->keymaster2_device(), &version_info);
192         return device->keymaster2_device();
193     }
194 
algorithm_in_km0_hardware(keymaster_algorithm_t) const195     bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
keymaster0_calls() const196     int keymaster0_calls() const override { return 0; }
minimal_digest_set() const197     int minimal_digest_set() const override { return false; }
is_keymaster1_hw() const198     bool is_keymaster1_hw() const override { return true; }
keymaster_context() const199     KeymasterContext* keymaster_context() const override { return context_; }
name() const200     string name() const override { return "Wrapped fake keymaster1 w/full digests"; }
201 
202   private:
203     mutable TestKeymasterContext* context_;
204 };
205 
206 static auto test_params = testing::Values(
207     InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
208     InstanceCreatorPtr(new Keymaster1TestInstanceCreator),
209     InstanceCreatorPtr(new Sha256OnlyKeymaster1TestInstanceCreator));
210 
211 class NewKeyGeneration : public Keymaster2Test {
212   protected:
CheckBaseParams()213     void CheckBaseParams() {
214         AuthorizationSet auths = sw_enforced();
215         EXPECT_GT(auths.SerializedSize(), 12U);
216 
217         EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
218         EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
219         EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
220         EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
221         EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
222 
223         // Verify that App ID, App data and ROT are NOT included.
224         EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
225         EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
226         EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
227 
228         // Just for giggles, check that some unexpected tags/values are NOT present.
229         EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
230         EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
231         EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
232 
233         // Now check that unspecified, defaulted tags are correct.
234         EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
235         if (GetParam()->is_keymaster1_hw()) {
236             // If the underlying (faked) HW is KM1, it will not have version info.
237             EXPECT_FALSE(auths.Contains(TAG_OS_VERSION));
238             EXPECT_FALSE(auths.Contains(TAG_OS_PATCHLEVEL));
239         } else {
240             // In all othe cases; SoftKeymasterDevice keys, or keymaster0 keys wrapped by
241             // SoftKeymasterDevice, version information will be present and up to date.
242             EXPECT_TRUE(contains(auths, TAG_OS_VERSION, kOsVersion));
243             EXPECT_TRUE(contains(auths, TAG_OS_PATCHLEVEL, kOsPatchLevel));
244         }
245     }
246 };
247 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
248 
TEST_P(NewKeyGeneration,Rsa)249 TEST_P(NewKeyGeneration, Rsa) {
250     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
251                                            .RsaSigningKey(256, 3)
252                                            .Digest(KM_DIGEST_NONE)
253                                            .Padding(KM_PAD_NONE)));
254     CheckBaseParams();
255 
256     // Check specified tags are all present, and in the right set.
257     AuthorizationSet crypto_params;
258     AuthorizationSet non_crypto_params;
259     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
260         EXPECT_NE(0U, hw_enforced().size());
261         EXPECT_NE(0U, sw_enforced().size());
262         crypto_params.push_back(hw_enforced());
263         non_crypto_params.push_back(sw_enforced());
264     } else {
265         EXPECT_EQ(0U, hw_enforced().size());
266         EXPECT_NE(0U, sw_enforced().size());
267         crypto_params.push_back(sw_enforced());
268     }
269 
270     EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
271     EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
272     EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
273     EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
274     EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
275     EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
276 
277     EXPECT_EQ(KM_ERROR_OK, DeleteKey());
278 
279     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
280         EXPECT_EQ(2, GetParam()->keymaster0_calls());
281 }
282 
TEST_P(NewKeyGeneration,RsaDefaultSize)283 TEST_P(NewKeyGeneration, RsaDefaultSize) {
284     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
285               GenerateKey(AuthorizationSetBuilder()
286                               .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
287                               .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
288                               .SigningKey()));
289 
290     EXPECT_EQ(0, GetParam()->keymaster0_calls());
291 }
292 
TEST_P(NewKeyGeneration,Ecdsa)293 TEST_P(NewKeyGeneration, Ecdsa) {
294     ASSERT_EQ(KM_ERROR_OK,
295               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
296     CheckBaseParams();
297 
298     // Check specified tags are all present, and in the right set.
299     AuthorizationSet crypto_params;
300     AuthorizationSet non_crypto_params;
301     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
302         EXPECT_NE(0U, hw_enforced().size());
303         EXPECT_NE(0U, sw_enforced().size());
304         crypto_params.push_back(hw_enforced());
305         non_crypto_params.push_back(sw_enforced());
306     } else {
307         EXPECT_EQ(0U, hw_enforced().size());
308         EXPECT_NE(0U, sw_enforced().size());
309         crypto_params.push_back(sw_enforced());
310     }
311 
312     EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
313     EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
314     EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
315     EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
316 
317     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
318         EXPECT_EQ(1, GetParam()->keymaster0_calls());
319 }
320 
TEST_P(NewKeyGeneration,EcdsaDefaultSize)321 TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
322     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
323               GenerateKey(AuthorizationSetBuilder()
324                               .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
325                               .SigningKey()
326                               .Digest(KM_DIGEST_NONE)));
327 
328     EXPECT_EQ(0, GetParam()->keymaster0_calls());
329 }
330 
TEST_P(NewKeyGeneration,EcdsaInvalidSize)331 TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
332     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
333               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
334     EXPECT_EQ(0, GetParam()->keymaster0_calls());
335 }
336 
TEST_P(NewKeyGeneration,EcdsaMismatchKeySize)337 TEST_P(NewKeyGeneration, EcdsaMismatchKeySize) {
338     ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT,
339               GenerateKey(AuthorizationSetBuilder()
340                               .EcdsaSigningKey(224)
341                               .Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256)
342                               .Digest(KM_DIGEST_NONE)));
343 }
344 
TEST_P(NewKeyGeneration,EcdsaAllValidSizes)345 TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
346     size_t valid_sizes[] = {224, 256, 384, 521};
347     for (size_t size : valid_sizes) {
348         EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
349                                    KM_DIGEST_NONE)))
350             << "Failed to generate size: " << size;
351     }
352 
353     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
354         EXPECT_EQ(4, GetParam()->keymaster0_calls());
355 }
356 
TEST_P(NewKeyGeneration,HmacSha256)357 TEST_P(NewKeyGeneration, HmacSha256) {
358     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
359                                            .HmacKey(128)
360                                            .Digest(KM_DIGEST_SHA_2_256)
361                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
362 
363     EXPECT_EQ(0, GetParam()->keymaster0_calls());
364 }
365 
TEST_P(NewKeyGeneration,CheckKeySizes)366 TEST_P(NewKeyGeneration, CheckKeySizes) {
367     for (size_t key_size = 0; key_size <= kMaxHmacKeyLengthBits + 10; ++key_size) {
368         if (key_size < kMinHmacKeyLengthBits || key_size > kMaxHmacKeyLengthBits ||
369             key_size % 8 != 0) {
370             EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
371                       GenerateKey(AuthorizationSetBuilder()
372                                       .HmacKey(key_size)
373                                       .Digest(KM_DIGEST_SHA_2_256)
374                                       .Authorization(TAG_MIN_MAC_LENGTH, 256)))
375                 << "HMAC key size " << key_size << " invalid.";
376         } else {
377             EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
378                                                    .HmacKey(key_size)
379                                                    .Digest(KM_DIGEST_SHA_2_256)
380                                                    .Authorization(TAG_MIN_MAC_LENGTH, 256)));
381         }
382     }
383     EXPECT_EQ(0, GetParam()->keymaster0_calls());
384 }
385 
TEST_P(NewKeyGeneration,HmacMultipleDigests)386 TEST_P(NewKeyGeneration, HmacMultipleDigests) {
387     ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
388               GenerateKey(AuthorizationSetBuilder()
389                               .HmacKey(128)
390                               .Digest(KM_DIGEST_SHA1)
391                               .Digest(KM_DIGEST_SHA_2_256)
392                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
393 
394     EXPECT_EQ(0, GetParam()->keymaster0_calls());
395 }
396 
TEST_P(NewKeyGeneration,HmacDigestNone)397 TEST_P(NewKeyGeneration, HmacDigestNone) {
398     ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
399               GenerateKey(AuthorizationSetBuilder()
400                               .HmacKey(128)
401                               .Digest(KM_DIGEST_NONE)
402                               .Authorization(TAG_MIN_MAC_LENGTH, 128)));
403 
404     EXPECT_EQ(0, GetParam()->keymaster0_calls());
405 }
406 
TEST_P(NewKeyGeneration,HmacSha256TooShortMacLength)407 TEST_P(NewKeyGeneration, HmacSha256TooShortMacLength) {
408     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
409               GenerateKey(AuthorizationSetBuilder()
410                               .HmacKey(128)
411                               .Digest(KM_DIGEST_SHA_2_256)
412                               .Authorization(TAG_MIN_MAC_LENGTH, 48)));
413 
414     EXPECT_EQ(0, GetParam()->keymaster0_calls());
415 }
416 
TEST_P(NewKeyGeneration,HmacSha256NonIntegralOctetMacLength)417 TEST_P(NewKeyGeneration, HmacSha256NonIntegralOctetMacLength) {
418     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
419               GenerateKey(AuthorizationSetBuilder()
420                               .HmacKey(128)
421                               .Digest(KM_DIGEST_SHA_2_256)
422                               .Authorization(TAG_MIN_MAC_LENGTH, 130)));
423 
424     EXPECT_EQ(0, GetParam()->keymaster0_calls());
425 }
426 
TEST_P(NewKeyGeneration,HmacSha256TooLongMacLength)427 TEST_P(NewKeyGeneration, HmacSha256TooLongMacLength) {
428     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
429               GenerateKey(AuthorizationSetBuilder()
430                               .HmacKey(128)
431                               .Digest(KM_DIGEST_SHA_2_256)
432                               .Authorization(TAG_MIN_MAC_LENGTH, 384)));
433 
434     EXPECT_EQ(0, GetParam()->keymaster0_calls());
435 }
436 
437 typedef Keymaster2Test GetKeyCharacteristics;
438 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
439 
TEST_P(GetKeyCharacteristics,SimpleRsa)440 TEST_P(GetKeyCharacteristics, SimpleRsa) {
441     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
442                                            .RsaSigningKey(256, 3)
443                                            .Digest(KM_DIGEST_NONE)
444                                            .Padding(KM_PAD_NONE)));
445     AuthorizationSet original(sw_enforced());
446 
447     ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
448     EXPECT_EQ(original, sw_enforced());
449 
450     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
451         EXPECT_EQ(1, GetParam()->keymaster0_calls());
452 }
453 
454 typedef Keymaster2Test SigningOperationsTest;
455 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
456 
TEST_P(SigningOperationsTest,RsaSuccess)457 TEST_P(SigningOperationsTest, RsaSuccess) {
458     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
459                                            .RsaSigningKey(256, 3)
460                                            .Digest(KM_DIGEST_NONE)
461                                            .Padding(KM_PAD_NONE)));
462     string message = "12345678901234567890123456789012";
463     string signature;
464     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
465 
466     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
467         EXPECT_EQ(3, GetParam()->keymaster0_calls());
468 }
469 
TEST_P(SigningOperationsTest,RsaPssSha256Success)470 TEST_P(SigningOperationsTest, RsaPssSha256Success) {
471     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
472                                            .RsaSigningKey(768, 3)
473                                            .Digest(KM_DIGEST_SHA_2_256)
474                                            .Padding(KM_PAD_RSA_PSS)));
475     // Use large message, which won't work without digesting.
476     string message(1024, 'a');
477     string signature;
478     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
479 
480     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
481         EXPECT_EQ(3, GetParam()->keymaster0_calls());
482 }
483 
TEST_P(SigningOperationsTest,RsaPaddingNoneDoesNotAllowOther)484 TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
485     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
486                                            .RsaSigningKey(512, 3)
487                                            .Digest(KM_DIGEST_NONE)
488                                            .Padding(KM_PAD_NONE)));
489     string message = "12345678901234567890123456789012";
490     string signature;
491 
492     AuthorizationSet begin_params(client_params());
493     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
494     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
495     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
496 
497     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
498         EXPECT_EQ(2, GetParam()->keymaster0_calls());
499 }
500 
TEST_P(SigningOperationsTest,RsaPkcs1Sha256Success)501 TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
502     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
503                                            .RsaSigningKey(512, 3)
504                                            .Digest(KM_DIGEST_SHA_2_256)
505                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
506     string message(1024, 'a');
507     string signature;
508     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
509 
510     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
511         EXPECT_EQ(3, GetParam()->keymaster0_calls());
512 }
513 
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestSuccess)514 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
515     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
516                                            .RsaSigningKey(512, 3)
517                                            .Digest(KM_DIGEST_NONE)
518                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
519     string message(53, 'a');
520     string signature;
521     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
522 
523     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
524         EXPECT_EQ(3, GetParam()->keymaster0_calls());
525 }
526 
TEST_P(SigningOperationsTest,RsaPkcs1NoDigestTooLarge)527 TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
528     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
529                                            .RsaSigningKey(512, 3)
530                                            .Digest(KM_DIGEST_NONE)
531                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
532     string message(54, 'a');
533 
534     AuthorizationSet begin_params(client_params());
535     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
536     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
537     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
538     string result;
539     string signature;
540     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &signature));
541 
542     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
543         EXPECT_EQ(2, GetParam()->keymaster0_calls());
544 }
545 
TEST_P(SigningOperationsTest,RsaPssSha256TooSmallKey)546 TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
547     // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
548     // verify that nine bytes larger than hash won't work.
549     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
550                                            .RsaSigningKey(256 + 9 * 8, 3)
551                                            .Digest(KM_DIGEST_SHA_2_256)
552                                            .Padding(KM_PAD_RSA_PSS)));
553     string message(1024, 'a');
554     string signature;
555 
556     AuthorizationSet begin_params(client_params());
557     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
558     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
559     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
560 }
561 
TEST_P(SigningOperationsTest,RsaNoPaddingHugeData)562 TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
563     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
564                                            .RsaSigningKey(256, 3)
565                                            .Digest(KM_DIGEST_NONE)
566                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
567     string message(64 * 1024, 'a');
568     string signature;
569     AuthorizationSet begin_params(client_params());
570     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
571     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
572     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
573     string result;
574     size_t input_consumed;
575     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
576 
577     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
578         EXPECT_EQ(2, GetParam()->keymaster0_calls());
579 }
580 
TEST_P(SigningOperationsTest,RsaAbort)581 TEST_P(SigningOperationsTest, RsaAbort) {
582     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
583                                            .RsaSigningKey(256, 3)
584                                            .Digest(KM_DIGEST_NONE)
585                                            .Padding(KM_PAD_NONE)));
586     AuthorizationSet begin_params(client_params());
587     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
588     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
589     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
590     EXPECT_EQ(KM_ERROR_OK, AbortOperation());
591     // Another abort should fail
592     EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
593 
594     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
595         EXPECT_EQ(2, GetParam()->keymaster0_calls());
596 }
597 
TEST_P(SigningOperationsTest,RsaUnsupportedPadding)598 TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
599     GenerateKey(AuthorizationSetBuilder()
600                     .RsaSigningKey(256, 3)
601                     .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
602                     .Padding(KM_PAD_PKCS7));
603     AuthorizationSet begin_params(client_params());
604     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
605     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
606 
607     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
608         EXPECT_EQ(2, GetParam()->keymaster0_calls());
609 }
610 
TEST_P(SigningOperationsTest,RsaNoDigest)611 TEST_P(SigningOperationsTest, RsaNoDigest) {
612     // PSS requires a digest.
613     GenerateKey(AuthorizationSetBuilder()
614                     .RsaSigningKey(256, 3)
615                     .Digest(KM_DIGEST_NONE)
616                     .Padding(KM_PAD_RSA_PSS));
617     AuthorizationSet begin_params(client_params());
618     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
619     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
620     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
621 
622     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
623         EXPECT_EQ(2, GetParam()->keymaster0_calls());
624 }
625 
TEST_P(SigningOperationsTest,RsaNoPadding)626 TEST_P(SigningOperationsTest, RsaNoPadding) {
627     // Padding must be specified
628     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
629                                KM_DIGEST_NONE)));
630     AuthorizationSet begin_params(client_params());
631     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
632     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
633 
634     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
635         EXPECT_EQ(2, GetParam()->keymaster0_calls());
636 }
637 
TEST_P(SigningOperationsTest,RsaTooShortMessage)638 TEST_P(SigningOperationsTest, RsaTooShortMessage) {
639     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
640                                            .RsaSigningKey(256, 3)
641                                            .Digest(KM_DIGEST_NONE)
642                                            .Padding(KM_PAD_NONE)));
643     string message = "1234567890123456789012345678901";
644     string signature;
645     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
646 
647     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
648         EXPECT_EQ(3, GetParam()->keymaster0_calls());
649 }
650 
TEST_P(SigningOperationsTest,RsaSignWithEncryptionKey)651 TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
652     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
653                                            .RsaEncryptionKey(256, 3)
654                                            .Digest(KM_DIGEST_NONE)
655                                            .Padding(KM_PAD_NONE)));
656     AuthorizationSet begin_params(client_params());
657     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
658     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
659     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
660 
661     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
662         EXPECT_EQ(2, GetParam()->keymaster0_calls());
663 }
664 
TEST_P(SigningOperationsTest,RsaSignTooLargeMessage)665 TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
666     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
667                                            .RsaSigningKey(256, 3)
668                                            .Digest(KM_DIGEST_NONE)
669                                            .Padding(KM_PAD_NONE)));
670     string message(256 / 8, static_cast<char>(0xff));
671     string signature;
672     AuthorizationSet begin_params(client_params());
673     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
674     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
675     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
676     string result;
677     size_t input_consumed;
678     ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
679     ASSERT_EQ(message.size(), input_consumed);
680     string output;
681     ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&output));
682 
683     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
684         EXPECT_EQ(3, GetParam()->keymaster0_calls());
685 }
686 
TEST_P(SigningOperationsTest,EcdsaSuccess)687 TEST_P(SigningOperationsTest, EcdsaSuccess) {
688     ASSERT_EQ(KM_ERROR_OK,
689               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
690     string message(224 / 8, 'a');
691     string signature;
692     SignMessage(message, &signature, KM_DIGEST_NONE);
693 
694     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
695         EXPECT_EQ(3, GetParam()->keymaster0_calls());
696 }
697 
TEST_P(SigningOperationsTest,EcdsaSha256Success)698 TEST_P(SigningOperationsTest, EcdsaSha256Success) {
699     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
700                                KM_DIGEST_SHA_2_256)));
701     string message(1024, 'a');
702     string signature;
703     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
704 
705     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
706         EXPECT_EQ(3, GetParam()->keymaster0_calls());
707 }
708 
TEST_P(SigningOperationsTest,EcdsaSha384Success)709 TEST_P(SigningOperationsTest, EcdsaSha384Success) {
710     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
711                                KM_DIGEST_SHA_2_384)));
712     string message(1024, 'a');
713     string signature;
714     SignMessage(message, &signature, KM_DIGEST_SHA_2_384);
715 
716     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
717         EXPECT_EQ(3, GetParam()->keymaster0_calls());
718 }
719 
TEST_P(SigningOperationsTest,EcdsaNoPaddingHugeData)720 TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
721     ASSERT_EQ(KM_ERROR_OK,
722               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
723     string message(64 * 1024, 'a');
724     string signature;
725     AuthorizationSet begin_params(client_params());
726     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
727     ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
728     string result;
729     size_t input_consumed;
730     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
731 
732     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
733         EXPECT_EQ(2, GetParam()->keymaster0_calls());
734 }
735 
TEST_P(SigningOperationsTest,EcdsaAllSizesAndHashes)736 TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
737     vector<int> key_sizes = {224, 256, 384, 521};
738     vector<keymaster_digest_t> digests = {
739         KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
740         KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
741     };
742 
743     for (int key_size : key_sizes) {
744         for (keymaster_digest_t digest : digests) {
745             ASSERT_EQ(
746                 KM_ERROR_OK,
747                 GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(digest)));
748 
749             string message(1024, 'a');
750             string signature;
751             if (digest == KM_DIGEST_NONE)
752                 message.resize(key_size / 8);
753             SignMessage(message, &signature, digest);
754         }
755     }
756 
757     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
758         EXPECT_EQ(digests.size() * key_sizes.size() * 3,
759                   static_cast<size_t>(GetParam()->keymaster0_calls()));
760 }
761 
TEST_P(SigningOperationsTest,AesEcbSign)762 TEST_P(SigningOperationsTest, AesEcbSign) {
763     ASSERT_EQ(KM_ERROR_OK,
764               GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
765                   TAG_BLOCK_MODE, KM_MODE_ECB)));
766     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
767     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
768 
769     EXPECT_EQ(0, GetParam()->keymaster0_calls());
770 }
771 
TEST_P(SigningOperationsTest,HmacSha1Success)772 TEST_P(SigningOperationsTest, HmacSha1Success) {
773     GenerateKey(AuthorizationSetBuilder()
774                     .HmacKey(128)
775                     .Digest(KM_DIGEST_SHA1)
776                     .Authorization(TAG_MIN_MAC_LENGTH, 160));
777     string message = "12345678901234567890123456789012";
778     string signature;
779     MacMessage(message, &signature, 160);
780     ASSERT_EQ(20U, signature.size());
781 
782     EXPECT_EQ(0, GetParam()->keymaster0_calls());
783 }
784 
TEST_P(SigningOperationsTest,HmacSha224Success)785 TEST_P(SigningOperationsTest, HmacSha224Success) {
786     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
787                                            .HmacKey(128)
788                                            .Digest(KM_DIGEST_SHA_2_224)
789                                            .Authorization(TAG_MIN_MAC_LENGTH, 160)));
790     string message = "12345678901234567890123456789012";
791     string signature;
792     MacMessage(message, &signature, 224);
793     ASSERT_EQ(28U, signature.size());
794 
795     EXPECT_EQ(0, GetParam()->keymaster0_calls());
796 }
797 
TEST_P(SigningOperationsTest,HmacSha256Success)798 TEST_P(SigningOperationsTest, HmacSha256Success) {
799     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
800                                            .HmacKey(128)
801                                            .Digest(KM_DIGEST_SHA_2_256)
802                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
803     string message = "12345678901234567890123456789012";
804     string signature;
805     MacMessage(message, &signature, 256);
806     ASSERT_EQ(32U, signature.size());
807 
808     EXPECT_EQ(0, GetParam()->keymaster0_calls());
809 }
810 
TEST_P(SigningOperationsTest,HmacSha384Success)811 TEST_P(SigningOperationsTest, HmacSha384Success) {
812     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
813                                            .HmacKey(128)
814                                            .Digest(KM_DIGEST_SHA_2_384)
815                                            .Authorization(TAG_MIN_MAC_LENGTH, 384)));
816 
817     string message = "12345678901234567890123456789012";
818     string signature;
819     MacMessage(message, &signature, 384);
820     ASSERT_EQ(48U, signature.size());
821 
822     EXPECT_EQ(0, GetParam()->keymaster0_calls());
823 }
824 
TEST_P(SigningOperationsTest,HmacSha512Success)825 TEST_P(SigningOperationsTest, HmacSha512Success) {
826     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
827                                            .HmacKey(128)
828                                            .Digest(KM_DIGEST_SHA_2_512)
829                                            .Authorization(TAG_MIN_MAC_LENGTH, 384)));
830     string message = "12345678901234567890123456789012";
831     string signature;
832     MacMessage(message, &signature, 512);
833     ASSERT_EQ(64U, signature.size());
834 
835     EXPECT_EQ(0, GetParam()->keymaster0_calls());
836 }
837 
TEST_P(SigningOperationsTest,HmacLengthInKey)838 TEST_P(SigningOperationsTest, HmacLengthInKey) {
839     // TODO(swillden): unified API should generate an error on key generation.
840     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
841                                            .HmacKey(128)
842                                            .Digest(KM_DIGEST_SHA_2_256)
843                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
844     string message = "12345678901234567890123456789012";
845     string signature;
846     MacMessage(message, &signature, 160);
847     ASSERT_EQ(20U, signature.size());
848 
849     EXPECT_EQ(0, GetParam()->keymaster0_calls());
850 }
851 
TEST_P(SigningOperationsTest,HmacRfc4231TestCase3)852 TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
853     string key(20, 0xaa);
854     string message(50, 0xdd);
855     uint8_t sha_224_expected[] = {
856         0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
857         0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
858     };
859     uint8_t sha_256_expected[] = {
860         0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
861         0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
862         0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
863     };
864     uint8_t sha_384_expected[] = {
865         0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
866         0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
867         0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
868         0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
869     };
870     uint8_t sha_512_expected[] = {
871         0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
872         0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
873         0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
874         0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
875         0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
876     };
877 
878     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
879     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
880     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
881     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
882 
883     EXPECT_EQ(0, GetParam()->keymaster0_calls());
884 }
885 
TEST_P(SigningOperationsTest,HmacRfc4231TestCase4)886 TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
887     uint8_t key_data[25] = {
888         0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
889         0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
890     };
891     string key = make_string(key_data);
892     string message(50, 0xcd);
893     uint8_t sha_224_expected[] = {
894         0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
895         0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
896     };
897     uint8_t sha_256_expected[] = {
898         0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
899         0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
900         0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
901     };
902     uint8_t sha_384_expected[] = {
903         0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
904         0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
905         0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
906         0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
907     };
908     uint8_t sha_512_expected[] = {
909         0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
910         0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
911         0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
912         0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
913         0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
914     };
915 
916     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
917     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
918     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
919     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
920 
921     EXPECT_EQ(0, GetParam()->keymaster0_calls());
922 }
923 
TEST_P(SigningOperationsTest,HmacRfc4231TestCase5)924 TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
925     string key(20, 0x0c);
926     string message = "Test With Truncation";
927 
928     uint8_t sha_224_expected[] = {
929         0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
930         0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
931     };
932     uint8_t sha_256_expected[] = {
933         0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
934         0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
935     };
936     uint8_t sha_384_expected[] = {
937         0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
938         0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
939     };
940     uint8_t sha_512_expected[] = {
941         0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
942         0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
943     };
944 
945     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
946     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
947     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
948     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
949 
950     EXPECT_EQ(0, GetParam()->keymaster0_calls());
951 }
952 
TEST_P(SigningOperationsTest,HmacRfc4231TestCase6)953 TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
954     string key(131, 0xaa);
955     string message = "Test Using Larger Than Block-Size Key - Hash Key First";
956 
957     uint8_t sha_224_expected[] = {
958         0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
959         0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
960     };
961     uint8_t sha_256_expected[] = {
962         0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
963         0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
964         0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
965     };
966     uint8_t sha_384_expected[] = {
967         0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
968         0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
969         0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
970         0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
971     };
972     uint8_t sha_512_expected[] = {
973         0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
974         0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
975         0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
976         0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
977         0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
978     };
979 
980     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
981     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
982     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
983     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
984 
985     EXPECT_EQ(0, GetParam()->keymaster0_calls());
986 }
987 
TEST_P(SigningOperationsTest,HmacRfc4231TestCase7)988 TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
989     string key(131, 0xaa);
990     string message = "This is a test using a larger than block-size key and a larger than "
991                      "block-size data. The key needs to be hashed before being used by the HMAC "
992                      "algorithm.";
993 
994     uint8_t sha_224_expected[] = {
995         0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
996         0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
997     };
998     uint8_t sha_256_expected[] = {
999         0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
1000         0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
1001         0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
1002     };
1003     uint8_t sha_384_expected[] = {
1004         0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
1005         0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
1006         0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
1007         0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
1008     };
1009     uint8_t sha_512_expected[] = {
1010         0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
1011         0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
1012         0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
1013         0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
1014         0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
1015     };
1016 
1017     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1018     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1019     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1020     CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1021 
1022     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1023 }
1024 
TEST_P(SigningOperationsTest,HmacSha256TooLargeMacLength)1025 TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1026     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1027                                            .HmacKey(128)
1028                                            .Digest(KM_DIGEST_SHA_2_256)
1029                                            .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1030     AuthorizationSet begin_params(client_params());
1031     begin_params.push_back(TAG_MAC_LENGTH, 264);
1032     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1033     ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH,
1034               BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1035 
1036     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1037 }
1038 
TEST_P(SigningOperationsTest,HmacSha256TooSmallMacLength)1039 TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1040     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1041                                            .HmacKey(128)
1042                                            .Digest(KM_DIGEST_SHA_2_256)
1043                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1044     AuthorizationSet begin_params(client_params());
1045     begin_params.push_back(TAG_MAC_LENGTH, 120);
1046     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1047     ASSERT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
1048               BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1049 
1050     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1051 }
1052 
1053 // TODO(swillden): Add more verification failure tests.
1054 
1055 typedef Keymaster2Test VerificationOperationsTest;
1056 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
1057 
TEST_P(VerificationOperationsTest,RsaSuccess)1058 TEST_P(VerificationOperationsTest, RsaSuccess) {
1059     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1060                                            .RsaSigningKey(256, 3)
1061                                            .Digest(KM_DIGEST_NONE)
1062                                            .Padding(KM_PAD_NONE)));
1063     string message = "12345678901234567890123456789012";
1064     string signature;
1065     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1066     VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1067 
1068     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1069         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1070 }
1071 
TEST_P(VerificationOperationsTest,RsaPssSha256Success)1072 TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
1073     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1074                                            .RsaSigningKey(768, 3)
1075                                            .Digest(KM_DIGEST_SHA_2_256)
1076                                            .Padding(KM_PAD_RSA_PSS)));
1077     // Use large message, which won't work without digesting.
1078     string message(1024, 'a');
1079     string signature;
1080     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1081     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1082 
1083     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1084         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1085 }
1086 
TEST_P(VerificationOperationsTest,RsaPssSha224Success)1087 TEST_P(VerificationOperationsTest, RsaPssSha224Success) {
1088     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1089                                            .RsaSigningKey(512, 3)
1090                                            .Digest(KM_DIGEST_SHA_2_224)
1091                                            .Padding(KM_PAD_RSA_PSS)));
1092     // Use large message, which won't work without digesting.
1093     string message(1024, 'a');
1094     string signature;
1095     SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1096     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1097 
1098     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1099         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1100 
1101     // Verify with OpenSSL.
1102     string pubkey;
1103     EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1104 
1105     const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1106     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1107         d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1108     ASSERT_TRUE(pkey.get());
1109 
1110     EVP_MD_CTX digest_ctx;
1111     EVP_MD_CTX_init(&digest_ctx);
1112     EVP_PKEY_CTX* pkey_ctx;
1113     EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1114                                       pkey.get()));
1115     EXPECT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING));
1116     EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1117     EXPECT_EQ(1,
1118               EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1119                                     signature.size()));
1120     EVP_MD_CTX_cleanup(&digest_ctx);
1121 }
1122 
TEST_P(VerificationOperationsTest,RsaPssSha256CorruptSignature)1123 TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
1124     GenerateKey(AuthorizationSetBuilder()
1125                     .RsaSigningKey(768, 3)
1126                     .Digest(KM_DIGEST_SHA_2_256)
1127                     .Padding(KM_PAD_RSA_PSS));
1128     string message(1024, 'a');
1129     string signature;
1130     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1131     ++signature[signature.size() / 2];
1132 
1133     AuthorizationSet begin_params(client_params());
1134     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1135     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1136     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1137 
1138     string result;
1139     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1140 
1141     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1142         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1143 }
1144 
TEST_P(VerificationOperationsTest,RsaPssSha256CorruptInput)1145 TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
1146     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1147                                            .RsaSigningKey(768, 3)
1148                                            .Digest(KM_DIGEST_SHA_2_256)
1149                                            .Padding(KM_PAD_RSA_PSS)));
1150     // Use large message, which won't work without digesting.
1151     string message(1024, 'a');
1152     string signature;
1153     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1154     ++message[message.size() / 2];
1155 
1156     AuthorizationSet begin_params(client_params());
1157     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1158     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1159     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1160 
1161     string result;
1162     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1163 
1164     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1165         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1166 }
1167 
TEST_P(VerificationOperationsTest,RsaPkcs1Sha256Success)1168 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
1169     GenerateKey(AuthorizationSetBuilder()
1170                     .RsaSigningKey(512, 3)
1171                     .Digest(KM_DIGEST_SHA_2_256)
1172                     .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1173     string message(1024, 'a');
1174     string signature;
1175     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1176     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1177 
1178     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1179         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1180 }
1181 
TEST_P(VerificationOperationsTest,RsaPks1Sha224Success)1182 TEST_P(VerificationOperationsTest, RsaPks1Sha224Success) {
1183     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1184                                            .RsaSigningKey(512, 3)
1185                                            .Digest(KM_DIGEST_SHA_2_224)
1186                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1187     // Use large message, which won't work without digesting.
1188     string message(1024, 'a');
1189     string signature;
1190     SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1191     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1192 
1193     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1194         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1195 
1196     // Verify with OpenSSL.
1197     string pubkey;
1198     EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1199 
1200     const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1201     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1202         d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1203     ASSERT_TRUE(pkey.get());
1204 
1205     EVP_MD_CTX digest_ctx;
1206     EVP_MD_CTX_init(&digest_ctx);
1207     EVP_PKEY_CTX* pkey_ctx;
1208     EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1209                                       pkey.get()));
1210     EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1211     EXPECT_EQ(1,
1212               EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1213                                     signature.size()));
1214     EVP_MD_CTX_cleanup(&digest_ctx);
1215 }
1216 
TEST_P(VerificationOperationsTest,RsaPkcs1Sha256CorruptSignature)1217 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
1218     GenerateKey(AuthorizationSetBuilder()
1219                     .RsaSigningKey(512, 3)
1220                     .Digest(KM_DIGEST_SHA_2_256)
1221                     .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1222     string message(1024, 'a');
1223     string signature;
1224     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1225     ++signature[signature.size() / 2];
1226 
1227     AuthorizationSet begin_params(client_params());
1228     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1229     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1230     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1231 
1232     string result;
1233     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1234 
1235     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1236         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1237 }
1238 
TEST_P(VerificationOperationsTest,RsaPkcs1Sha256CorruptInput)1239 TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
1240     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1241                                            .RsaSigningKey(512, 3)
1242                                            .Digest(KM_DIGEST_SHA_2_256)
1243                                            .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1244     // Use large message, which won't work without digesting.
1245     string message(1024, 'a');
1246     string signature;
1247     SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1248     ++message[message.size() / 2];
1249 
1250     AuthorizationSet begin_params(client_params());
1251     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1252     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1253     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1254 
1255     string result;
1256     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1257 
1258     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1259         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1260 }
1261 
TEST_P(VerificationOperationsTest,RsaAllDigestAndPadCombinations)1262 TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
1263     vector<keymaster_digest_t> digests = {
1264         KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
1265         KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1266     };
1267 
1268     vector<keymaster_padding_t> padding_modes{
1269         KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS,
1270     };
1271 
1272     int trial_count = 0;
1273     for (keymaster_padding_t padding_mode : padding_modes) {
1274         for (keymaster_digest_t digest : digests) {
1275             if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
1276                 // Digesting requires padding
1277                 continue;
1278 
1279             // Compute key & message size that will work.
1280             size_t key_bits = 0;
1281             size_t message_len = 1000;
1282 
1283             if (digest == KM_DIGEST_NONE) {
1284                 key_bits = 256;
1285                 switch (padding_mode) {
1286                 case KM_PAD_NONE:
1287                     // Match key size.
1288                     message_len = key_bits / 8;
1289                     break;
1290                 case KM_PAD_RSA_PKCS1_1_5_SIGN:
1291                     message_len = key_bits / 8 - 11;
1292                     break;
1293                 case KM_PAD_RSA_PSS:
1294                     // PSS requires a digest.
1295                     continue;
1296                 default:
1297                     FAIL() << "Missing padding";
1298                     break;
1299                 }
1300             } else {
1301                 size_t digest_bits;
1302                 switch (digest) {
1303                 case KM_DIGEST_MD5:
1304                     digest_bits = 128;
1305                     break;
1306                 case KM_DIGEST_SHA1:
1307                     digest_bits = 160;
1308                     break;
1309                 case KM_DIGEST_SHA_2_224:
1310                     digest_bits = 224;
1311                     break;
1312                 case KM_DIGEST_SHA_2_256:
1313                     digest_bits = 256;
1314                     break;
1315                 case KM_DIGEST_SHA_2_384:
1316                     digest_bits = 384;
1317                     break;
1318                 case KM_DIGEST_SHA_2_512:
1319                     digest_bits = 512;
1320                     break;
1321                 default:
1322                     FAIL() << "Missing digest";
1323                 }
1324 
1325                 switch (padding_mode) {
1326                 case KM_PAD_RSA_PKCS1_1_5_SIGN:
1327                     key_bits = digest_bits + 8 * (11 + 19);
1328                     break;
1329                 case KM_PAD_RSA_PSS:
1330                     key_bits = digest_bits * 2 + 2 * 8;
1331                     break;
1332                 default:
1333                     FAIL() << "Missing padding";
1334                     break;
1335                 }
1336             }
1337 
1338             // Round up to the nearest multiple of 128.
1339             key_bits = (key_bits + 127) / 128 * 128;
1340 
1341             GenerateKey(AuthorizationSetBuilder()
1342                             .RsaSigningKey(key_bits, 3)
1343                             .Digest(digest)
1344                             .Padding(padding_mode));
1345             string message(message_len, 'a');
1346             string signature;
1347             SignMessage(message, &signature, digest, padding_mode);
1348             VerifyMessage(message, signature, digest, padding_mode);
1349             ++trial_count;
1350         }
1351     }
1352 
1353     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1354         EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
1355 }
1356 
TEST_P(VerificationOperationsTest,EcdsaSuccess)1357 TEST_P(VerificationOperationsTest, EcdsaSuccess) {
1358     ASSERT_EQ(KM_ERROR_OK,
1359               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1360     string message = "12345678901234567890123456789012";
1361     string signature;
1362     SignMessage(message, &signature, KM_DIGEST_NONE);
1363     VerifyMessage(message, signature, KM_DIGEST_NONE);
1364 
1365     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1366         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1367 }
1368 
TEST_P(VerificationOperationsTest,EcdsaTooShort)1369 TEST_P(VerificationOperationsTest, EcdsaTooShort) {
1370     ASSERT_EQ(KM_ERROR_OK,
1371               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1372     string message = "12345678901234567890";
1373     string signature;
1374     SignMessage(message, &signature, KM_DIGEST_NONE);
1375     VerifyMessage(message, signature, KM_DIGEST_NONE);
1376 
1377     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1378         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1379 }
1380 
TEST_P(VerificationOperationsTest,EcdsaSlightlyTooLong)1381 TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
1382     ASSERT_EQ(KM_ERROR_OK,
1383               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
1384 
1385     string message(66, 'a');
1386     string signature;
1387     SignMessage(message, &signature, KM_DIGEST_NONE);
1388     VerifyMessage(message, signature, KM_DIGEST_NONE);
1389 
1390     // Modifying low-order bits doesn't matter, because they didn't get signed.  Ugh.
1391     message[65] ^= 7;
1392     VerifyMessage(message, signature, KM_DIGEST_NONE);
1393 
1394     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1395         EXPECT_EQ(5, GetParam()->keymaster0_calls());
1396 }
1397 
TEST_P(VerificationOperationsTest,EcdsaSha256Success)1398 TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
1399     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1400                                            .EcdsaSigningKey(256)
1401                                            .Digest(KM_DIGEST_SHA_2_256)
1402                                            .Digest(KM_DIGEST_NONE)));
1403     string message = "12345678901234567890123456789012";
1404     string signature;
1405     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
1406     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1407 
1408     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1409         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1410 
1411     // Just for giggles, try verifying with the wrong digest.
1412     AuthorizationSet begin_params(client_params());
1413     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1414     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1415 
1416     string result;
1417     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1418 }
1419 
TEST_P(VerificationOperationsTest,EcdsaSha224Success)1420 TEST_P(VerificationOperationsTest, EcdsaSha224Success) {
1421     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
1422                                KM_DIGEST_SHA_2_224)));
1423 
1424     string message = "12345678901234567890123456789012";
1425     string signature;
1426     SignMessage(message, &signature, KM_DIGEST_SHA_2_224);
1427     VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
1428 
1429     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1430         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1431 
1432     // Just for giggles, try verifying with the wrong digest.
1433     AuthorizationSet begin_params(client_params());
1434     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1435     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1436 
1437     string result;
1438     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(message, signature, &result));
1439 }
1440 
TEST_P(VerificationOperationsTest,EcdsaAllDigestsAndKeySizes)1441 TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndKeySizes) {
1442     keymaster_digest_t digests[] = {
1443         KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
1444         KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1445     };
1446     size_t key_sizes[] = {224, 256, 384, 521};
1447 
1448     string message = "1234567890";
1449     string signature;
1450 
1451     for (auto key_size : key_sizes) {
1452         SCOPED_TRACE(testing::Message() << "Key size: " << key_size);
1453         AuthorizationSetBuilder builder;
1454         builder.EcdsaSigningKey(key_size);
1455         for (auto digest : digests)
1456             builder.Digest(digest);
1457         ASSERT_EQ(KM_ERROR_OK, GenerateKey(builder));
1458 
1459         for (auto digest : digests) {
1460             SCOPED_TRACE(testing::Message() << "Digest: " << digest);
1461             SignMessage(message, &signature, digest);
1462             VerifyMessage(message, signature, digest);
1463         }
1464     }
1465 
1466     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1467         EXPECT_EQ(static_cast<int>(array_length(key_sizes) * (1 + 3 * array_length(digests))),
1468                   GetParam()->keymaster0_calls());
1469 }
1470 
TEST_P(VerificationOperationsTest,HmacSha1Success)1471 TEST_P(VerificationOperationsTest, HmacSha1Success) {
1472     GenerateKey(AuthorizationSetBuilder()
1473                     .HmacKey(128)
1474                     .Digest(KM_DIGEST_SHA1)
1475                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1476     string message = "123456789012345678901234567890123456789012345678";
1477     string signature;
1478     MacMessage(message, &signature, 160);
1479     VerifyMac(message, signature);
1480 
1481     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1482 }
1483 
TEST_P(VerificationOperationsTest,HmacSha224Success)1484 TEST_P(VerificationOperationsTest, HmacSha224Success) {
1485     GenerateKey(AuthorizationSetBuilder()
1486                     .HmacKey(128)
1487                     .Digest(KM_DIGEST_SHA_2_224)
1488                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1489     string message = "123456789012345678901234567890123456789012345678";
1490     string signature;
1491     MacMessage(message, &signature, 224);
1492     VerifyMac(message, signature);
1493 
1494     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1495 }
1496 
TEST_P(VerificationOperationsTest,HmacSha256Success)1497 TEST_P(VerificationOperationsTest, HmacSha256Success) {
1498     GenerateKey(AuthorizationSetBuilder()
1499                     .HmacKey(128)
1500                     .Digest(KM_DIGEST_SHA_2_256)
1501                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1502     string message = "123456789012345678901234567890123456789012345678";
1503     string signature;
1504     MacMessage(message, &signature, 256);
1505     VerifyMac(message, signature);
1506 
1507     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1508 }
1509 
TEST_P(VerificationOperationsTest,HmacSha256TooShortMac)1510 TEST_P(VerificationOperationsTest, HmacSha256TooShortMac) {
1511     GenerateKey(AuthorizationSetBuilder()
1512                     .HmacKey(128)
1513                     .Digest(KM_DIGEST_SHA_2_256)
1514                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1515     string message = "123456789012345678901234567890123456789012345678";
1516     string signature;
1517     MacMessage(message, &signature, 256);
1518 
1519     // Shorten to 128 bits, should still work.
1520     signature.resize(128 / 8);
1521     VerifyMac(message, signature);
1522 
1523     // Drop one more byte.
1524     signature.resize(signature.length() - 1);
1525 
1526     AuthorizationSet begin_params(client_params());
1527     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1528     string result;
1529     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, FinishOperation(message, signature, &result));
1530 
1531     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1532 }
1533 
TEST_P(VerificationOperationsTest,HmacSha384Success)1534 TEST_P(VerificationOperationsTest, HmacSha384Success) {
1535     GenerateKey(AuthorizationSetBuilder()
1536                     .HmacKey(128)
1537                     .Digest(KM_DIGEST_SHA_2_384)
1538                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1539     string message = "123456789012345678901234567890123456789012345678";
1540     string signature;
1541     MacMessage(message, &signature, 384);
1542     VerifyMac(message, signature);
1543 
1544     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1545 }
1546 
TEST_P(VerificationOperationsTest,HmacSha512Success)1547 TEST_P(VerificationOperationsTest, HmacSha512Success) {
1548     GenerateKey(AuthorizationSetBuilder()
1549                     .HmacKey(128)
1550                     .Digest(KM_DIGEST_SHA_2_512)
1551                     .Authorization(TAG_MIN_MAC_LENGTH, 128));
1552     string message = "123456789012345678901234567890123456789012345678";
1553     string signature;
1554     MacMessage(message, &signature, 512);
1555     VerifyMac(message, signature);
1556 
1557     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1558 }
1559 
1560 typedef Keymaster2Test ExportKeyTest;
1561 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
1562 
TEST_P(ExportKeyTest,RsaSuccess)1563 TEST_P(ExportKeyTest, RsaSuccess) {
1564     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1565                                            .RsaSigningKey(256, 3)
1566                                            .Digest(KM_DIGEST_NONE)
1567                                            .Padding(KM_PAD_NONE)));
1568     string export_data;
1569     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1570     EXPECT_GT(export_data.length(), 0U);
1571 
1572     // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1573 
1574     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1575         EXPECT_EQ(2, GetParam()->keymaster0_calls());
1576 }
1577 
TEST_P(ExportKeyTest,EcdsaSuccess)1578 TEST_P(ExportKeyTest, EcdsaSuccess) {
1579     ASSERT_EQ(KM_ERROR_OK,
1580               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
1581     string export_data;
1582     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1583     EXPECT_GT(export_data.length(), 0U);
1584 
1585     // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1586 
1587     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1588         EXPECT_EQ(2, GetParam()->keymaster0_calls());
1589 }
1590 
TEST_P(ExportKeyTest,RsaUnsupportedKeyFormat)1591 TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
1592     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1593                                            .RsaSigningKey(256, 3)
1594                                            .Digest(KM_DIGEST_NONE)
1595                                            .Padding(KM_PAD_NONE)));
1596     string export_data;
1597     ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1598 
1599     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1600         EXPECT_EQ(2, GetParam()->keymaster0_calls());
1601 }
1602 
TEST_P(ExportKeyTest,RsaCorruptedKeyBlob)1603 TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
1604     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1605                                            .RsaSigningKey(256, 3)
1606                                            .Digest(KM_DIGEST_NONE)
1607                                            .Padding(KM_PAD_NONE)));
1608     corrupt_key_blob();
1609     string export_data;
1610     ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1611 
1612     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1613         EXPECT_EQ(2, GetParam()->keymaster0_calls());
1614 }
1615 
TEST_P(ExportKeyTest,AesKeyExportFails)1616 TEST_P(ExportKeyTest, AesKeyExportFails) {
1617     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
1618     string export_data;
1619 
1620     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1621     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1622     EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
1623 
1624     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1625 }
1626 
read_file(const string & file_name)1627 static string read_file(const string& file_name) {
1628     ifstream file_stream(file_name, std::ios::binary);
1629     istreambuf_iterator<char> file_begin(file_stream);
1630     istreambuf_iterator<char> file_end;
1631     return string(file_begin, file_end);
1632 }
1633 
1634 typedef Keymaster2Test ImportKeyTest;
1635 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
1636 
TEST_P(ImportKeyTest,RsaSuccess)1637 TEST_P(ImportKeyTest, RsaSuccess) {
1638     string pk8_key = read_file("rsa_privkey_pk8.der");
1639     ASSERT_EQ(633U, pk8_key.size());
1640 
1641     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1642                                          .RsaSigningKey(1024, 65537)
1643                                          .Digest(KM_DIGEST_NONE)
1644                                          .Padding(KM_PAD_NONE),
1645                                      KM_KEY_FORMAT_PKCS8, pk8_key));
1646 
1647     // Check values derived from the key.
1648     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1649                                                                                  : sw_enforced(),
1650                          TAG_ALGORITHM, KM_ALGORITHM_RSA));
1651     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1652                                                                                  : sw_enforced(),
1653                          TAG_KEY_SIZE, 1024));
1654     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1655                                                                                  : sw_enforced(),
1656                          TAG_RSA_PUBLIC_EXPONENT, 65537U));
1657 
1658     // And values provided by AndroidKeymaster
1659     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1660         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1661     else
1662         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1663     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1664 
1665     string message(1024 / 8, 'a');
1666     string signature;
1667     SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1668     VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1669 
1670     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1671         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1672 }
1673 
TEST_P(ImportKeyTest,RsaKeySizeMismatch)1674 TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1675     string pk8_key = read_file("rsa_privkey_pk8.der");
1676     ASSERT_EQ(633U, pk8_key.size());
1677     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1678               ImportKey(AuthorizationSetBuilder()
1679                             .RsaSigningKey(2048 /* Doesn't match key */, 3)
1680                             .Digest(KM_DIGEST_NONE)
1681                             .Padding(KM_PAD_NONE),
1682                         KM_KEY_FORMAT_PKCS8, pk8_key));
1683 
1684     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1685 }
1686 
TEST_P(ImportKeyTest,RsaPublicExponenMismatch)1687 TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
1688     string pk8_key = read_file("rsa_privkey_pk8.der");
1689     ASSERT_EQ(633U, pk8_key.size());
1690     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1691               ImportKey(AuthorizationSetBuilder()
1692                             .RsaSigningKey(256, 3 /* Doesnt' match key */)
1693                             .Digest(KM_DIGEST_NONE)
1694                             .Padding(KM_PAD_NONE),
1695                         KM_KEY_FORMAT_PKCS8, pk8_key));
1696 
1697     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1698 }
1699 
TEST_P(ImportKeyTest,EcdsaSuccess)1700 TEST_P(ImportKeyTest, EcdsaSuccess) {
1701     string pk8_key = read_file("ec_privkey_pk8.der");
1702     ASSERT_EQ(138U, pk8_key.size());
1703 
1704     ASSERT_EQ(KM_ERROR_OK,
1705               ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1706                         KM_KEY_FORMAT_PKCS8, pk8_key));
1707 
1708     // Check values derived from the key.
1709     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1710                                                                                 : sw_enforced(),
1711                          TAG_ALGORITHM, KM_ALGORITHM_EC));
1712     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1713                                                                                 : sw_enforced(),
1714                          TAG_KEY_SIZE, 256));
1715 
1716     // And values provided by AndroidKeymaster
1717     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1718         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1719     else
1720         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1721     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1722 
1723     string message(32, 'a');
1724     string signature;
1725     SignMessage(message, &signature, KM_DIGEST_NONE);
1726     VerifyMessage(message, signature, KM_DIGEST_NONE);
1727 
1728     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1729         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1730 }
1731 
TEST_P(ImportKeyTest,EcdsaSizeSpecified)1732 TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
1733     string pk8_key = read_file("ec_privkey_pk8.der");
1734     ASSERT_EQ(138U, pk8_key.size());
1735 
1736     ASSERT_EQ(KM_ERROR_OK,
1737               ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1738                         KM_KEY_FORMAT_PKCS8, pk8_key));
1739 
1740     // Check values derived from the key.
1741     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1742                                                                                 : sw_enforced(),
1743                          TAG_ALGORITHM, KM_ALGORITHM_EC));
1744     EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1745                                                                                 : sw_enforced(),
1746                          TAG_KEY_SIZE, 256));
1747 
1748     // And values provided by AndroidKeymaster
1749     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1750         EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1751     else
1752         EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1753     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1754 
1755     string message(32, 'a');
1756     string signature;
1757     SignMessage(message, &signature, KM_DIGEST_NONE);
1758     VerifyMessage(message, signature, KM_DIGEST_NONE);
1759 
1760     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1761         EXPECT_EQ(4, GetParam()->keymaster0_calls());
1762 }
1763 
TEST_P(ImportKeyTest,EcdsaSizeMismatch)1764 TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
1765     string pk8_key = read_file("ec_privkey_pk8.der");
1766     ASSERT_EQ(138U, pk8_key.size());
1767     ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1768               ImportKey(AuthorizationSetBuilder()
1769                             .EcdsaSigningKey(224 /* Doesn't match key */)
1770                             .Digest(KM_DIGEST_NONE),
1771                         KM_KEY_FORMAT_PKCS8, pk8_key));
1772 
1773     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1774 }
1775 
TEST_P(ImportKeyTest,AesKeySuccess)1776 TEST_P(ImportKeyTest, AesKeySuccess) {
1777     char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1778     string key(key_data, sizeof(key_data));
1779     ASSERT_EQ(KM_ERROR_OK,
1780               ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
1781                             TAG_PADDING, KM_PAD_PKCS7),
1782                         KM_KEY_FORMAT_RAW, key));
1783 
1784     EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1785     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1786 
1787     string message = "Hello World!";
1788     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
1789     string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
1790     EXPECT_EQ(message, plaintext);
1791 
1792     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1793 }
1794 
TEST_P(ImportKeyTest,HmacSha256KeySuccess)1795 TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
1796     char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1797     string key(key_data, sizeof(key_data));
1798     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1799                                          .HmacKey(sizeof(key_data) * 8)
1800                                          .Digest(KM_DIGEST_SHA_2_256)
1801                                          .Authorization(TAG_MIN_MAC_LENGTH, 256),
1802                                      KM_KEY_FORMAT_RAW, key));
1803 
1804     EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1805     EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1806 
1807     string message = "Hello World!";
1808     string signature;
1809     MacMessage(message, &signature, 256);
1810     VerifyMac(message, signature);
1811 
1812     EXPECT_EQ(0, GetParam()->keymaster0_calls());
1813 }
1814 
1815 string wrapped_key = hex2str(
1816     "3082017302010004820100A2B7988012A043CE83E762A4E4D3C86D578B2E1EA5E04138353114A816951308E3222AFA"
1817     "D86CA141C581198E65BC56D9EEDC5B555713BE2C20948DD076AB4980305871317F89DD3A7A67FBBB7AACF6941C06B2"
1818     "65396D894A6DCC7B9FB152FFA8CBF44FF8063748795F3FB506DF8718535289E759075A13A5DDC83EF8470549AA7794"
1819     "3AFBACF6CF82DCE3751E05BFE05F30B998D73E23611E6EAEFC2A497E097A895C4242607B472AE8F19DA77A9A5A4786"
1820     "75541FC813C9213B5CE8C2E598BFBBCD1B369E3D7AEC0274F9B79118D8AA5FBB7634EBD3C4C2AF3B5DA483DF2CFDF1"
1821     "E68A3BFC7B6C0D503AF88E82C9EE841A278B144FF8D39F2DB2ACE9415C120190040CD796B02C370F1FA4CC0124F130"
1822     "280201033023A1083106020100020101A203020120A30402020100A4053103020101A60531030201400420CCD54085"
1823     "5F833A5E1480BFD2D36FAF3AEEE15DF5BEABE2691BC82DDE2A7AA91004107CB81BDDCD09E8F4DF575726279F3229");
1824 
1825 string wrapped_key_masked = hex2str(
1826     "30820173020100048201008CBEE0DC600215FFC85FC26B57DD2331DDF5D3E106C0A68BFEF167AFD428041D9B7C3316"
1827     "110BBB914A86FC24D4EF5C6A4673C9B3CC914C7806453650753B5130C4FE72264A52C1A270286032513F24EB3E033A"
1828     "BCC26A9D6AEFD0D0AD3E922E4E737ECDAD3C4DF2ABDB416378E67381BE0391175EC8F05FDFBC3794B7D0D88298010F"
1829     "E9B6F788BC049D874575D2D4C33DB582B113694738A9151BBC7603D3556B26FEC0279EE1C1CA44D6F7F91F4C424912"
1830     "7F9CC3232DE8B0AEFFD5AFAD4C3D5B846FD26873315606F6457BC19447FD7C6431550D6E6592A0555E61C7A021D149"
1831     "BCEE7A858DD6D4A8E230C6015EEDF0A58F4CAA8A6D0E3A1E3794CAEE7854CE92040C6D9721D08589581AB49204A330"
1832     "280201033023A1083106020100020101A203020120A30402020100A4053103020101A60531030201400420A61C6E24"
1833     "7E25B3E6E69AA78EB03C2D4AC20D1F99A9A024A76F35C8E2CAB9B68D04101FF7A0E793B9EE4AECEBB9AC4C545254");
1834 
1835 string wrapping_key = hex2str(
1836     "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d8900ce56"
1837     "b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86acbddc41bb759c28"
1838     "54eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe7c0d23be312d7bd5921ffaea"
1839     "1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c1374c3886427411c449796792e0bef75dec"
1840     "858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3a7ee4991d0d48b0172a95f9536f02ba13cecccb9"
1841     "2b727db5c27e5b2f5cec09600b286af5cf14c42024c61ddfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed"
1842     "3f4833cca2bd8fa62821dd55020301000102820100431447b6251908112b1ee76f99f3711a52b6630960046c2de70d"
1843     "e188d833f8b8b91e4d785caeeeaf4f0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b"
1844     "5d2c43080e52bee71e9eaeb6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2"
1845     "579ba02aae0a00900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4"
1846     "a957bbddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f851"
1847     "e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f8618102818100de"
1848     "392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a164c5970007047b8c517"
1849     "db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788e1f1a97223b524b5357fdf72e2"
1850     "f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d71c743502818100c95387c0f9d35f137b57"
1851     "d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3863ca645fcce49582a9aa17349db6c4a95affdae0d"
1852     "ae612e1afac99ed39a2d934c880440aed8832f9843163a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f583093"
1853     "66a7de25f7c3c9b880677c068e1be936e81288815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0"
1854     "b8b36cd6c136e52e4085f4ea5a063212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece"
1855     "1af76ad0b030f27af6f0ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719"
1856     "d6e2b9439823719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b65"
1857     "56ca31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8a43e"
1858     "34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277cff1e6aaa5d57"
1859     "aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6864236d0c4736a0008a1"
1860     "45af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2bfdfe27ae778983f959356210723"
1861     "287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9bf27ba61be6ad02dfddda8f4e6822");
1862 
1863 string zero_masking_key =
1864     hex2str("0000000000000000000000000000000000000000000000000000000000000000");
1865 string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
1866 
1867 class ImportWrappedKeyTest : public testing::Test {
1868   public:
ImportWrappedKeyTest()1869     ImportWrappedKeyTest() : keymaster_(new PureSoftKeymasterContext(), 16) {}
1870 
1871   protected:
SetUp()1872     void SetUp() override {
1873         ConfigureRequest configReq;
1874         configReq.os_version = kOsVersion;
1875         configReq.os_patchlevel = kOsPatchLevel;
1876         ConfigureResponse configRsp;
1877         keymaster_.Configure(configReq, &configRsp);
1878         EXPECT_EQ(KM_ERROR_OK, configRsp.error);
1879     }
1880 
BeginOperation(keymaster_purpose_t purpose,const AuthorizationSet & input_set)1881     keymaster_error_t BeginOperation(keymaster_purpose_t purpose,
1882                                      const AuthorizationSet& input_set) {
1883         BeginOperationRequest req;
1884         req.purpose = purpose;
1885         req.SetKeyMaterial(blob_);
1886         req.additional_params = input_set;
1887 
1888         BeginOperationResponse rsp;
1889         keymaster_.BeginOperation(req, &rsp);
1890         op_handle_ = rsp.op_handle;
1891 
1892         return rsp.error;
1893     }
1894 
FinishOperation(const string & input,string * output)1895     keymaster_error_t FinishOperation(const string& input, string* output) {
1896         FinishOperationRequest req;
1897         req.op_handle = op_handle_;
1898         req.input.Reinitialize(input.data(), input.size());
1899 
1900         FinishOperationResponse rsp;
1901         keymaster_.FinishOperation(req, &rsp);
1902 
1903         if (output) {
1904             *output = string(reinterpret_cast<const char*>(rsp.output.peek_read()),
1905                              rsp.output.available_read());
1906         }
1907 
1908         return rsp.error;
1909     }
1910 
ProcessMessage(keymaster_purpose_t purpose,const string & message,const AuthorizationSet & begin_params)1911     string ProcessMessage(keymaster_purpose_t purpose, const string& message,
1912                           const AuthorizationSet& begin_params) {
1913         EXPECT_EQ(KM_ERROR_OK, BeginOperation(purpose, begin_params));
1914 
1915         string result;
1916         EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, &result));
1917         return result;
1918     }
1919 
1920     AndroidKeymaster keymaster_;
1921     KeymasterKeyBlob blob_;
1922     uint64_t op_handle_;
1923 };
1924 
TEST_F(ImportWrappedKeyTest,GoldenKeySuccess)1925 TEST_F(ImportWrappedKeyTest, GoldenKeySuccess) {
1926     ImportKeyRequest import_request;
1927 
1928     auto import_params = AuthorizationSetBuilder()
1929                              .RsaEncryptionKey(2048, 65537)
1930                              .Digest(KM_DIGEST_SHA1)
1931                              .Padding(KM_PAD_RSA_OAEP)
1932                              .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
1933                              .build();
1934     import_request.key_description.Reinitialize(import_params);
1935     import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
1936                                   wrapping_key.size());
1937     import_request.key_format = KM_KEY_FORMAT_PKCS8;
1938     ImportKeyResponse import_response;
1939     keymaster_.ImportKey(import_request, &import_response);
1940     ASSERT_EQ(import_response.error, KM_ERROR_OK);
1941 
1942     ImportWrappedKeyRequest request;
1943     KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key.c_str()),
1944                                       wrapped_key.size());
1945     request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
1946     request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(zero_masking_key.c_str()),
1947                                   zero_masking_key.size());
1948     ImportWrappedKeyResponse response;
1949 
1950     keymaster_.ImportWrappedKey(request, &response);
1951 
1952     EXPECT_EQ(response.error, KM_ERROR_OK);
1953     // Check that the tags from the wrapped auth list were imported correctly
1954     ASSERT_EQ(response.key_blob.key_material_size > 0, true);
1955     ASSERT_EQ(response.unenforced.Contains(TAG_ALGORITHM), true);
1956     ASSERT_EQ(response.unenforced.Contains(TAG_KEY_SIZE), true);
1957     ASSERT_EQ(response.unenforced.Contains(TAG_PURPOSE), true);
1958     ASSERT_EQ(response.unenforced.Contains(TAG_BLOCK_MODE), true);
1959 
1960     blob_ = move(response.key_blob);
1961 
1962     string message = "Hello World!";
1963     auto params = AuthorizationSetBuilder().BlockMode(KM_MODE_ECB).Padding(KM_PAD_PKCS7).build();
1964     string ciphertext = ProcessMessage(KM_PURPOSE_ENCRYPT, message, params);
1965     string plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext, params);
1966 
1967     EXPECT_EQ(message, plaintext);
1968 }
1969 
TEST_F(ImportWrappedKeyTest,SuccessMaskingKey)1970 TEST_F(ImportWrappedKeyTest, SuccessMaskingKey) {
1971     ImportKeyRequest import_request;
1972 
1973     auto import_params = AuthorizationSetBuilder()
1974                              .RsaEncryptionKey(2048, 65537)
1975                              .Digest(KM_DIGEST_SHA1)
1976                              .Padding(KM_PAD_RSA_OAEP)
1977                              .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
1978                              .build();
1979     import_request.key_description.Reinitialize(import_params);
1980     import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
1981                                   wrapping_key.size());
1982 
1983     import_request.key_format = KM_KEY_FORMAT_PKCS8;
1984     ImportKeyResponse import_response;
1985     keymaster_.ImportKey(import_request, &import_response);
1986     EXPECT_EQ(import_response.error, KM_ERROR_OK);
1987 
1988     if (import_response.error != KM_ERROR_OK) return;
1989 
1990     ImportWrappedKeyRequest request;
1991     KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key_masked.c_str()),
1992                                       wrapped_key_masked.size());
1993     request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
1994     request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(masking_key.c_str()),
1995                                   masking_key.size());
1996     ImportWrappedKeyResponse response;
1997 
1998     keymaster_.ImportWrappedKey(request, &response);
1999     EXPECT_EQ(response.error, KM_ERROR_OK);
2000 }
2001 
TEST_F(ImportWrappedKeyTest,WrongMaskingKey)2002 TEST_F(ImportWrappedKeyTest, WrongMaskingKey) {
2003     ImportKeyRequest import_request;
2004 
2005     auto import_params = AuthorizationSetBuilder()
2006                              .RsaEncryptionKey(2048, 65537)
2007                              .Digest(KM_DIGEST_SHA1)
2008                              .Padding(KM_PAD_RSA_OAEP)
2009                              .Authorization(TAG_PURPOSE, KM_PURPOSE_WRAP)
2010                              .build();
2011     import_request.key_description.Reinitialize(import_params);
2012     import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
2013                                   wrapping_key.size());
2014 
2015     import_request.key_format = KM_KEY_FORMAT_PKCS8;
2016     ImportKeyResponse import_response;
2017     keymaster_.ImportKey(import_request, &import_response);
2018     EXPECT_EQ(import_response.error, KM_ERROR_OK);
2019 
2020     if (import_response.error != KM_ERROR_OK) return;
2021 
2022     ImportWrappedKeyRequest request;
2023     KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key_masked.c_str()),
2024                                       wrapped_key_masked.size());
2025     request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
2026     request.SetMaskingKeyMaterial(reinterpret_cast<const uint8_t*>(zero_masking_key.c_str()),
2027                                   zero_masking_key.size());
2028     ImportWrappedKeyResponse response;
2029 
2030     keymaster_.ImportWrappedKey(request, &response);
2031     EXPECT_EQ(response.error, KM_ERROR_VERIFICATION_FAILED);
2032 }
2033 
TEST_F(ImportWrappedKeyTest,WrongPurpose)2034 TEST_F(ImportWrappedKeyTest, WrongPurpose) {
2035     ImportKeyRequest import_request;
2036 
2037     auto import_params = AuthorizationSetBuilder()
2038                              .RsaEncryptionKey(2048, 65537)
2039                              .Digest(KM_DIGEST_SHA1)
2040                              .Padding(KM_PAD_RSA_OAEP)
2041                              .build();
2042     import_request.key_description.Reinitialize(import_params);
2043     import_request.SetKeyMaterial(reinterpret_cast<const uint8_t*>(wrapping_key.c_str()),
2044                                   wrapping_key.size());
2045     import_request.key_format = KM_KEY_FORMAT_PKCS8;
2046     ImportKeyResponse import_response;
2047     keymaster_.ImportKey(import_request, &import_response);
2048     EXPECT_EQ(import_response.error, KM_ERROR_OK);
2049 
2050     if (import_response.error != KM_ERROR_OK) return;
2051 
2052     ImportWrappedKeyRequest request;
2053     KeymasterKeyBlob wrapped_key_blob(reinterpret_cast<const uint8_t*>(wrapped_key.c_str()),
2054                                       wrapped_key.size());
2055     request.SetKeyMaterial(wrapped_key_blob, import_response.key_blob);
2056     ImportWrappedKeyResponse response;
2057 
2058     keymaster_.ImportWrappedKey(request, &response);
2059     EXPECT_EQ(response.error, KM_ERROR_INCOMPATIBLE_PURPOSE);
2060 }
2061 
2062 typedef Keymaster2Test EncryptionOperationsTest;
2063 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
2064 
TEST_P(EncryptionOperationsTest,RsaNoPaddingSuccess)2065 TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2066     ASSERT_EQ(KM_ERROR_OK,
2067               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2068 
2069     string message = "12345678901234567890123456789012";
2070     string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
2071     EXPECT_EQ(256U / 8, ciphertext1.size());
2072 
2073     string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
2074     EXPECT_EQ(256U / 8, ciphertext2.size());
2075 
2076     // Unpadded RSA is deterministic
2077     EXPECT_EQ(ciphertext1, ciphertext2);
2078 
2079     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2080         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2081 }
2082 
TEST_P(EncryptionOperationsTest,RsaNoPaddingTooShort)2083 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
2084     ASSERT_EQ(KM_ERROR_OK,
2085               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2086 
2087     string message = "1";
2088 
2089     string ciphertext = EncryptMessage(message, KM_PAD_NONE);
2090     EXPECT_EQ(256U / 8, ciphertext.size());
2091 
2092     string expected_plaintext = string(256 / 8 - 1, 0) + message;
2093     string plaintext = DecryptMessage(ciphertext, KM_PAD_NONE);
2094 
2095     EXPECT_EQ(expected_plaintext, plaintext);
2096 
2097     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2098         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2099 }
2100 
TEST_P(EncryptionOperationsTest,RsaNoPaddingTooLong)2101 TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2102     ASSERT_EQ(KM_ERROR_OK,
2103               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2104 
2105     string message = "123456789012345678901234567890123";
2106 
2107     AuthorizationSet begin_params(client_params());
2108     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2109     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2110 
2111     string result;
2112     size_t input_consumed;
2113     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
2114 
2115     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2116         EXPECT_EQ(2, GetParam()->keymaster0_calls());
2117 }
2118 
TEST_P(EncryptionOperationsTest,RsaNoPaddingLargerThanModulus)2119 TEST_P(EncryptionOperationsTest, RsaNoPaddingLargerThanModulus) {
2120     ASSERT_EQ(KM_ERROR_OK,
2121               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
2122 
2123     string exported;
2124     ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &exported));
2125 
2126     const uint8_t* p = reinterpret_cast<const uint8_t*>(exported.data());
2127     unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
2128         d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
2129     unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pkey.get()));
2130 
2131     size_t modulus_len = BN_num_bytes(rsa->n);
2132     ASSERT_EQ(256U / 8, modulus_len);
2133     unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
2134     BN_bn2bin(rsa->n, modulus_buf.get());
2135 
2136     // The modulus is too big to encrypt.
2137     string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2138 
2139     AuthorizationSet begin_params(client_params());
2140     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2141     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2142 
2143     string result;
2144     size_t input_consumed;
2145     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2146     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
2147 
2148     // One smaller than the modulus is okay.
2149     BN_sub(rsa->n, rsa->n, BN_value_one());
2150     modulus_len = BN_num_bytes(rsa->n);
2151     ASSERT_EQ(256U / 8, modulus_len);
2152     BN_bn2bin(rsa->n, modulus_buf.get());
2153     message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
2154     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2155     EXPECT_EQ(KM_ERROR_OK, FinishOperation(message, "", &result));
2156 
2157     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2158         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2159 }
2160 
TEST_P(EncryptionOperationsTest,RsaOaepSuccess)2161 TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2162     size_t key_size = 768;
2163     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2164                                            .RsaEncryptionKey(key_size, 3)
2165                                            .Padding(KM_PAD_RSA_OAEP)
2166                                            .Digest(KM_DIGEST_SHA_2_256)));
2167 
2168     string message = "Hello";
2169     string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2170     EXPECT_EQ(key_size / 8, ciphertext1.size());
2171 
2172     string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2173     EXPECT_EQ(key_size / 8, ciphertext2.size());
2174 
2175     // OAEP randomizes padding so every result should be different.
2176     EXPECT_NE(ciphertext1, ciphertext2);
2177 
2178     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2179         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2180 }
2181 
TEST_P(EncryptionOperationsTest,RsaOaepSha224Success)2182 TEST_P(EncryptionOperationsTest, RsaOaepSha224Success) {
2183     size_t key_size = 768;
2184     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2185                                            .RsaEncryptionKey(key_size, 3)
2186                                            .Padding(KM_PAD_RSA_OAEP)
2187                                            .Digest(KM_DIGEST_SHA_2_224)));
2188 
2189     string message = "Hello";
2190     string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2191     EXPECT_EQ(key_size / 8, ciphertext1.size());
2192 
2193     string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2194     EXPECT_EQ(key_size / 8, ciphertext2.size());
2195 
2196     // OAEP randomizes padding so every result should be different.
2197     EXPECT_NE(ciphertext1, ciphertext2);
2198 
2199     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2200         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2201 }
2202 
TEST_P(EncryptionOperationsTest,RsaOaepRoundTrip)2203 TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
2204     size_t key_size = 768;
2205     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2206                                            .RsaEncryptionKey(key_size, 3)
2207                                            .Padding(KM_PAD_RSA_OAEP)
2208                                            .Digest(KM_DIGEST_SHA_2_256)));
2209     string message = "Hello World!";
2210     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2211     EXPECT_EQ(key_size / 8, ciphertext.size());
2212 
2213     string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2214     EXPECT_EQ(message, plaintext);
2215 
2216     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2217         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2218 }
2219 
TEST_P(EncryptionOperationsTest,RsaOaepSha224RoundTrip)2220 TEST_P(EncryptionOperationsTest, RsaOaepSha224RoundTrip) {
2221     size_t key_size = 768;
2222     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2223                                            .RsaEncryptionKey(key_size, 3)
2224                                            .Padding(KM_PAD_RSA_OAEP)
2225                                            .Digest(KM_DIGEST_SHA_2_224)));
2226     string message = "Hello World!";
2227     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2228     EXPECT_EQ(key_size / 8, ciphertext.size());
2229 
2230     string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2231     EXPECT_EQ(message, plaintext);
2232 
2233     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2234         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2235 }
2236 
TEST_P(EncryptionOperationsTest,RsaOaepInvalidDigest)2237 TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2238     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2239                                            .RsaEncryptionKey(512, 3)
2240                                            .Padding(KM_PAD_RSA_OAEP)
2241                                            .Digest(KM_DIGEST_NONE)));
2242     string message = "Hello World!";
2243 
2244     AuthorizationSet begin_params(client_params());
2245     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2246     begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
2247     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2248 
2249     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2250         EXPECT_EQ(2, GetParam()->keymaster0_calls());
2251 }
2252 
TEST_P(EncryptionOperationsTest,RsaOaepUnauthorizedDigest)2253 TEST_P(EncryptionOperationsTest, RsaOaepUnauthorizedDigest) {
2254     if (GetParam()->minimal_digest_set())
2255         // We don't have two supported digests, so we can't try authorizing one and using another.
2256         return;
2257 
2258     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2259                                            .RsaEncryptionKey(512, 3)
2260                                            .Padding(KM_PAD_RSA_OAEP)
2261                                            .Digest(KM_DIGEST_SHA_2_256)));
2262     string message = "Hello World!";
2263     // Works because encryption is a public key operation.
2264     EncryptMessage(string(message), KM_DIGEST_SHA1, KM_PAD_RSA_OAEP);
2265 
2266     AuthorizationSet begin_params(client_params());
2267     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2268     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2269     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2270 
2271     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2272         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2273 }
2274 
TEST_P(EncryptionOperationsTest,RsaOaepDecryptWithWrongDigest)2275 TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2276     if (GetParam()->minimal_digest_set())
2277         // We don't have two supported digests, so we can't try encrypting with one and decrypting
2278         // with another.
2279         return;
2280 
2281     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2282                                            .RsaEncryptionKey(768, 3)
2283                                            .Padding(KM_PAD_RSA_OAEP)
2284                                            .Digest(KM_DIGEST_SHA_2_256)
2285                                            .Digest(KM_DIGEST_SHA_2_384)));
2286     string message = "Hello World!";
2287     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2288 
2289     string result;
2290     size_t input_consumed;
2291     AuthorizationSet begin_params(client_params());
2292     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2293     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
2294     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2295     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2296     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2297     EXPECT_EQ(0U, result.size());
2298 
2299     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2300         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2301 }
2302 
TEST_P(EncryptionOperationsTest,RsaOaepTooLarge)2303 TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2304     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2305                                            .RsaEncryptionKey(512, 3)
2306                                            .Padding(KM_PAD_RSA_OAEP)
2307                                            .Digest(KM_DIGEST_SHA1)));
2308     string message = "12345678901234567890123";
2309     string result;
2310     size_t input_consumed;
2311 
2312     AuthorizationSet begin_params(client_params());
2313     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2314     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2315     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2316     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2317     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
2318     EXPECT_EQ(0U, result.size());
2319 
2320     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2321         EXPECT_EQ(2, GetParam()->keymaster0_calls());
2322 }
2323 
TEST_P(EncryptionOperationsTest,RsaOaepCorruptedDecrypt)2324 TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
2325     size_t key_size = 768;
2326     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2327                                            .RsaEncryptionKey(768, 3)
2328                                            .Padding(KM_PAD_RSA_OAEP)
2329                                            .Digest(KM_DIGEST_SHA_2_256)));
2330     string message = "Hello World!";
2331     string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2332     EXPECT_EQ(key_size / 8, ciphertext.size());
2333 
2334     // Corrupt the ciphertext
2335     ciphertext[key_size / 8 / 2]++;
2336 
2337     string result;
2338     size_t input_consumed;
2339     AuthorizationSet begin_params(client_params());
2340     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2341     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
2342     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2343     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2344     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2345     EXPECT_EQ(0U, result.size());
2346 
2347     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2348         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2349 }
2350 
TEST_P(EncryptionOperationsTest,RsaPkcs1Success)2351 TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2352     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2353                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2354     string message = "Hello World!";
2355     string ciphertext1 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2356     EXPECT_EQ(512U / 8, ciphertext1.size());
2357 
2358     string ciphertext2 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2359     EXPECT_EQ(512U / 8, ciphertext2.size());
2360 
2361     // PKCS1 v1.5 randomizes padding so every result should be different.
2362     EXPECT_NE(ciphertext1, ciphertext2);
2363 
2364     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2365         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2366 }
2367 
TEST_P(EncryptionOperationsTest,RsaPkcs1RoundTrip)2368 TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
2369     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2370                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2371     string message = "Hello World!";
2372     string ciphertext = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2373     EXPECT_EQ(512U / 8, ciphertext.size());
2374 
2375     string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2376     EXPECT_EQ(message, plaintext);
2377 
2378     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2379         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2380 }
2381 
TEST_P(EncryptionOperationsTest,RsaRoundTripAllCombinations)2382 TEST_P(EncryptionOperationsTest, RsaRoundTripAllCombinations) {
2383     size_t key_size = 2048;
2384     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2385                                            .RsaEncryptionKey(key_size, 3)
2386                                            .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
2387                                            .Padding(KM_PAD_RSA_OAEP)
2388                                            .Digest(KM_DIGEST_NONE)
2389                                            .Digest(KM_DIGEST_MD5)
2390                                            .Digest(KM_DIGEST_SHA1)
2391                                            .Digest(KM_DIGEST_SHA_2_224)
2392                                            .Digest(KM_DIGEST_SHA_2_256)
2393                                            .Digest(KM_DIGEST_SHA_2_384)
2394                                            .Digest(KM_DIGEST_SHA_2_512)));
2395 
2396     string message = "Hello World!";
2397 
2398     keymaster_padding_t padding_modes[] = {KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
2399     keymaster_digest_t digests[] = {
2400         KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
2401         KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
2402     };
2403 
2404     for (auto padding : padding_modes)
2405         for (auto digest : digests) {
2406             if (padding == KM_PAD_RSA_OAEP && digest == KM_DIGEST_NONE)
2407                 // OAEP requires a digest.
2408                 continue;
2409 
2410             string ciphertext = EncryptMessage(message, digest, padding);
2411             EXPECT_EQ(key_size / 8, ciphertext.size());
2412 
2413             string plaintext = DecryptMessage(ciphertext, digest, padding);
2414             EXPECT_EQ(message, plaintext);
2415         }
2416 
2417     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2418         EXPECT_EQ(40, GetParam()->keymaster0_calls());
2419 }
2420 
TEST_P(EncryptionOperationsTest,RsaPkcs1TooLarge)2421 TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2422     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2423                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2424     string message = "123456789012345678901234567890123456789012345678901234";
2425     string result;
2426     size_t input_consumed;
2427 
2428     AuthorizationSet begin_params(client_params());
2429     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2430     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2431     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2432     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
2433     EXPECT_EQ(0U, result.size());
2434 
2435     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2436         EXPECT_EQ(2, GetParam()->keymaster0_calls());
2437 }
2438 
TEST_P(EncryptionOperationsTest,RsaPkcs1CorruptedDecrypt)2439 TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
2440     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2441                                KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2442     string message = "Hello World!";
2443     string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2444     EXPECT_EQ(512U / 8, ciphertext.size());
2445 
2446     // Corrupt the ciphertext
2447     ciphertext[512 / 8 / 2]++;
2448 
2449     string result;
2450     size_t input_consumed;
2451     AuthorizationSet begin_params(client_params());
2452     begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2453     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2454     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2455     EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2456     EXPECT_EQ(0U, result.size());
2457 
2458     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2459         EXPECT_EQ(4, GetParam()->keymaster0_calls());
2460 }
2461 
TEST_P(EncryptionOperationsTest,RsaEncryptWithSigningKey)2462 TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
2463     ASSERT_EQ(KM_ERROR_OK,
2464               GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
2465 
2466     AuthorizationSet begin_params(client_params());
2467     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2468     ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2469 
2470     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2471         EXPECT_EQ(2, GetParam()->keymaster0_calls());
2472 }
2473 
TEST_P(EncryptionOperationsTest,EcdsaEncrypt)2474 TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2475     ASSERT_EQ(KM_ERROR_OK,
2476               GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
2477     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2478     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2479 
2480     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
2481         EXPECT_EQ(3, GetParam()->keymaster0_calls());
2482 }
2483 
TEST_P(EncryptionOperationsTest,HmacEncrypt)2484 TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2485     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2486                                            .HmacKey(128)
2487                                            .Digest(KM_DIGEST_SHA_2_256)
2488                                            .Padding(KM_PAD_NONE)
2489                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2490     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2491     ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2492 
2493     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2494 }
2495 
TEST_P(EncryptionOperationsTest,AesEcbRoundTripSuccess)2496 TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2497     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2498                                            .AesEncryptionKey(128)
2499                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2500                                            .Padding(KM_PAD_NONE)));
2501     // Two-block message.
2502     string message = "12345678901234567890123456789012";
2503     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2504     EXPECT_EQ(message.size(), ciphertext1.size());
2505 
2506     string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
2507     EXPECT_EQ(message.size(), ciphertext2.size());
2508 
2509     // ECB is deterministic.
2510     EXPECT_EQ(ciphertext1, ciphertext2);
2511 
2512     string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
2513     EXPECT_EQ(message, plaintext);
2514 
2515     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2516 }
2517 
TEST_P(EncryptionOperationsTest,AesEcbNotAuthorized)2518 TEST_P(EncryptionOperationsTest, AesEcbNotAuthorized) {
2519     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2520                                            .AesEncryptionKey(128)
2521                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2522                                            .Padding(KM_PAD_NONE)));
2523     // Two-block message.
2524     string message = "12345678901234567890123456789012";
2525     AuthorizationSet begin_params(client_params());
2526     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2527     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2528     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2529 
2530     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2531 }
2532 
TEST_P(EncryptionOperationsTest,AesEcbNoPaddingWrongInputSize)2533 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2534     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2535                                            .AesEncryptionKey(128)
2536                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2537                                            .Padding(KM_PAD_NONE)));
2538     // Message is slightly shorter than two blocks.
2539     string message = "1234567890123456789012345678901";
2540 
2541     AuthorizationSet begin_params(client_params());
2542     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2543     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2544     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2545     string ciphertext;
2546     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
2547 
2548     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2549 }
2550 
TEST_P(EncryptionOperationsTest,AesEcbPkcs7Padding)2551 TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2552     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2553                                            .AesEncryptionKey(128)
2554                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2555                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2556 
2557     // Try various message lengths; all should work.
2558     for (size_t i = 0; i < 32; ++i) {
2559         string message(i, 'a');
2560         string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2561         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2562         string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
2563         EXPECT_EQ(message, plaintext);
2564     }
2565 
2566     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2567 }
2568 
TEST_P(EncryptionOperationsTest,AesEcbNoPaddingKeyWithPkcs7Padding)2569 TEST_P(EncryptionOperationsTest, AesEcbNoPaddingKeyWithPkcs7Padding) {
2570     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2571                                            .AesEncryptionKey(128)
2572                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2573                                            .Authorization(TAG_PADDING, KM_PAD_NONE)));
2574 
2575     // Try various message lengths; all should fail.
2576     for (size_t i = 0; i < 32; ++i) {
2577         AuthorizationSet begin_params(client_params());
2578         begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2579         begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2580         EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
2581                   BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2582     }
2583 
2584     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2585 }
2586 
TEST_P(EncryptionOperationsTest,AesEcbPkcs7PaddingCorrupted)2587 TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2588     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2589                                            .AesEncryptionKey(128)
2590                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2591                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2592 
2593     string message = "a";
2594     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2595     EXPECT_EQ(16U, ciphertext.size());
2596     EXPECT_NE(ciphertext, message);
2597     ++ciphertext[ciphertext.size() / 2];
2598 
2599     AuthorizationSet begin_params(client_params());
2600     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2601     begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2602     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2603     string plaintext;
2604     size_t input_consumed;
2605     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
2606     EXPECT_EQ(ciphertext.size(), input_consumed);
2607     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
2608 
2609     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2610 }
2611 
TEST_P(EncryptionOperationsTest,AesCtrRoundTripSuccess)2612 TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2613     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2614                                            .AesEncryptionKey(128)
2615                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2616                                            .Padding(KM_PAD_NONE)));
2617     string message = "123";
2618     string iv1;
2619     string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
2620     EXPECT_EQ(message.size(), ciphertext1.size());
2621     EXPECT_EQ(16U, iv1.size());
2622 
2623     string iv2;
2624     string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
2625     EXPECT_EQ(message.size(), ciphertext2.size());
2626     EXPECT_EQ(16U, iv2.size());
2627 
2628     // IVs should be random, so ciphertexts should differ.
2629     EXPECT_NE(iv1, iv2);
2630     EXPECT_NE(ciphertext1, ciphertext2);
2631 
2632     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
2633     EXPECT_EQ(message, plaintext);
2634 
2635     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2636 }
2637 
TEST_P(EncryptionOperationsTest,AesCtrIncremental)2638 TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
2639     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2640                                            .AesEncryptionKey(128)
2641                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2642                                            .Padding(KM_PAD_NONE)));
2643 
2644     int increment = 15;
2645     string message(239, 'a');
2646     AuthorizationSet input_params(client_params());
2647     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2648     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2649     AuthorizationSet output_params;
2650     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2651 
2652     string ciphertext;
2653     size_t input_consumed;
2654     for (size_t i = 0; i < message.size(); i += increment)
2655         EXPECT_EQ(KM_ERROR_OK,
2656                   UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2657     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2658     EXPECT_EQ(message.size(), ciphertext.size());
2659 
2660     // Move TAG_NONCE into input_params
2661     input_params.Reinitialize(output_params);
2662     input_params.push_back(client_params());
2663     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2664     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2665     output_params.Clear();
2666 
2667     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2668     string plaintext;
2669     for (size_t i = 0; i < ciphertext.size(); i += increment)
2670         EXPECT_EQ(KM_ERROR_OK,
2671                   UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2672     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2673     EXPECT_EQ(ciphertext.size(), plaintext.size());
2674     EXPECT_EQ(message, plaintext);
2675 
2676     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2677 }
2678 
2679 struct AesCtrSp80038aTestVector {
2680     const char* key;
2681     const char* nonce;
2682     const char* plaintext;
2683     const char* ciphertext;
2684 };
2685 
2686 // These test vectors are taken from
2687 // http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2688 static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2689     // AES-128
2690     {
2691         "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2692         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2693         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2694         "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2695         "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2696     },
2697     // AES-192
2698     {
2699         "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2700         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2701         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2702         "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2703         "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2704     },
2705     // AES-256
2706     {
2707         "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2708         "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2709         "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2710         "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2711         "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2712         "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2713     },
2714 };
2715 
TEST_P(EncryptionOperationsTest,AesCtrSp80038aTestVector)2716 TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2717     for (size_t i = 0; i < 3; i++) {
2718         const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2719         const string key = hex2str(test.key);
2720         const string nonce = hex2str(test.nonce);
2721         const string plaintext = hex2str(test.plaintext);
2722         const string ciphertext = hex2str(test.ciphertext);
2723         CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2724     }
2725 
2726     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2727 }
2728 
TEST_P(EncryptionOperationsTest,AesCtrInvalidPaddingMode)2729 TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
2730     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2731                                            .AesEncryptionKey(128)
2732                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2733                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2734     AuthorizationSet begin_params(client_params());
2735     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2736     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2737     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2738 
2739     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2740 }
2741 
TEST_P(EncryptionOperationsTest,AesCtrInvalidCallerNonce)2742 TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2743     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2744                                            .AesEncryptionKey(128)
2745                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2746                                            .Authorization(TAG_CALLER_NONCE)
2747                                            .Padding(KM_PAD_NONE)));
2748 
2749     AuthorizationSet input_params(client_params());
2750     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2751     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2752     input_params.push_back(TAG_NONCE, "123", 3);
2753     EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
2754 
2755     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2756 }
2757 
TEST_P(EncryptionOperationsTest,AesCbcRoundTripSuccess)2758 TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2759     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2760                                            .AesEncryptionKey(128)
2761                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2762                                            .Padding(KM_PAD_NONE)));
2763     // Two-block message.
2764     string message = "12345678901234567890123456789012";
2765     string iv1;
2766     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2767     EXPECT_EQ(message.size(), ciphertext1.size());
2768 
2769     string iv2;
2770     string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
2771     EXPECT_EQ(message.size(), ciphertext2.size());
2772 
2773     // IVs should be random, so ciphertexts should differ.
2774     EXPECT_NE(iv1, iv2);
2775     EXPECT_NE(ciphertext1, ciphertext2);
2776 
2777     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2778     EXPECT_EQ(message, plaintext);
2779 
2780     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2781 }
2782 
TEST_P(EncryptionOperationsTest,AesCallerNonce)2783 TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2784     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2785                                            .AesEncryptionKey(128)
2786                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2787                                            .Authorization(TAG_CALLER_NONCE)
2788                                            .Padding(KM_PAD_NONE)));
2789     string message = "12345678901234567890123456789012";
2790     string iv1;
2791     // Don't specify nonce, should get a random one.
2792     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2793     EXPECT_EQ(message.size(), ciphertext1.size());
2794     EXPECT_EQ(16U, iv1.size());
2795 
2796     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2797     EXPECT_EQ(message, plaintext);
2798 
2799     // Now specify a nonce, should also work.
2800     AuthorizationSet input_params(client_params());
2801     AuthorizationSet update_params;
2802     AuthorizationSet output_params;
2803     input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2804     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2805     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2806     string ciphertext2 =
2807         ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
2808 
2809     // Decrypt with correct nonce.
2810     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2811                                &output_params);
2812     EXPECT_EQ(message, plaintext);
2813 
2814     // Now try with wrong nonce.
2815     input_params.Reinitialize(client_params());
2816     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2817     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2818     input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
2819     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2820                                &output_params);
2821     EXPECT_NE(message, plaintext);
2822 
2823     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2824 }
2825 
TEST_P(EncryptionOperationsTest,AesCallerNonceProhibited)2826 TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
2827     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2828                                            .AesEncryptionKey(128)
2829                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2830                                            .Padding(KM_PAD_NONE)));
2831 
2832     string message = "12345678901234567890123456789012";
2833     string iv1;
2834     // Don't specify nonce, should get a random one.
2835     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2836     EXPECT_EQ(message.size(), ciphertext1.size());
2837     EXPECT_EQ(16U, iv1.size());
2838 
2839     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2840     EXPECT_EQ(message, plaintext);
2841 
2842     // Now specify a nonce, should fail.
2843     AuthorizationSet input_params(client_params());
2844     AuthorizationSet update_params;
2845     AuthorizationSet output_params;
2846     input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2847     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2848     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2849 
2850     EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
2851               BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2852 
2853     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2854 }
2855 
TEST_P(EncryptionOperationsTest,AesCbcIncrementalNoPadding)2856 TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
2857     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2858                                            .AesEncryptionKey(128)
2859                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2860                                            .Padding(KM_PAD_NONE)));
2861 
2862     int increment = 15;
2863     string message(240, 'a');
2864     AuthorizationSet input_params(client_params());
2865     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2866     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2867     AuthorizationSet output_params;
2868     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2869 
2870     string ciphertext;
2871     size_t input_consumed;
2872     for (size_t i = 0; i < message.size(); i += increment)
2873         EXPECT_EQ(KM_ERROR_OK,
2874                   UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2875     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2876     EXPECT_EQ(message.size(), ciphertext.size());
2877 
2878     // Move TAG_NONCE into input_params
2879     input_params.Reinitialize(output_params);
2880     input_params.push_back(client_params());
2881     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2882     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2883     output_params.Clear();
2884 
2885     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2886     string plaintext;
2887     for (size_t i = 0; i < ciphertext.size(); i += increment)
2888         EXPECT_EQ(KM_ERROR_OK,
2889                   UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2890     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2891     EXPECT_EQ(ciphertext.size(), plaintext.size());
2892     EXPECT_EQ(message, plaintext);
2893 
2894     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2895 }
2896 
TEST_P(EncryptionOperationsTest,AesCbcPkcs7Padding)2897 TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
2898     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2899                                            .AesEncryptionKey(128)
2900                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2901                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2902 
2903     // Try various message lengths; all should work.
2904     for (size_t i = 0; i < 32; ++i) {
2905         string message(i, 'a');
2906         string iv;
2907         string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
2908         EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2909         string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
2910         EXPECT_EQ(message, plaintext);
2911     }
2912 
2913     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2914 }
2915 
TEST_P(EncryptionOperationsTest,AesGcmRoundTripSuccess)2916 TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
2917     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2918                                            .AesEncryptionKey(128)
2919                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2920                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
2921                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2922     string aad = "foobar";
2923     string message = "123456789012345678901234567890123456";
2924     AuthorizationSet begin_params(client_params());
2925     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2926     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2927     begin_params.push_back(TAG_MAC_LENGTH, 128);
2928 
2929     AuthorizationSet update_params;
2930     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2931 
2932     // Encrypt
2933     AuthorizationSet begin_out_params;
2934     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2935     string ciphertext;
2936     size_t input_consumed;
2937     AuthorizationSet update_out_params;
2938     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2939                                            &input_consumed));
2940     EXPECT_EQ(message.size(), input_consumed);
2941     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2942 
2943     // Grab nonce
2944     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2945     begin_params.push_back(begin_out_params);
2946 
2947     // Decrypt.
2948     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2949     string plaintext;
2950     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2951                                            &plaintext, &input_consumed));
2952     EXPECT_EQ(ciphertext.size(), input_consumed);
2953     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2954 
2955     EXPECT_EQ(message, plaintext);
2956     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2957 }
2958 
TEST_P(EncryptionOperationsTest,AesGcmTooShortTag)2959 TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
2960     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2961                                            .AesEncryptionKey(128)
2962                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2963                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
2964                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2965     string aad = "foobar";
2966     string message = "123456789012345678901234567890123456";
2967     AuthorizationSet begin_params(client_params());
2968     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2969     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2970     begin_params.push_back(TAG_MAC_LENGTH, 96);
2971 
2972     AuthorizationSet update_params;
2973     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2974 
2975     AuthorizationSet begin_out_params;
2976     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
2977               BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2978 
2979     EXPECT_EQ(0, GetParam()->keymaster0_calls());
2980 }
2981 
TEST_P(EncryptionOperationsTest,AesGcmTooShortTagOnDecrypt)2982 TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
2983     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2984                                            .AesEncryptionKey(128)
2985                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2986                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
2987                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2988     string aad = "foobar";
2989     string message = "123456789012345678901234567890123456";
2990     AuthorizationSet begin_params(client_params());
2991     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2992     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2993     begin_params.push_back(TAG_MAC_LENGTH, 128);
2994 
2995     AuthorizationSet update_params;
2996     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2997 
2998     // Encrypt
2999     AuthorizationSet begin_out_params;
3000     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3001     string ciphertext;
3002     size_t input_consumed;
3003     AuthorizationSet update_out_params;
3004     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3005                                            &input_consumed));
3006     EXPECT_EQ(message.size(), input_consumed);
3007     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3008 
3009     // Grab nonce
3010     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3011     begin_params.Reinitialize(client_params());
3012     begin_params.push_back(begin_out_params);
3013     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3014     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3015     begin_params.push_back(TAG_MAC_LENGTH, 96);
3016 
3017     // Decrypt.
3018     EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3019 
3020     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3021 }
3022 
TEST_P(EncryptionOperationsTest,AesGcmCorruptKey)3023 TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3024     uint8_t nonce[] = {
3025         0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3026     };
3027     uint8_t ciphertext[] = {
3028         0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
3029         0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
3030         0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
3031         0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3032         0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3033     };
3034     string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
3035 
3036     AuthorizationSet begin_params(client_params());
3037     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3038     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3039     begin_params.push_back(TAG_MAC_LENGTH, 128);
3040     begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
3041 
3042     string plaintext;
3043     size_t input_consumed;
3044 
3045     // Import correct key and decrypt
3046     uint8_t good_key[] = {
3047         0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3048         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3049     };
3050     string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
3051     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
3052                                          .AesEncryptionKey(128)
3053                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3054                                          .Authorization(TAG_PADDING, KM_PAD_NONE)
3055                                          .Authorization(TAG_CALLER_NONCE)
3056                                          .Authorization(TAG_MIN_MAC_LENGTH, 128),
3057                                      KM_KEY_FORMAT_RAW, good_key_str));
3058     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3059     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
3060     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3061 
3062     // Import bad key and decrypt
3063     uint8_t bad_key[] = {
3064         0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3065         0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3066     };
3067     string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
3068     ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
3069                                          .AesEncryptionKey(128)
3070                                          .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3071                                          .Authorization(TAG_PADDING, KM_PAD_NONE)
3072                                          .Authorization(TAG_MIN_MAC_LENGTH, 128),
3073                                      KM_KEY_FORMAT_RAW, bad_key_str));
3074     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3075     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
3076     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3077 
3078     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3079 }
3080 
TEST_P(EncryptionOperationsTest,AesGcmAadNoData)3081 TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3082     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3083                                            .AesEncryptionKey(128)
3084                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3085                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3086                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3087     string aad = "123456789012345678";
3088     string empty_message;
3089     AuthorizationSet begin_params(client_params());
3090     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3091     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3092     begin_params.push_back(TAG_MAC_LENGTH, 128);
3093 
3094     AuthorizationSet update_params;
3095     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3096 
3097     // Encrypt
3098     AuthorizationSet begin_out_params;
3099     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3100     string ciphertext;
3101     size_t input_consumed;
3102     AuthorizationSet update_out_params;
3103     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
3104                                            &ciphertext, &input_consumed));
3105     EXPECT_EQ(0U, input_consumed);
3106     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3107 
3108     // Grab nonce
3109     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3110     begin_params.push_back(begin_out_params);
3111 
3112     // Decrypt.
3113     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3114     string plaintext;
3115     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3116                                            &plaintext, &input_consumed));
3117     EXPECT_EQ(ciphertext.size(), input_consumed);
3118     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3119 
3120     EXPECT_EQ(empty_message, plaintext);
3121     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3122 }
3123 
TEST_P(EncryptionOperationsTest,AesGcmIncremental)3124 TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
3125     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3126                                            .AesEncryptionKey(128)
3127                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3128                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3129                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3130     AuthorizationSet begin_params(client_params());
3131     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3132     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3133     begin_params.push_back(TAG_MAC_LENGTH, 128);
3134 
3135     AuthorizationSet update_params;
3136     update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
3137 
3138     // Encrypt
3139     AuthorizationSet begin_out_params;
3140     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3141     string ciphertext;
3142     size_t input_consumed;
3143     AuthorizationSet update_out_params;
3144 
3145     // Send AAD, incrementally
3146     for (int i = 0; i < 1000; ++i) {
3147         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
3148                                                &input_consumed));
3149         EXPECT_EQ(0U, input_consumed);
3150         EXPECT_EQ(0U, ciphertext.size());
3151     }
3152 
3153     // Now send data, incrementally, no data.
3154     AuthorizationSet empty_params;
3155     for (int i = 0; i < 1000; ++i) {
3156         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
3157                                                &input_consumed));
3158         EXPECT_EQ(1U, input_consumed);
3159     }
3160     EXPECT_EQ(1000U, ciphertext.size());
3161 
3162     // And finish.
3163     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3164     EXPECT_EQ(1016U, ciphertext.size());
3165 
3166     // Grab nonce
3167     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3168     begin_params.push_back(begin_out_params);
3169 
3170     // Decrypt.
3171     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3172     string plaintext;
3173 
3174     // Send AAD, incrementally, no data
3175     for (int i = 0; i < 1000; ++i) {
3176         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
3177                                                &input_consumed));
3178         EXPECT_EQ(0U, input_consumed);
3179         EXPECT_EQ(0U, plaintext.size());
3180     }
3181 
3182     // Now send data, incrementally.
3183     for (size_t i = 0; i < ciphertext.length(); ++i) {
3184         EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
3185                                                &update_out_params, &plaintext, &input_consumed));
3186         EXPECT_EQ(1U, input_consumed);
3187     }
3188     EXPECT_EQ(1000U, plaintext.size());
3189     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3190 
3191     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3192 }
3193 
TEST_P(EncryptionOperationsTest,AesGcmMultiPartAad)3194 TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3195     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3196                                            .AesEncryptionKey(128)
3197                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3198                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3199                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3200     string message = "123456789012345678901234567890123456";
3201     AuthorizationSet begin_params(client_params());
3202     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3203     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3204     begin_params.push_back(TAG_MAC_LENGTH, 128);
3205     AuthorizationSet begin_out_params;
3206 
3207     AuthorizationSet update_params;
3208     update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
3209 
3210     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3211 
3212     // No data, AAD only.
3213     string ciphertext;
3214     size_t input_consumed;
3215     AuthorizationSet update_out_params;
3216     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
3217                                            &ciphertext, &input_consumed));
3218     EXPECT_EQ(0U, input_consumed);
3219 
3220     // AAD and data.
3221     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3222                                            &input_consumed));
3223     EXPECT_EQ(message.size(), input_consumed);
3224     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3225 
3226     // Grab nonce.
3227     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3228     begin_params.push_back(begin_out_params);
3229 
3230     // Decrypt
3231     update_params.Clear();
3232     update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
3233 
3234     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3235     string plaintext;
3236     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3237                                            &plaintext, &input_consumed));
3238     EXPECT_EQ(ciphertext.size(), input_consumed);
3239     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3240 
3241     EXPECT_EQ(message, plaintext);
3242     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3243 }
3244 
TEST_P(EncryptionOperationsTest,AesGcmBadAad)3245 TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3246     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3247                                            .AesEncryptionKey(128)
3248                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3249                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3250                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3251     string message = "12345678901234567890123456789012";
3252     AuthorizationSet begin_params(client_params());
3253     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3254     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3255     begin_params.push_back(TAG_MAC_LENGTH, 128);
3256 
3257     AuthorizationSet update_params;
3258     update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3259 
3260     AuthorizationSet finish_params;
3261     AuthorizationSet finish_out_params;
3262 
3263     // Encrypt
3264     AuthorizationSet begin_out_params;
3265     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3266     AuthorizationSet update_out_params;
3267     string ciphertext;
3268     size_t input_consumed;
3269     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3270                                            &input_consumed));
3271     EXPECT_EQ(message.size(), input_consumed);
3272     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3273 
3274     // Grab nonce
3275     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3276     begin_params.push_back(begin_out_params);
3277 
3278     update_params.Clear();
3279     update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
3280 
3281     // Decrypt.
3282     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3283     string plaintext;
3284     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3285                                            &plaintext, &input_consumed));
3286     EXPECT_EQ(ciphertext.size(), input_consumed);
3287     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3288 
3289     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3290 }
3291 
TEST_P(EncryptionOperationsTest,AesGcmWrongNonce)3292 TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3293     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3294                                            .AesEncryptionKey(128)
3295                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3296                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3297                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3298     string message = "12345678901234567890123456789012";
3299     AuthorizationSet begin_params(client_params());
3300     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3301     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3302     begin_params.push_back(TAG_MAC_LENGTH, 128);
3303 
3304     AuthorizationSet update_params;
3305     update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3306 
3307     // Encrypt
3308     AuthorizationSet begin_out_params;
3309     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3310     AuthorizationSet update_out_params;
3311     string ciphertext;
3312     size_t input_consumed;
3313     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3314                                            &input_consumed));
3315     EXPECT_EQ(message.size(), input_consumed);
3316     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3317 
3318     begin_params.push_back(TAG_NONCE, "123456789012", 12);
3319 
3320     // Decrypt
3321     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3322     string plaintext;
3323     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3324                                            &plaintext, &input_consumed));
3325     EXPECT_EQ(ciphertext.size(), input_consumed);
3326     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3327 
3328     // With wrong nonce, should have gotten garbage plaintext.
3329     EXPECT_NE(message, plaintext);
3330     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3331 }
3332 
TEST_P(EncryptionOperationsTest,AesGcmCorruptTag)3333 TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3334     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3335                                            .AesEncryptionKey(128)
3336                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3337                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3338                                            .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3339     string aad = "foobar";
3340     string message = "123456789012345678901234567890123456";
3341     AuthorizationSet begin_params(client_params());
3342     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3343     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3344     begin_params.push_back(TAG_MAC_LENGTH, 128);
3345     AuthorizationSet begin_out_params;
3346 
3347     AuthorizationSet update_params;
3348     update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3349 
3350     // Encrypt
3351     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3352     AuthorizationSet update_out_params;
3353     string ciphertext;
3354     size_t input_consumed;
3355     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3356                                            &input_consumed));
3357     EXPECT_EQ(message.size(), input_consumed);
3358     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3359 
3360     // Corrupt tag
3361     (*ciphertext.rbegin())++;
3362 
3363     // Grab nonce.
3364     EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3365     begin_params.push_back(begin_out_params);
3366 
3367     // Decrypt.
3368     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3369     string plaintext;
3370     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3371                                            &plaintext, &input_consumed));
3372     EXPECT_EQ(ciphertext.size(), input_consumed);
3373     EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3374 
3375     EXPECT_EQ(message, plaintext);
3376     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3377 }
3378 
TEST_P(EncryptionOperationsTest,TripleDesEcbRoundTripSuccess)3379 TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
3380     auto auths = AuthorizationSetBuilder()
3381                      .TripleDesEncryptionKey(112)
3382                      .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3383                      .Padding(KM_PAD_NONE);
3384 
3385     ASSERT_EQ(KM_ERROR_OK, GenerateKey(auths));
3386     // Two-block message.
3387     string message = "1234567890123456";
3388     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3389     EXPECT_EQ(message.size(), ciphertext1.size());
3390 
3391     string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
3392     EXPECT_EQ(message.size(), ciphertext2.size());
3393 
3394     // ECB is deterministic.
3395     EXPECT_EQ(ciphertext1, ciphertext2);
3396 
3397     string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
3398     EXPECT_EQ(message, plaintext);
3399 }
3400 
TEST_P(EncryptionOperationsTest,TripleDesEcbNotAuthorized)3401 TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
3402     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3403                                            .TripleDesEncryptionKey(112)
3404                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3405                                            .Padding(KM_PAD_NONE)));
3406     // Two-block message.
3407     string message = "1234567890123456";
3408     AuthorizationSet begin_params(client_params());
3409     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3410     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3411     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3412 }
3413 
TEST_P(EncryptionOperationsTest,TripleDesEcbNoPaddingWrongInputSize)3414 TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingWrongInputSize) {
3415     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3416                                            .TripleDesEncryptionKey(112)
3417                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3418                                            .Padding(KM_PAD_NONE)));
3419     // Message is slightly shorter than two blocks.
3420     string message = "123456789012345";
3421 
3422     AuthorizationSet begin_params(client_params());
3423     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3424     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3425     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3426     string ciphertext;
3427     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
3428 }
3429 
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7Padding)3430 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
3431     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3432                                            .TripleDesEncryptionKey(112)
3433                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3434                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
3435 
3436     // Try various message lengths; all should work.
3437     for (size_t i = 0; i < 32; ++i) {
3438         string message(i, 'a');
3439         string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
3440         EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3441         string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
3442         EXPECT_EQ(message, plaintext);
3443     }
3444 }
3445 
TEST_P(EncryptionOperationsTest,TripleDesEcbNoPaddingKeyWithPkcs7Padding)3446 TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
3447     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3448                                            .TripleDesEncryptionKey(112)
3449                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3450                                            .Authorization(TAG_PADDING, KM_PAD_NONE)));
3451 
3452     // Try various message lengths; all should fail.
3453     for (size_t i = 0; i < 32; ++i) {
3454         AuthorizationSet begin_params(client_params());
3455         begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3456         begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
3457         EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
3458                   BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3459     }
3460 }
3461 
TEST_P(EncryptionOperationsTest,TripleDesEcbPkcs7PaddingCorrupted)3462 TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
3463     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3464                                            .TripleDesEncryptionKey(112)
3465                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3466                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
3467 
3468     string message = "a";
3469     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
3470     EXPECT_EQ(8U, ciphertext.size());
3471     EXPECT_NE(ciphertext, message);
3472     ++ciphertext[ciphertext.size() / 2];
3473 
3474     AuthorizationSet begin_params(client_params());
3475     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3476     begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
3477     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3478     string plaintext;
3479     size_t input_consumed;
3480     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
3481     EXPECT_EQ(ciphertext.size(), input_consumed);
3482     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
3483 }
3484 
3485 struct TripleDesTestVector {
3486     const char* name;
3487     const keymaster_purpose_t purpose;
3488     const keymaster_block_mode_t block_mode;
3489     const keymaster_padding_t padding_mode;
3490     const char* key;
3491     const char* iv;
3492     const char* input;
3493     const char* output;
3494 };
3495 
3496 // These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all of
3497 // the NIST vectors are multiples of the block size.
3498 static const TripleDesTestVector kTripleDesTestVectors[] = {
3499     {
3500         "TECBMMT2 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
3501         "ad192fd064b5579e7a4fb3c8f794f22a",  // key
3502         "",                                  // IV
3503         "13bad542f3652d67",                  // input
3504         "908e543cf2cb254f",                  // output
3505     },
3506     {
3507         "TECBMMT2 Encrypt 0 PKCS7", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_PKCS7,
3508         "ad192fd064b5579e7a4fb3c8f794f22a",  // key
3509         "",                                  // IV
3510         "13bad542f3652d6700",                // input
3511         "908e543cf2cb254fc40165289a89008c",  // output
3512     },
3513     {
3514         "TECBMMT2 Encrypt 0 PKCS7 decrypted", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_PKCS7,
3515         "ad192fd064b5579e7a4fb3c8f794f22a",  // key
3516         "",                                  // IV
3517         "908e543cf2cb254fc40165289a89008c",  // input
3518         "13bad542f3652d6700",                // output
3519     },
3520     {
3521         "TECBMMT2 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
3522         "259df16e7af804fe83b90e9bf7c7e557",  // key
3523         "",                                  // IV
3524         "a4619c433bbd6787c07c81728f9ac9fa",  // input
3525         "9e06de155c483c6bcfd834dbc8bd5830",  // output
3526     },
3527     {
3528         "TECBMMT2 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
3529         "b32ff42092024adf2076b9d3d9f19e6d",  // key
3530         "",                                  // IV
3531         "2f3f2a49bba807a5",                  // input
3532         "2249973fa135fb52",                  // output
3533     },
3534     {
3535         "TECBMMT2 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
3536         "023dfbe6621aa17cc219eae9cdecd923",  // key
3537         "",                                  // IV
3538         "54045dc71d8d565b227ec19f06fef912",  // input
3539         "9b071622181e6412de6066429401410d",  // output
3540     },
3541     {
3542         "TECBMMT3 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
3543         "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd",  // key
3544         "",                                                  // IV
3545         "329d86bdf1bc5af4",                                  // input
3546         "d946c2756d78633f",                                  // output
3547     },
3548     {
3549         "TECBMMT3 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_ECB, KM_PAD_NONE,
3550         "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49",  // key
3551         "",                                                  // IV
3552         "6b1540781b01ce1997adae102dbf3c5b",                  // input
3553         "4d0dc182d6e481ac4a3dc6ab6976ccae",                  // output
3554     },
3555     {
3556         "TECBMMT3 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
3557         "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9",  // key
3558         "",                                                  // IV
3559         "6daad94ce08acfe7",                                  // input
3560         "660e7d32dcc90e79",                                  // output
3561     },
3562     {
3563         "TECBMMT3 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_ECB, KM_PAD_NONE,
3564         "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce",  // key
3565         "",                                                  // IV
3566         "e9653a0a1f05d31b9acd12d73aa9879d",                  // input
3567         "9b2ae9d998efe62f1b592e7e1df8ff38",                  // output
3568     },
3569     {
3570         "TCBCMMT2 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
3571         "34a41a8c293176c1b30732ecfe38ae8a",  // key
3572         "f55b4855228bd0b4",                  // IV
3573         "7dd880d2a9ab411c",                  // input
3574         "c91892948b6cadb4",                  // output
3575     },
3576     {
3577         "TCBCMMT2 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
3578         "70a88fa1dfb9942fa77f40157ffef2ad",  // key
3579         "ece08ce2fdc6ce80",                  // IV
3580         "bc225304d5a3a5c9918fc5006cbc40cc",  // input
3581         "27f67dc87af7ddb4b68f63fa7c2d454a",  // output
3582     },
3583     {
3584         "TCBCMMT2 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
3585         "4ff47fda89209bda8c85f7fe80192007",  // key
3586         "d5bc4891dabe48b9",                  // IV
3587         "7e154b28c353adef",                  // input
3588         "712b961ea9a1d0af",                  // output
3589     },
3590     {
3591         "TCBCMMT2 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
3592         "464092cdbf736d38fb1fe6a12a94ae0e",  // key
3593         "5423455f00023b01",                  // IV
3594         "3f6050b74ed64416bc23d53b0469ed7a",  // input
3595         "9cbe7d1b5cdd1864c3095ba810575960",  // output
3596     },
3597     {
3598         "TCBCMMT3 Encrypt 0", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
3599         "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37",  // key
3600         "43f791134c5647ba",                                  // IV
3601         "dcc153cef81d6f24",                                  // input
3602         "92538bd8af18d3ba",                                  // output
3603     },
3604     {
3605         "TCBCMMT3 Encrypt 1", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_NONE,
3606         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3607         "c2e999cb6249023c",                                  // IV
3608         "c689aee38a301bb316da75db36f110b5",                  // input
3609         "e9afaba5ec75ea1bbe65506655bb4ecb",                  // output
3610     },
3611     {
3612         "TCBCMMT3 Encrypt 1 PKCS7 variant", KM_PURPOSE_ENCRYPT, KM_MODE_CBC, KM_PAD_PKCS7,
3613         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3614         "c2e999cb6249023c",                                  // IV
3615         "c689aee38a301bb316da75db36f110b500",                // input
3616         "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156",  // output
3617     },
3618     {
3619         "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_PKCS7,
3620         "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358",  // key
3621         "c2e999cb6249023c",                                  // IV
3622         "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156",  // input
3623         "c689aee38a301bb316da75db36f110b500",                // output
3624     },
3625     {
3626         "TCBCMMT3 Decrypt 0", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
3627         "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1",  // key
3628         "41746c7e442d3681",                                  // IV
3629         "c53a7b0ec40600fe",                                  // input
3630         "d4f00eb455de1034",                                  // output
3631     },
3632     {
3633         "TCBCMMT3 Decrypt 1", KM_PURPOSE_DECRYPT, KM_MODE_CBC, KM_PAD_NONE,
3634         "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549",  // key
3635         "3982bc02c3727d45",                                  // IV
3636         "6006f10adef52991fcc777a1238bbb65",                  // input
3637         "edae09288e9e3bc05746d872b48e3b29",                  // output
3638     },
3639 };
3640 
TEST_P(EncryptionOperationsTest,TripleDesTestVector)3641 TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
3642     for (auto& test : array_range(kTripleDesTestVectors)) {
3643         SCOPED_TRACE(test.name);
3644         CheckTripleDesTestVector(test.purpose, test.block_mode, test.padding_mode,
3645                                  hex2str(test.key), hex2str(test.iv), hex2str(test.input),
3646                                  hex2str(test.output));
3647     }
3648 }
3649 
TEST_P(EncryptionOperationsTest,TripleDesCbcRoundTripSuccess)3650 TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
3651     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3652                                            .TripleDesEncryptionKey(112)
3653                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3654                                            .Padding(KM_PAD_NONE)));
3655     // Two-block message.
3656     string message = "1234567890123456";
3657     string iv1;
3658     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
3659     EXPECT_EQ(message.size(), ciphertext1.size());
3660 
3661     string iv2;
3662     string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
3663     EXPECT_EQ(message.size(), ciphertext2.size());
3664 
3665     // IVs should be random, so ciphertexts should differ.
3666     EXPECT_NE(iv1, iv2);
3667     EXPECT_NE(ciphertext1, ciphertext2);
3668 
3669     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
3670     EXPECT_EQ(message, plaintext);
3671 
3672     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3673 }
3674 
TEST_P(EncryptionOperationsTest,TripleDesCallerIv)3675 TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
3676     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3677                                            .TripleDesEncryptionKey(112)
3678                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3679                                            .Authorization(TAG_CALLER_NONCE)
3680                                            .Padding(KM_PAD_NONE)));
3681     string message = "1234567890123456";
3682     string iv1;
3683     // Don't specify IV, should get a random one.
3684     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
3685     EXPECT_EQ(message.size(), ciphertext1.size());
3686     EXPECT_EQ(8U, iv1.size());
3687 
3688     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
3689     EXPECT_EQ(message, plaintext);
3690 
3691     // Now specify an IV, should also work.
3692     AuthorizationSet input_params(client_params());
3693     AuthorizationSet update_params;
3694     AuthorizationSet output_params;
3695     input_params.push_back(TAG_NONCE, "abcdefgh", 8);
3696     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3697     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
3698     string ciphertext2 =
3699         ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
3700 
3701     // Decrypt with correct IV.
3702     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
3703                                &output_params);
3704     EXPECT_EQ(message, plaintext);
3705 
3706     // Now try with wrong IV.
3707     input_params.Reinitialize(client_params());
3708     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3709     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
3710     input_params.push_back(TAG_NONCE, "aaaaaaaa", 8);
3711     plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
3712                                &output_params);
3713     EXPECT_NE(message, plaintext);
3714 }
3715 
TEST_P(EncryptionOperationsTest,TripleDesCallerNonceProhibited)3716 TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
3717     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3718                                            .TripleDesEncryptionKey(112)
3719                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3720                                            .Padding(KM_PAD_NONE)));
3721 
3722     string message = "12345678901234567890123456789012";
3723     string iv1;
3724     // Don't specify nonce, should get a random one.
3725     string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
3726     EXPECT_EQ(message.size(), ciphertext1.size());
3727     EXPECT_EQ(8U, iv1.size());
3728 
3729     string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
3730     EXPECT_EQ(message, plaintext);
3731 
3732     // Now specify a nonce, should fail.
3733     AuthorizationSet input_params(client_params());
3734     AuthorizationSet update_params;
3735     AuthorizationSet output_params;
3736     input_params.push_back(TAG_NONCE, "abcdefgh", 8);
3737     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3738     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
3739 
3740     EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
3741               BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
3742 }
3743 
TEST_P(EncryptionOperationsTest,TripleDesCbcNotAuthorized)3744 TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
3745     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3746                                            .TripleDesEncryptionKey(112)
3747                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
3748                                            .Padding(KM_PAD_NONE)));
3749     // Two-block message.
3750     string message = "1234567890123456";
3751     AuthorizationSet begin_params(client_params());
3752     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3753     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3754     EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3755 }
3756 
TEST_P(EncryptionOperationsTest,TripleDesCbcNoPaddingWrongInputSize)3757 TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
3758     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3759                                            .TripleDesEncryptionKey(112)
3760                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3761                                            .Padding(KM_PAD_NONE)));
3762     // Message is slightly shorter than two blocks.
3763     string message = "123456789012345";
3764 
3765     AuthorizationSet begin_params(client_params());
3766     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3767     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3768     AuthorizationSet output_params;
3769     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &output_params));
3770     string ciphertext;
3771     EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(message, "", &ciphertext));
3772 }
3773 
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7Padding)3774 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
3775     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3776                                            .TripleDesEncryptionKey(112)
3777                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3778                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
3779 
3780     // Try various message lengths; all should work.
3781     for (size_t i = 0; i < 32; ++i) {
3782         string message(i, 'a');
3783         string iv;
3784         string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
3785         EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3786         string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
3787         EXPECT_EQ(message, plaintext);
3788     }
3789 }
3790 
TEST_P(EncryptionOperationsTest,TripleDesCbcNoPaddingKeyWithPkcs7Padding)3791 TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
3792     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3793                                            .TripleDesEncryptionKey(112)
3794                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3795                                            .Authorization(TAG_PADDING, KM_PAD_NONE)));
3796 
3797     // Try various message lengths; all should fail.
3798     for (size_t i = 0; i < 32; ++i) {
3799         AuthorizationSet begin_params(client_params());
3800         begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3801         begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
3802         EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
3803                   BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3804     }
3805 }
3806 
TEST_P(EncryptionOperationsTest,TripleDesCbcPkcs7PaddingCorrupted)3807 TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
3808     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3809                                            .TripleDesEncryptionKey(112)
3810                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3811                                            .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
3812 
3813     string message = "a";
3814     string iv;
3815     string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
3816     EXPECT_EQ(8U, ciphertext.size());
3817     EXPECT_NE(ciphertext, message);
3818     ++ciphertext[ciphertext.size() / 2];
3819 
3820     AuthorizationSet begin_params(client_params());
3821     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3822     begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
3823     begin_params.push_back(TAG_NONCE, iv.data(), iv.size());
3824     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3825     string plaintext;
3826     size_t input_consumed;
3827     EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
3828     EXPECT_EQ(ciphertext.size(), input_consumed);
3829     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
3830 }
3831 
TEST_P(EncryptionOperationsTest,TripleDesCbcIncrementalNoPadding)3832 TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
3833     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3834                                            .TripleDesEncryptionKey(112)
3835                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
3836                                            .Padding(KM_PAD_NONE)));
3837 
3838     int increment = 7;
3839     string message(240, 'a');
3840     AuthorizationSet input_params(client_params());
3841     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3842     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
3843     AuthorizationSet output_params;
3844     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
3845 
3846     string ciphertext;
3847     size_t input_consumed;
3848     for (size_t i = 0; i < message.size(); i += increment)
3849         EXPECT_EQ(KM_ERROR_OK,
3850                   UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
3851     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3852     EXPECT_EQ(message.size(), ciphertext.size());
3853 
3854     // Move TAG_NONCE into input_params
3855     input_params.Reinitialize(output_params);
3856     input_params.push_back(client_params());
3857     input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
3858     input_params.push_back(TAG_PADDING, KM_PAD_NONE);
3859     output_params.Clear();
3860 
3861     EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
3862     string plaintext;
3863     for (size_t i = 0; i < ciphertext.size(); i += increment)
3864         EXPECT_EQ(KM_ERROR_OK,
3865                   UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
3866     EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3867     EXPECT_EQ(ciphertext.size(), plaintext.size());
3868     EXPECT_EQ(message, plaintext);
3869 
3870     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3871 }
3872 
3873 typedef Keymaster2Test MaxOperationsTest;
3874 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
3875 
TEST_P(MaxOperationsTest,TestLimit)3876 TEST_P(MaxOperationsTest, TestLimit) {
3877     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3878                                            .AesEncryptionKey(128)
3879                                            .EcbMode()
3880                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3881                                            .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3882 
3883     string message = "1234567890123456";
3884     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3885     string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3886     string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3887 
3888     // Fourth time should fail.
3889     AuthorizationSet begin_params(client_params());
3890     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3891     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3892     EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3893 
3894     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3895 }
3896 
TEST_P(MaxOperationsTest,TestAbort)3897 TEST_P(MaxOperationsTest, TestAbort) {
3898     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3899                                            .AesEncryptionKey(128)
3900                                            .EcbMode()
3901                                            .Authorization(TAG_PADDING, KM_PAD_NONE)
3902                                            .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3903 
3904     string message = "1234567890123456";
3905     string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3906     string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3907     string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3908 
3909     // Fourth time should fail.
3910     AuthorizationSet begin_params(client_params());
3911     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3912     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3913     EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3914 
3915     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3916 }
3917 
3918 typedef Keymaster2Test AddEntropyTest;
3919 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
3920 
TEST_P(AddEntropyTest,AddEntropy)3921 TEST_P(AddEntropyTest, AddEntropy) {
3922     // There's no obvious way to test that entropy is actually added, but we can test that the API
3923     // doesn't blow up or return an error.
3924     EXPECT_EQ(KM_ERROR_OK,
3925               device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
3926 
3927     EXPECT_EQ(0, GetParam()->keymaster0_calls());
3928 }
3929 
3930 typedef Keymaster2Test AttestationTest;
3931 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AttestationTest, test_params);
3932 
parse_cert_blob(const keymaster_blob_t & blob)3933 static X509* parse_cert_blob(const keymaster_blob_t& blob) {
3934     const uint8_t* p = blob.data;
3935     return d2i_X509(nullptr, &p, blob.data_length);
3936 }
3937 
verify_chain(const keymaster_cert_chain_t & chain)3938 static bool verify_chain(const keymaster_cert_chain_t& chain) {
3939     for (size_t i = 0; i < chain.entry_count - 1; ++i) {
3940         keymaster_blob_t& key_cert_blob = chain.entries[i];
3941         keymaster_blob_t& signing_cert_blob = chain.entries[i + 1];
3942 
3943         X509_Ptr key_cert(parse_cert_blob(key_cert_blob));
3944         X509_Ptr signing_cert(parse_cert_blob(signing_cert_blob));
3945         EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
3946         if (!key_cert.get() || !signing_cert.get())
3947             return false;
3948 
3949         EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
3950         EXPECT_TRUE(!!signing_pubkey.get());
3951         if (!signing_pubkey.get())
3952             return false;
3953 
3954         EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
3955             << "Verification of certificate " << i << " failed";
3956     }
3957 
3958     return true;
3959 }
3960 
3961 // Extract attestation record from cert. Returned object is still part of cert; don't free it
3962 // separately.
get_attestation_record(X509 * certificate)3963 static ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
3964     ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
3965     EXPECT_TRUE(!!oid.get());
3966     if (!oid.get())
3967         return nullptr;
3968 
3969     int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
3970     EXPECT_NE(-1, location);
3971     if (location == -1)
3972         return nullptr;
3973 
3974     X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
3975     EXPECT_TRUE(!!attest_rec_ext);
3976     if (!attest_rec_ext)
3977         return nullptr;
3978 
3979     ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
3980     EXPECT_TRUE(!!attest_rec);
3981     return attest_rec;
3982 }
3983 
verify_attestation_record(const string & challenge,AuthorizationSet expected_sw_enforced,AuthorizationSet expected_tee_enforced,uint32_t expected_keymaster_version,keymaster_security_level_t expected_keymaster_security_level,const keymaster_blob_t & attestation_cert)3984 static bool verify_attestation_record(const string& challenge,
3985                                       AuthorizationSet expected_sw_enforced,
3986                                       AuthorizationSet expected_tee_enforced,
3987                                       uint32_t expected_keymaster_version,
3988                                       keymaster_security_level_t expected_keymaster_security_level,
3989                                       const keymaster_blob_t& attestation_cert) {
3990 
3991     X509_Ptr cert(parse_cert_blob(attestation_cert));
3992     EXPECT_TRUE(!!cert.get());
3993     if (!cert.get())
3994         return false;
3995 
3996     ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
3997     EXPECT_TRUE(!!attest_rec);
3998     if (!attest_rec)
3999         return false;
4000 
4001     AuthorizationSet att_sw_enforced;
4002     AuthorizationSet att_tee_enforced;
4003     uint32_t att_attestation_version;
4004     uint32_t att_keymaster_version;
4005     keymaster_security_level_t att_attestation_security_level;
4006     keymaster_security_level_t att_keymaster_security_level;
4007     keymaster_blob_t att_challenge = {};
4008     keymaster_blob_t att_unique_id = {};
4009     EXPECT_EQ(KM_ERROR_OK, parse_attestation_record(
4010                                attest_rec->data, attest_rec->length, &att_attestation_version,
4011                                &att_attestation_security_level, &att_keymaster_version,
4012                                &att_keymaster_security_level, &att_challenge, &att_sw_enforced,
4013                                &att_tee_enforced, &att_unique_id));
4014 
4015     EXPECT_EQ(2U, att_attestation_version);
4016     EXPECT_EQ(KM_SECURITY_LEVEL_SOFTWARE, att_attestation_security_level);
4017     EXPECT_EQ(expected_keymaster_version, att_keymaster_version);
4018     EXPECT_EQ(expected_keymaster_security_level, att_keymaster_security_level);
4019 
4020     EXPECT_EQ(challenge.length(), att_challenge.data_length);
4021     EXPECT_EQ(0, memcmp(challenge.data(), att_challenge.data, challenge.length()));
4022 
4023     // Add TAG_USER_ID to the relevant attestation list, because user IDs are not included in
4024     // attestations, since they're meaningless off-device.
4025     uint32_t user_id;
4026     if (expected_sw_enforced.GetTagValue(TAG_USER_ID, &user_id))
4027         att_sw_enforced.push_back(TAG_USER_ID, user_id);
4028     if (expected_tee_enforced.GetTagValue(TAG_USER_ID, &user_id))
4029         att_tee_enforced.push_back(TAG_USER_ID, user_id);
4030 
4031     // Add TAG_INCLUDE_UNIQUE_ID to the relevant attestation list, because that tag is not included
4032     // in the attestation.
4033     if (expected_sw_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
4034         att_sw_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
4035     if (expected_tee_enforced.GetTagValue(TAG_INCLUDE_UNIQUE_ID))
4036         att_tee_enforced.push_back(TAG_INCLUDE_UNIQUE_ID);
4037 
4038     att_sw_enforced.Sort();
4039     expected_sw_enforced.Sort();
4040     EXPECT_EQ(expected_sw_enforced, att_sw_enforced);
4041 
4042     att_tee_enforced.Sort();
4043     expected_tee_enforced.Sort();
4044     EXPECT_EQ(expected_tee_enforced, att_tee_enforced);
4045 
4046     delete[] att_challenge.data;
4047     delete[] att_unique_id.data;
4048 
4049     return true;
4050 }
4051 
TEST_P(AttestationTest,RsaAttestation)4052 TEST_P(AttestationTest, RsaAttestation) {
4053     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
4054                                            .RsaSigningKey(256, 3)
4055                                            .Digest(KM_DIGEST_NONE)
4056                                            .Padding(KM_PAD_NONE)
4057                                            .Authorization(TAG_INCLUDE_UNIQUE_ID)));
4058 
4059     keymaster_cert_chain_t cert_chain;
4060     EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", "attest_app_id", &cert_chain));
4061     ASSERT_EQ(3U, cert_chain.entry_count);
4062     EXPECT_TRUE(verify_chain(cert_chain));
4063 
4064     uint32_t expected_keymaster_version;
4065     keymaster_security_level_t expected_keymaster_security_level;
4066     // TODO(swillden): Add a test KM1 that claims to be hardware.
4067     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
4068         expected_keymaster_version = 0;
4069         expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
4070     } else {
4071         expected_keymaster_version = 3;
4072         expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
4073     }
4074 
4075     EXPECT_TRUE(verify_attestation_record(
4076         "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
4077         expected_keymaster_security_level, cert_chain.entries[0]));
4078 
4079     keymaster_free_cert_chain(&cert_chain);
4080 }
4081 
TEST_P(AttestationTest,EcAttestation)4082 TEST_P(AttestationTest, EcAttestation) {
4083     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
4084                                KM_DIGEST_SHA_2_256)));
4085 
4086     uint32_t expected_keymaster_version;
4087     keymaster_security_level_t expected_keymaster_security_level;
4088     // TODO(swillden): Add a test KM1 that claims to be hardware.
4089     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
4090         expected_keymaster_version = 0;
4091         expected_keymaster_security_level = KM_SECURITY_LEVEL_TRUSTED_ENVIRONMENT;
4092     } else {
4093         expected_keymaster_version = 3;
4094         expected_keymaster_security_level = KM_SECURITY_LEVEL_SOFTWARE;
4095     }
4096 
4097     keymaster_cert_chain_t cert_chain;
4098     EXPECT_EQ(KM_ERROR_OK, AttestKey("challenge", "attest_app_id", &cert_chain));
4099     ASSERT_EQ(3U, cert_chain.entry_count);
4100     EXPECT_TRUE(verify_chain(cert_chain));
4101     EXPECT_TRUE(verify_attestation_record(
4102         "challenge", sw_enforced(), hw_enforced(), expected_keymaster_version,
4103         expected_keymaster_security_level, cert_chain.entries[0]));
4104 
4105     keymaster_free_cert_chain(&cert_chain);
4106 }
4107 
4108 typedef Keymaster2Test KeyUpgradeTest;
4109 INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, KeyUpgradeTest, test_params);
4110 
TEST_P(KeyUpgradeTest,AesVersionUpgrade)4111 TEST_P(KeyUpgradeTest, AesVersionUpgrade) {
4112     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4113 
4114     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
4115                                            .AesEncryptionKey(128)
4116                                            .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
4117                                            .Padding(KM_PAD_NONE)));
4118 
4119     // Key should operate fine.
4120     string message = "1234567890123456";
4121     string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
4122     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
4123 
4124     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
4125     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
4126     AuthorizationSet begin_params(client_params());
4127     begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
4128     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
4129     if (GetParam()->is_keymaster1_hw()) {
4130         // Keymaster1 hardware can't support version binding.  The key will work regardless
4131         // of system version.  Just abort the remainder of the test.
4132         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4133         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
4134         return;
4135     }
4136     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4137 
4138     // Getting characteristics should also fail
4139     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
4140 
4141     // Upgrade key.
4142     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
4143 
4144     // Key should work again
4145     ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
4146     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_NONE));
4147 
4148     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
4149     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4150     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4151     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
4152 
4153     // Upgrade should fail
4154     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
4155 
4156     EXPECT_EQ(0, GetParam()->keymaster0_calls());
4157 }
4158 
TEST_P(KeyUpgradeTest,RsaVersionUpgrade)4159 TEST_P(KeyUpgradeTest, RsaVersionUpgrade) {
4160     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4161 
4162     ASSERT_EQ(KM_ERROR_OK,
4163               GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
4164 
4165     // Key should operate fine.
4166     string message = "12345678901234567890123456789012";
4167     string ciphertext = EncryptMessage(message, KM_PAD_NONE);
4168     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
4169 
4170     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
4171     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
4172     AuthorizationSet begin_params(client_params());
4173     begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
4174     if (GetParam()->is_keymaster1_hw()) {
4175         // Keymaster1 hardware can't support version binding.  The key will work regardless
4176         // of system version.  Just abort the remainder of the test.
4177         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4178         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
4179         return;
4180     }
4181     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4182 
4183     // Getting characteristics should also fail
4184     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
4185 
4186     // Upgrade key.
4187     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
4188 
4189     // Key should work again
4190     ciphertext = EncryptMessage(message, KM_PAD_NONE);
4191     EXPECT_EQ(message, DecryptMessage(ciphertext, KM_PAD_NONE));
4192 
4193     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
4194     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4195     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4196     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
4197 
4198     // Upgrade should fail
4199     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
4200 
4201     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
4202         EXPECT_EQ(7, GetParam()->keymaster0_calls());
4203 }
4204 
TEST_P(KeyUpgradeTest,EcVersionUpgrade)4205 TEST_P(KeyUpgradeTest, EcVersionUpgrade) {
4206     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4207 
4208     ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
4209                                KM_DIGEST_SHA_2_256)));
4210 
4211     // Key should operate fine.
4212     string message = "1234567890123456";
4213     string signature;
4214     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
4215     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
4216 
4217     // Increase patch level.  Key usage should fail with KM_ERROR_KEY_REQUIRES_UPGRADE.
4218     GetParam()->keymaster_context()->SetSystemVersion(1, 2);
4219     AuthorizationSet begin_params(client_params());
4220     begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
4221     if (GetParam()->is_keymaster1_hw()) {
4222         // Keymaster1 hardware can't support version binding.  The key will work regardless
4223         // of system version.  Just abort the remainder of the test.
4224         EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
4225         EXPECT_EQ(KM_ERROR_OK, AbortOperation());
4226         return;
4227     }
4228     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
4229 
4230     // Getting characteristics should also fail
4231     EXPECT_EQ(KM_ERROR_KEY_REQUIRES_UPGRADE, GetCharacteristics());
4232 
4233     // Upgrade key.
4234     EXPECT_EQ(KM_ERROR_OK, UpgradeKey(client_params()));
4235 
4236     // Key should work again
4237     SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
4238     VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
4239 
4240     // Decrease patch level.  Key usage should fail with KM_ERROR_INVALID_KEY_BLOB.
4241     GetParam()->keymaster_context()->SetSystemVersion(1, 1);
4242     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
4243     EXPECT_EQ(KM_ERROR_INVALID_KEY_BLOB, GetCharacteristics());
4244 
4245     // Upgrade should fail
4246     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, UpgradeKey(client_params()));
4247 
4248     if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
4249         EXPECT_EQ(7, GetParam()->keymaster0_calls());
4250 }
4251 
TEST(SoftKeymasterWrapperTest,CheckKeymaster2Device)4252 TEST(SoftKeymasterWrapperTest, CheckKeymaster2Device) {
4253     // Make a good fake device, and wrap it.
4254     SoftKeymasterDevice* good_fake(new SoftKeymasterDevice(new TestKeymasterContext));
4255 
4256     // Wrap it and check it.
4257     SoftKeymasterDevice* good_fake_wrapper(new SoftKeymasterDevice(new TestKeymasterContext));
4258     good_fake_wrapper->SetHardwareDevice(good_fake->keymaster_device());
4259     EXPECT_TRUE(good_fake_wrapper->Keymaster1DeviceIsGood());
4260 
4261     // Close and clean up wrapper and wrapped
4262     good_fake_wrapper->keymaster_device()->common.close(good_fake_wrapper->hw_device());
4263 
4264     // Make a "bad" (doesn't support all digests) device;
4265     keymaster1_device_t* sha256_only_fake = make_device_sha256_only(
4266         (new SoftKeymasterDevice(new TestKeymasterContext("256")))->keymaster_device());
4267 
4268     // Wrap it and check it.
4269     SoftKeymasterDevice* sha256_only_fake_wrapper(
4270         (new SoftKeymasterDevice(new TestKeymasterContext)));
4271     sha256_only_fake_wrapper->SetHardwareDevice(sha256_only_fake);
4272     EXPECT_FALSE(sha256_only_fake_wrapper->Keymaster1DeviceIsGood());
4273 
4274     // Close and clean up wrapper and wrapped
4275     sha256_only_fake_wrapper->keymaster_device()->common.close(
4276         sha256_only_fake_wrapper->hw_device());
4277 }
4278 
4279 class HmacKeySharingTest : public ::testing::Test {
4280   protected:
4281     using KeymasterVec = std::vector<std::unique_ptr<AndroidKeymaster>>;
4282     using ParamsVec = std::vector<HmacSharingParameters>;
4283     using ByteString = std::basic_string<uint8_t>;
4284     using NonceVec = std::vector<ByteString>;
4285     using ResponseVec = std::vector<ComputeSharedHmacResponse>;
4286 
CreateKeymasters(size_t count)4287     KeymasterVec CreateKeymasters(size_t count) {
4288         KeymasterVec keymasters;
4289         for (size_t i = 0; i < count; ++i) {
4290             keymasters.push_back(make_unique<AndroidKeymaster>(new TestKeymasterContext, 16));
4291         }
4292         return keymasters;
4293     }
4294 
GetHmacSharingParameters(const KeymasterVec & keymasters)4295     ParamsVec GetHmacSharingParameters(const KeymasterVec& keymasters) {
4296         ParamsVec paramsVec;
4297         for (auto& keymaster : keymasters) {
4298             auto result = keymaster->GetHmacSharingParameters();
4299             EXPECT_EQ(KM_ERROR_OK, result.error);
4300             if (result.error == KM_ERROR_OK) paramsVec.push_back(move(result.params));
4301         }
4302         return paramsVec;
4303     }
4304 
ToByteString(const uint8_t (& a)[N])4305     template <size_t N> ByteString ToByteString(const uint8_t (&a)[N]) { return ByteString(a, N); }
4306 
ToByteString(const keymaster_blob_t & b)4307     ByteString ToByteString(const keymaster_blob_t& b) { return ByteString(b.data, b.data_length); }
4308 
CopyNonces(const ParamsVec & paramsVec)4309     NonceVec CopyNonces(const ParamsVec& paramsVec) {
4310         NonceVec nonces;
4311         for (auto& param : paramsVec) {
4312             nonces.push_back(ToByteString(param.nonce));
4313         }
4314         return nonces;
4315     }
4316 
ComputeSharedHmac(const KeymasterVec & keymasters,const ParamsVec & paramsVec)4317     ResponseVec ComputeSharedHmac(const KeymasterVec& keymasters, const ParamsVec& paramsVec) {
4318         ComputeSharedHmacRequest req;
4319         req.params_array.params_array = const_cast<HmacSharingParameters*>(paramsVec.data());
4320         auto prevent_deletion_of_paramsVec_data =
4321             finally([&]() { req.params_array.params_array = nullptr; });
4322         req.params_array.num_params = paramsVec.size();
4323 
4324         ResponseVec responses;
4325         for (auto& keymaster : keymasters) {
4326             responses.push_back(keymaster->ComputeSharedHmac(req));
4327         }
4328 
4329         return responses;
4330     }
4331 
VerifyResponses(const ByteString & expected,const ResponseVec & responses)4332     bool VerifyResponses(const ByteString& expected, const ResponseVec& responses) {
4333         for (auto& response : responses) {
4334             EXPECT_EQ(KM_ERROR_OK, response.error);
4335             auto this_sharing_check = ToByteString(response.sharing_check);
4336             EXPECT_EQ(expected, this_sharing_check) << "Sharing check values should match.";
4337             if (response.error != KM_ERROR_OK || expected != this_sharing_check) {
4338                 return false;
4339             }
4340         }
4341         return true;
4342     }
4343 };
4344 
TEST_F(HmacKeySharingTest,GetParametersIdempotency)4345 TEST_F(HmacKeySharingTest, GetParametersIdempotency) {
4346     AndroidKeymaster keymaster(new TestKeymasterContext, 16);
4347 
4348     ParamsVec paramsVec;
4349 
4350     auto result1 = keymaster.GetHmacSharingParameters();
4351     EXPECT_EQ(KM_ERROR_OK, result1.error);
4352     paramsVec.push_back(std::move(result1.params));
4353 
4354     auto result2 = keymaster.GetHmacSharingParameters();
4355     EXPECT_EQ(KM_ERROR_OK, result2.error);
4356     paramsVec.push_back(std::move(result2.params));
4357 
4358     ASSERT_EQ(ToByteString(paramsVec[0].seed), ToByteString(paramsVec[1].seed))
4359         << "A given keymaster should always return the same seed.";
4360     EXPECT_EQ(ToByteString(paramsVec[0].nonce), ToByteString(paramsVec[1].nonce))
4361         << "A given keymaster should always return the same nonce until restart.";
4362 }
4363 
TEST_F(HmacKeySharingTest,ComputeSharedHmac)4364 TEST_F(HmacKeySharingTest, ComputeSharedHmac) {
4365     // ComputeSharedHmac should work with any number of participants; we just test 1 through 4.
4366     for (size_t keymaster_count = 1; keymaster_count <= 4; ++keymaster_count) {
4367         SCOPED_TRACE(testing::Message() << keymaster_count << " keymaster instances");
4368 
4369         auto keymasters = CreateKeymasters(keymaster_count);
4370         auto params = GetHmacSharingParameters(keymasters);
4371         ASSERT_EQ(keymaster_count, params.size())
4372             << "One or more keymasters failed to provide parameters.";
4373 
4374         auto nonces = CopyNonces(params);
4375         EXPECT_EQ(keymaster_count, nonces.size()) << "We should have a nonce per keymaster.";
4376         std::sort(nonces.begin(), nonces.end());
4377         std::unique(nonces.begin(), nonces.end());
4378         EXPECT_EQ(keymaster_count, nonces.size()) << "Nonces should all be unique.";
4379 
4380         auto responses = ComputeSharedHmac(keymasters, params);
4381         ASSERT_EQ(keymaster_count, responses.size());
4382 
4383         ASSERT_TRUE(VerifyResponses(ToByteString(responses[0].sharing_check), responses));
4384     }
4385 }
4386 
TEST_F(HmacKeySharingTest,ComputeSharedHmacTwice)4387 TEST_F(HmacKeySharingTest, ComputeSharedHmacTwice) {
4388     for (size_t keymaster_count = 1; keymaster_count <= 4; ++keymaster_count) {
4389         SCOPED_TRACE(testing::Message() << keymaster_count << " keymaster instances");
4390 
4391         auto keymasters = CreateKeymasters(keymaster_count);
4392         auto params = GetHmacSharingParameters(keymasters);
4393         ASSERT_EQ(keymaster_count, params.size())
4394             << "One or more keymasters failed to provide parameters.";
4395 
4396         auto responses = ComputeSharedHmac(keymasters, params);
4397         ASSERT_EQ(keymaster_count, responses.size());
4398 
4399         ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
4400         ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
4401 
4402         params = GetHmacSharingParameters(keymasters);
4403         ASSERT_EQ(keymaster_count, params.size())
4404             << "One or more keymasters failed to provide parameters.";
4405         responses = ComputeSharedHmac(keymasters, params);
4406 
4407         // Verify against first check value; we should get the same one every time, because each
4408         // keymaster instance returns the same seed every time, and the same nonce until restart.
4409         ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
4410     }
4411 }
4412 
TEST_F(HmacKeySharingTest,ComputeSharedHmacCorruptNonce)4413 TEST_F(HmacKeySharingTest, ComputeSharedHmacCorruptNonce) {
4414     constexpr size_t keymaster_count = 4;
4415     auto keymasters = CreateKeymasters(keymaster_count);
4416 
4417     auto params = GetHmacSharingParameters(keymasters);
4418     ASSERT_EQ(keymaster_count, params.size())
4419         << "One or more keymasters failed to provide parameters.";
4420 
4421     // All should be well in the normal case
4422     auto responses = ComputeSharedHmac(keymasters, params);
4423     ASSERT_EQ(keymaster_count, responses.size());
4424     ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
4425     ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
4426 
4427     // Pick a random param, a random byte within the param's nonce, and a random bit within
4428     // the byte.  Flip that bit.
4429     size_t param_to_tweak = rand() % params.size();
4430     uint8_t byte_to_tweak = rand() % sizeof(params[param_to_tweak].nonce);
4431     uint8_t bit_to_tweak = rand() % 8;
4432     params[param_to_tweak].nonce[byte_to_tweak] ^= (1 << bit_to_tweak);
4433 
4434     responses = ComputeSharedHmac(keymasters, params);
4435     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, responses[param_to_tweak].error)
4436         << "Keymaster that provided tweaked response should fail to compute HMAC key";
4437     for (size_t i = 0; i < responses.size(); ++i) {
4438         if (i != param_to_tweak) {
4439             EXPECT_EQ(KM_ERROR_OK, responses[i].error) << "Others should succeed";
4440             EXPECT_NE(sharing_check_value, ToByteString(responses[i].sharing_check))
4441                 << "Others should calculate a different HMAC key, due to the tweaked nonce.";
4442         }
4443     }
4444 }
4445 
TEST_F(HmacKeySharingTest,ComputeSharedHmacCorruptSeed)4446 TEST_F(HmacKeySharingTest, ComputeSharedHmacCorruptSeed) {
4447     constexpr size_t keymaster_count = 4;
4448     auto keymasters = CreateKeymasters(keymaster_count);
4449 
4450     auto params = GetHmacSharingParameters(keymasters);
4451     ASSERT_EQ(keymaster_count, params.size())
4452         << "One or more keymasters failed to provide parameters.";
4453 
4454     // All should be well in the normal case
4455     auto responses = ComputeSharedHmac(keymasters, params);
4456     ASSERT_EQ(keymaster_count, responses.size());
4457     ByteString sharing_check_value = ToByteString(responses[0].sharing_check);
4458     ASSERT_TRUE(VerifyResponses(sharing_check_value, responses));
4459 
4460     // Pick a random param and modify the seed.
4461     auto param_to_tweak = rand() & params.size();
4462     constexpr uint8_t wrong_seed_value[] = {0xF, 0x0, 0x0};
4463     params[param_to_tweak].SetSeed({wrong_seed_value, sizeof(wrong_seed_value)});
4464     auto prevent_deletion_of_wrong_seed =
4465         finally([&]() { params[param_to_tweak].seed.data = nullptr; });
4466 
4467     responses = ComputeSharedHmac(keymasters, params);
4468     EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, responses[param_to_tweak].error)
4469         << "Keymaster that provided tweaked response should fail to compute HMAC key";
4470     for (size_t i = 0; i < responses.size(); ++i) {
4471         if (i != param_to_tweak) {
4472             EXPECT_EQ(KM_ERROR_OK, responses[i].error) << "Others should succeed";
4473             EXPECT_NE(sharing_check_value, ToByteString(responses[i].sharing_check))
4474                 << "Others should calculate a different HMAC key, due to the tweaked seed.";
4475         }
4476     }
4477 }
4478 
4479 }  // namespace test
4480 }  // namespace keymaster
4481