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