android_keymaster_test.cpp revision fc3cafd487e69c84d83444e1d129d0ab131c4e3d
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 <string>
19#include <vector>
20
21#include <openssl/evp.h>
22#include <openssl/x509.h>
23
24#include <hardware/keymaster0.h>
25#include <keymaster/key_factory.h>
26#include <keymaster/soft_keymaster_context.h>
27#include <keymaster/soft_keymaster_device.h>
28#include <keymaster/softkeymaster.h>
29
30#include "android_keymaster_test_utils.h"
31#include "attestation_record.h"
32#include "keymaster0_engine.h"
33#include "openssl_utils.h"
34
35using std::ifstream;
36using std::istreambuf_iterator;
37using std::ofstream;
38using std::string;
39using std::unique_ptr;
40using std::vector;
41
42extern "C" {
43int __android_log_print(int prio, const char* tag, const char* fmt);
44int __android_log_print(int prio, const char* tag, const char* fmt) {
45    (void)prio, (void)tag, (void)fmt;
46    return 0;
47}
48}  // extern "C"
49
50namespace keymaster {
51namespace test {
52
53StdoutLogger logger;
54
55template <typename T> vector<T> make_vector(const T* array, size_t len) {
56    return vector<T>(array, array + len);
57}
58
59/**
60 * KeymasterEnforcement class for use in testing.  It's permissive in the sense that it doesn't
61 * check cryptoperiods, but restrictive in the sense that the clock never advances (so rate-limited
62 * keys will only work once).
63 */
64class TestKeymasterEnforcement : public KeymasterEnforcement {
65  public:
66    TestKeymasterEnforcement() : KeymasterEnforcement(3, 3) {}
67
68    virtual bool activation_date_valid(uint64_t /* activation_date */) const { return true; }
69    virtual bool expiration_date_passed(uint64_t /* expiration_date */) const { return false; }
70    virtual bool auth_token_timed_out(const hw_auth_token_t& /* token */,
71                                      uint32_t /* timeout */) const {
72        return false;
73    }
74    virtual uint32_t get_current_time() const { return 0; }
75    virtual bool ValidateTokenSignature(const hw_auth_token_t& /* token */) const { return true; }
76};
77
78/**
79 * Variant of SoftKeymasterContext that provides a TestKeymasterEnforcement.
80 */
81class TestKeymasterContext : public SoftKeymasterContext {
82  public:
83    TestKeymasterContext() {}
84    TestKeymasterContext(const string& root_of_trust) : SoftKeymasterContext(root_of_trust) {}
85
86    KeymasterEnforcement* enforcement_policy() override { return &test_policy_; }
87
88  private:
89    TestKeymasterEnforcement test_policy_;
90};
91
92/**
93 * Test instance creator that builds a pure software keymaster1 implementations.
94 */
95class SoftKeymasterTestInstanceCreator : public Keymaster2TestInstanceCreator {
96  public:
97    keymaster2_device_t* CreateDevice() const override {
98        std::cerr << "Creating software-only device" << std::endl;
99        SoftKeymasterDevice* device = new SoftKeymasterDevice(new TestKeymasterContext);
100        return device->keymaster2_device();
101    }
102
103    bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
104    int keymaster0_calls() const override { return 0; }
105};
106
107/**
108 * Test instance creator that builds keymaster1 instances which wrap a faked hardware keymaster0
109 * instance, with or without EC support.
110 */
111class Keymaster0AdapterTestInstanceCreator : public Keymaster2TestInstanceCreator {
112  public:
113    Keymaster0AdapterTestInstanceCreator(bool support_ec) : support_ec_(support_ec) {}
114
115    keymaster2_device_t* CreateDevice() const {
116        std::cerr << "Creating keymaster0-backed device (with ec: " << std::boolalpha << support_ec_
117                  << ")." << std::endl;
118        hw_device_t* softkeymaster_device;
119        EXPECT_EQ(0, openssl_open(&softkeymaster_module.common, KEYSTORE_KEYMASTER,
120                                  &softkeymaster_device));
121        // Make the software device pretend to be hardware
122        keymaster0_device_t* keymaster0_device =
123            reinterpret_cast<keymaster0_device_t*>(softkeymaster_device);
124        keymaster0_device->flags &= ~KEYMASTER_SOFTWARE_ONLY;
125
126        if (!support_ec_) {
127            // Make the software device pretend not to support EC
128            keymaster0_device->flags &= ~KEYMASTER_SUPPORTS_EC;
129        }
130
131        counting_keymaster0_device_ = new Keymaster0CountingWrapper(keymaster0_device);
132
133        SoftKeymasterDevice* keymaster = new SoftKeymasterDevice(new TestKeymasterContext);
134        keymaster->SetHardwareDevice(counting_keymaster0_device_);
135        return keymaster->keymaster2_device();
136    }
137
138    bool algorithm_in_km0_hardware(keymaster_algorithm_t algorithm) const override {
139        switch (algorithm) {
140        case KM_ALGORITHM_RSA:
141            return true;
142        case KM_ALGORITHM_EC:
143            return support_ec_;
144        default:
145            return false;
146        }
147    }
148    int keymaster0_calls() const override { return counting_keymaster0_device_->count(); }
149
150  private:
151    mutable Keymaster0CountingWrapper* counting_keymaster0_device_;
152    bool support_ec_;
153};
154
155/**
156 * Test instance creator that builds a SoftKeymasterDevice which wraps a fake hardware keymaster1
157 * instance, with minimal digest support.
158 */
159class Sha256OnlyKeymaster1TestInstanceCreator : public Keymaster2TestInstanceCreator {
160    keymaster2_device_t* CreateDevice() const {
161        std::cerr << "Creating keymaster1-backed device that supports only SHA256";
162
163        // fake_device doesn't leak because device (below) takes ownership of it.
164        keymaster1_device_t* fake_device = make_device_sha256_only(
165            (new SoftKeymasterDevice(new TestKeymasterContext("PseudoHW")))->keymaster_device());
166
167        // device doesn't leak; it's cleaned up by device->keymaster_device()->common.close().
168        SoftKeymasterDevice* device = new SoftKeymasterDevice(new TestKeymasterContext);
169        device->SetHardwareDevice(fake_device);
170
171        return device->keymaster2_device();
172    }
173
174    bool algorithm_in_km0_hardware(keymaster_algorithm_t) const override { return false; }
175    int keymaster0_calls() const override { return 0; }
176    int minimal_digest_set() const override { return true; }
177};
178
179static auto test_params = testing::Values(
180    InstanceCreatorPtr(new SoftKeymasterTestInstanceCreator),
181    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
182    InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */)),
183    InstanceCreatorPtr(new Sha256OnlyKeymaster1TestInstanceCreator));
184
185class NewKeyGeneration : public Keymaster2Test {
186  protected:
187    void CheckBaseParams() {
188        AuthorizationSet auths = sw_enforced();
189        EXPECT_GT(auths.SerializedSize(), 12U);
190
191        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_SIGN));
192        EXPECT_TRUE(contains(auths, TAG_PURPOSE, KM_PURPOSE_VERIFY));
193        EXPECT_TRUE(contains(auths, TAG_USER_ID, 7));
194        EXPECT_TRUE(contains(auths, TAG_USER_AUTH_TYPE, HW_AUTH_PASSWORD));
195        EXPECT_TRUE(contains(auths, TAG_AUTH_TIMEOUT, 300));
196
197        // Verify that App ID, App data and ROT are NOT included.
198        EXPECT_FALSE(contains(auths, TAG_ROOT_OF_TRUST));
199        EXPECT_FALSE(contains(auths, TAG_APPLICATION_ID));
200        EXPECT_FALSE(contains(auths, TAG_APPLICATION_DATA));
201
202        // Just for giggles, check that some unexpected tags/values are NOT present.
203        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_ENCRYPT));
204        EXPECT_FALSE(contains(auths, TAG_PURPOSE, KM_PURPOSE_DECRYPT));
205        EXPECT_FALSE(contains(auths, TAG_AUTH_TIMEOUT, 301));
206
207        // Now check that unspecified, defaulted tags are correct.
208        EXPECT_TRUE(contains(auths, KM_TAG_CREATION_DATETIME));
209    }
210};
211INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, NewKeyGeneration, test_params);
212
213TEST_P(NewKeyGeneration, Rsa) {
214    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
215                                           .RsaSigningKey(256, 3)
216                                           .Digest(KM_DIGEST_NONE)
217                                           .Padding(KM_PAD_NONE)));
218    CheckBaseParams();
219
220    // Check specified tags are all present, and in the right set.
221    AuthorizationSet crypto_params;
222    AuthorizationSet non_crypto_params;
223    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA)) {
224        EXPECT_NE(0U, hw_enforced().size());
225        EXPECT_NE(0U, sw_enforced().size());
226        crypto_params.push_back(hw_enforced());
227        non_crypto_params.push_back(sw_enforced());
228    } else {
229        EXPECT_EQ(0U, hw_enforced().size());
230        EXPECT_NE(0U, sw_enforced().size());
231        crypto_params.push_back(sw_enforced());
232    }
233
234    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
235    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_RSA));
236    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 256));
237    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 256));
238    EXPECT_TRUE(contains(crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
239    EXPECT_FALSE(contains(non_crypto_params, TAG_RSA_PUBLIC_EXPONENT, 3));
240
241    EXPECT_EQ(KM_ERROR_OK, DeleteKey());
242
243    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
244        EXPECT_EQ(2, GetParam()->keymaster0_calls());
245}
246
247TEST_P(NewKeyGeneration, RsaDefaultSize) {
248    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
249              GenerateKey(AuthorizationSetBuilder()
250                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_RSA)
251                              .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3)
252                              .SigningKey()));
253
254    EXPECT_EQ(0, GetParam()->keymaster0_calls());
255}
256
257TEST_P(NewKeyGeneration, Ecdsa) {
258    ASSERT_EQ(KM_ERROR_OK,
259              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
260    CheckBaseParams();
261
262    // Check specified tags are all present, and in the right set.
263    AuthorizationSet crypto_params;
264    AuthorizationSet non_crypto_params;
265    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC)) {
266        EXPECT_NE(0U, hw_enforced().size());
267        EXPECT_NE(0U, sw_enforced().size());
268        crypto_params.push_back(hw_enforced());
269        non_crypto_params.push_back(sw_enforced());
270    } else {
271        EXPECT_EQ(0U, hw_enforced().size());
272        EXPECT_NE(0U, sw_enforced().size());
273        crypto_params.push_back(sw_enforced());
274    }
275
276    EXPECT_TRUE(contains(crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
277    EXPECT_FALSE(contains(non_crypto_params, TAG_ALGORITHM, KM_ALGORITHM_EC));
278    EXPECT_TRUE(contains(crypto_params, TAG_KEY_SIZE, 224));
279    EXPECT_FALSE(contains(non_crypto_params, TAG_KEY_SIZE, 224));
280
281    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
282        EXPECT_EQ(1, GetParam()->keymaster0_calls());
283}
284
285TEST_P(NewKeyGeneration, EcdsaDefaultSize) {
286    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_SIZE,
287              GenerateKey(AuthorizationSetBuilder()
288                              .Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC)
289                              .SigningKey()
290                              .Digest(KM_DIGEST_NONE)));
291
292    EXPECT_EQ(0, GetParam()->keymaster0_calls());
293}
294
295TEST_P(NewKeyGeneration, EcdsaInvalidSize) {
296    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
297        ASSERT_EQ(
298            KM_ERROR_UNKNOWN_ERROR,
299            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
300    else
301        ASSERT_EQ(
302            KM_ERROR_UNSUPPORTED_KEY_SIZE,
303            GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(190).Digest(KM_DIGEST_NONE)));
304
305    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
306        EXPECT_EQ(1, GetParam()->keymaster0_calls());
307}
308
309TEST_P(NewKeyGeneration, EcdsaAllValidSizes) {
310    size_t valid_sizes[] = {224, 256, 384, 521};
311    for (size_t size : valid_sizes) {
312        EXPECT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(size).Digest(
313                                   KM_DIGEST_NONE)))
314            << "Failed to generate size: " << size;
315    }
316
317    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
318        EXPECT_EQ(4, GetParam()->keymaster0_calls());
319}
320
321TEST_P(NewKeyGeneration, HmacSha256) {
322    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
323                                           .HmacKey(128)
324                                           .Digest(KM_DIGEST_SHA_2_256)
325                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
326
327    EXPECT_EQ(0, GetParam()->keymaster0_calls());
328}
329
330TEST_P(NewKeyGeneration, HmacMultipleDigests) {
331    ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
332              GenerateKey(AuthorizationSetBuilder()
333                              .HmacKey(128)
334                              .Digest(KM_DIGEST_SHA1)
335                              .Digest(KM_DIGEST_SHA_2_256)
336                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
337
338    EXPECT_EQ(0, GetParam()->keymaster0_calls());
339}
340
341TEST_P(NewKeyGeneration, HmacDigestNone) {
342    ASSERT_EQ(KM_ERROR_UNSUPPORTED_DIGEST,
343              GenerateKey(AuthorizationSetBuilder()
344                              .HmacKey(128)
345                              .Digest(KM_DIGEST_NONE)
346                              .Authorization(TAG_MIN_MAC_LENGTH, 128)));
347
348    EXPECT_EQ(0, GetParam()->keymaster0_calls());
349}
350
351TEST_P(NewKeyGeneration, HmacSha256TooShortMacLength) {
352    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
353              GenerateKey(AuthorizationSetBuilder()
354                              .HmacKey(128)
355                              .Digest(KM_DIGEST_SHA_2_256)
356                              .Authorization(TAG_MIN_MAC_LENGTH, 48)));
357
358    EXPECT_EQ(0, GetParam()->keymaster0_calls());
359}
360
361TEST_P(NewKeyGeneration, HmacSha256NonIntegralOctetMacLength) {
362    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
363              GenerateKey(AuthorizationSetBuilder()
364                              .HmacKey(128)
365                              .Digest(KM_DIGEST_SHA_2_256)
366                              .Authorization(TAG_MIN_MAC_LENGTH, 130)));
367
368    EXPECT_EQ(0, GetParam()->keymaster0_calls());
369}
370
371TEST_P(NewKeyGeneration, HmacSha256TooLongMacLength) {
372    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MIN_MAC_LENGTH,
373              GenerateKey(AuthorizationSetBuilder()
374                              .HmacKey(128)
375                              .Digest(KM_DIGEST_SHA_2_256)
376                              .Authorization(TAG_MIN_MAC_LENGTH, 384)));
377
378    EXPECT_EQ(0, GetParam()->keymaster0_calls());
379}
380
381typedef Keymaster2Test GetKeyCharacteristics;
382INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, GetKeyCharacteristics, test_params);
383
384TEST_P(GetKeyCharacteristics, SimpleRsa) {
385    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
386                                           .RsaSigningKey(256, 3)
387                                           .Digest(KM_DIGEST_NONE)
388                                           .Padding(KM_PAD_NONE)));
389    AuthorizationSet original(sw_enforced());
390
391    ASSERT_EQ(KM_ERROR_OK, GetCharacteristics());
392    EXPECT_EQ(original, sw_enforced());
393
394    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
395        EXPECT_EQ(1, GetParam()->keymaster0_calls());
396}
397
398typedef Keymaster2Test SigningOperationsTest;
399INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, SigningOperationsTest, test_params);
400
401TEST_P(SigningOperationsTest, RsaSuccess) {
402    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
403                                           .RsaSigningKey(256, 3)
404                                           .Digest(KM_DIGEST_NONE)
405                                           .Padding(KM_PAD_NONE)));
406    string message = "12345678901234567890123456789012";
407    string signature;
408    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
409
410    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
411        EXPECT_EQ(3, GetParam()->keymaster0_calls());
412}
413
414TEST_P(SigningOperationsTest, RsaPssSha256Success) {
415    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
416                                           .RsaSigningKey(512, 3)
417                                           .Digest(KM_DIGEST_SHA_2_256)
418                                           .Padding(KM_PAD_RSA_PSS)));
419    // Use large message, which won't work without digesting.
420    string message(1024, 'a');
421    string signature;
422    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
423
424    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
425        EXPECT_EQ(3, GetParam()->keymaster0_calls());
426}
427
428TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
429    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
430                                           .RsaSigningKey(512, 3)
431                                           .Digest(KM_DIGEST_NONE)
432                                           .Padding(KM_PAD_NONE)));
433    string message = "12345678901234567890123456789012";
434    string signature;
435
436    AuthorizationSet begin_params(client_params());
437    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
438    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
439    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
440
441    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
442        EXPECT_EQ(2, GetParam()->keymaster0_calls());
443}
444
445TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
446    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
447                                           .RsaSigningKey(512, 3)
448                                           .Digest(KM_DIGEST_SHA_2_256)
449                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
450    string message(1024, 'a');
451    string signature;
452    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
453
454    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
455        EXPECT_EQ(3, GetParam()->keymaster0_calls());
456}
457
458TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
459    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
460                                           .RsaSigningKey(512, 3)
461                                           .Digest(KM_DIGEST_NONE)
462                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
463    string message(53, 'a');
464    string signature;
465    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN);
466
467    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
468        EXPECT_EQ(3, GetParam()->keymaster0_calls());
469}
470
471TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLarge) {
472    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
473                                           .RsaSigningKey(512, 3)
474                                           .Digest(KM_DIGEST_NONE)
475                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
476    string message(54, 'a');
477
478    AuthorizationSet begin_params(client_params());
479    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
480    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
481    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
482    string result;
483    size_t input_consumed;
484    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
485    string signature;
486    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&signature));
487
488    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
489        EXPECT_EQ(2, GetParam()->keymaster0_calls());
490}
491
492TEST_P(SigningOperationsTest, RsaPssSha256TooSmallKey) {
493    // Key must be at least 10 bytes larger than hash, to provide eight bytes of random salt, so
494    // verify that nine bytes larger than hash won't work.
495    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
496                                           .RsaSigningKey(256 + 9 * 8, 3)
497                                           .Digest(KM_DIGEST_SHA_2_256)
498                                           .Padding(KM_PAD_RSA_PSS)));
499    string message(1024, 'a');
500    string signature;
501
502    AuthorizationSet begin_params(client_params());
503    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
504    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
505    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
506}
507
508TEST_P(SigningOperationsTest, RsaNoPaddingHugeData) {
509    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
510                                           .RsaSigningKey(256, 3)
511                                           .Digest(KM_DIGEST_NONE)
512                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
513    string message(64 * 1024, 'a');
514    string signature;
515    AuthorizationSet begin_params(client_params());
516    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
517    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
518    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
519    string result;
520    size_t input_consumed;
521    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
522
523    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
524        EXPECT_EQ(2, GetParam()->keymaster0_calls());
525}
526
527TEST_P(SigningOperationsTest, RsaAbort) {
528    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
529                                           .RsaSigningKey(256, 3)
530                                           .Digest(KM_DIGEST_NONE)
531                                           .Padding(KM_PAD_NONE)));
532    AuthorizationSet begin_params(client_params());
533    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
534    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
535    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
536    EXPECT_EQ(KM_ERROR_OK, AbortOperation());
537    // Another abort should fail
538    EXPECT_EQ(KM_ERROR_INVALID_OPERATION_HANDLE, AbortOperation());
539
540    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
541        EXPECT_EQ(2, GetParam()->keymaster0_calls());
542}
543
544TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
545    GenerateKey(AuthorizationSetBuilder()
546                    .RsaSigningKey(256, 3)
547                    .Digest(KM_DIGEST_SHA_2_256 /* supported digest */)
548                    .Padding(KM_PAD_PKCS7));
549    AuthorizationSet begin_params(client_params());
550    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
551    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
552
553    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
554        EXPECT_EQ(2, GetParam()->keymaster0_calls());
555}
556
557TEST_P(SigningOperationsTest, RsaNoDigest) {
558    // PSS requires a digest.
559    GenerateKey(AuthorizationSetBuilder()
560                    .RsaSigningKey(256, 3)
561                    .Digest(KM_DIGEST_NONE)
562                    .Padding(KM_PAD_RSA_PSS));
563    AuthorizationSet begin_params(client_params());
564    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
565    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
566    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_SIGN, begin_params));
567
568    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
569        EXPECT_EQ(2, GetParam()->keymaster0_calls());
570}
571
572TEST_P(SigningOperationsTest, RsaNoPadding) {
573    // Padding must be specified
574    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaKey(256, 3).SigningKey().Digest(
575                               KM_DIGEST_NONE)));
576    AuthorizationSet begin_params(client_params());
577    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
578    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PADDING_MODE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
579
580    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
581        EXPECT_EQ(2, GetParam()->keymaster0_calls());
582}
583
584TEST_P(SigningOperationsTest, RsaTooShortMessage) {
585    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
586                                           .RsaSigningKey(256, 3)
587                                           .Digest(KM_DIGEST_NONE)
588                                           .Padding(KM_PAD_NONE)));
589    string message = "1234567890123456789012345678901";
590    string signature;
591    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
592
593    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
594        EXPECT_EQ(3, GetParam()->keymaster0_calls());
595}
596
597TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
598    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
599                                           .RsaEncryptionKey(256, 3)
600                                           .Digest(KM_DIGEST_NONE)
601                                           .Padding(KM_PAD_NONE)));
602    AuthorizationSet begin_params(client_params());
603    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
604    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
605    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_SIGN, begin_params));
606
607    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
608        EXPECT_EQ(2, GetParam()->keymaster0_calls());
609}
610
611TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
612    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
613                                           .RsaSigningKey(256, 3)
614                                           .Digest(KM_DIGEST_NONE)
615                                           .Padding(KM_PAD_NONE)));
616    string message(256 / 8, static_cast<char>(0xff));
617    string signature;
618    AuthorizationSet begin_params(client_params());
619    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
620    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
621    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
622    string result;
623    size_t input_consumed;
624    ASSERT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
625    ASSERT_EQ(message.size(), input_consumed);
626    string output;
627    ASSERT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&output));
628
629    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
630        EXPECT_EQ(3, GetParam()->keymaster0_calls());
631}
632
633TEST_P(SigningOperationsTest, EcdsaSuccess) {
634    ASSERT_EQ(KM_ERROR_OK,
635              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
636    string message(224 / 8, 'a');
637    string signature;
638    SignMessage(message, &signature, KM_DIGEST_NONE);
639
640    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
641        EXPECT_EQ(3, GetParam()->keymaster0_calls());
642}
643
644TEST_P(SigningOperationsTest, EcdsaSha256Success) {
645    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
646                               KM_DIGEST_SHA_2_256)));
647    string message(1024, 'a');
648    string signature;
649    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
650
651    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
652        EXPECT_EQ(3, GetParam()->keymaster0_calls());
653}
654
655TEST_P(SigningOperationsTest, EcdsaSha384Success) {
656    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(
657                               KM_DIGEST_SHA_2_384)));
658    string message(1024, 'a');
659    string signature;
660    SignMessage(message, &signature, KM_DIGEST_SHA_2_384);
661
662    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
663        EXPECT_EQ(3, GetParam()->keymaster0_calls());
664}
665
666TEST_P(SigningOperationsTest, EcdsaNoPaddingHugeData) {
667    ASSERT_EQ(KM_ERROR_OK,
668              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
669    string message(64 * 1024, 'a');
670    string signature;
671    AuthorizationSet begin_params(client_params());
672    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
673    ASSERT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_SIGN, begin_params));
674    string result;
675    size_t input_consumed;
676    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
677
678    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
679        EXPECT_EQ(2, GetParam()->keymaster0_calls());
680}
681
682TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
683    vector<int> key_sizes = {224, 256, 384, 521};
684    vector<keymaster_digest_t> digests = {
685        KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
686        KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
687    };
688
689    for (int key_size : key_sizes) {
690        for (keymaster_digest_t digest : digests) {
691            ASSERT_EQ(
692                KM_ERROR_OK,
693                GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(key_size).Digest(digest)));
694
695            string message(1024, 'a');
696            string signature;
697            if (digest == KM_DIGEST_NONE)
698                message.resize(key_size / 8);
699            SignMessage(message, &signature, digest);
700        }
701    }
702
703    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
704        EXPECT_EQ(digests.size() * key_sizes.size() * 3,
705                  static_cast<size_t>(GetParam()->keymaster0_calls()));
706}
707
708TEST_P(SigningOperationsTest, AesEcbSign) {
709    ASSERT_EQ(KM_ERROR_OK,
710              GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128).Authorization(
711                  TAG_BLOCK_MODE, KM_MODE_ECB)));
712    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_SIGN));
713    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_VERIFY));
714
715    EXPECT_EQ(0, GetParam()->keymaster0_calls());
716}
717
718TEST_P(SigningOperationsTest, HmacSha1Success) {
719    if (GetParam()->minimal_digest_set())
720        // Can't emulate other digests for HMAC.
721        return;
722
723    GenerateKey(AuthorizationSetBuilder()
724                    .HmacKey(128)
725                    .Digest(KM_DIGEST_SHA1)
726                    .Authorization(TAG_MIN_MAC_LENGTH, 160));
727    string message = "12345678901234567890123456789012";
728    string signature;
729    MacMessage(message, &signature, 160);
730    ASSERT_EQ(20U, signature.size());
731
732    EXPECT_EQ(0, GetParam()->keymaster0_calls());
733}
734
735TEST_P(SigningOperationsTest, HmacSha224Success) {
736    if (GetParam()->minimal_digest_set())
737        // Can't emulate other digests for HMAC.
738        return;
739
740    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
741                                           .HmacKey(128)
742                                           .Digest(KM_DIGEST_SHA_2_224)
743                                           .Authorization(TAG_MIN_MAC_LENGTH, 160)));
744    string message = "12345678901234567890123456789012";
745    string signature;
746    MacMessage(message, &signature, 224);
747    ASSERT_EQ(28U, signature.size());
748
749    EXPECT_EQ(0, GetParam()->keymaster0_calls());
750}
751
752TEST_P(SigningOperationsTest, HmacSha256Success) {
753    if (GetParam()->minimal_digest_set())
754        // Can't emulate other digests for HMAC.
755        return;
756
757    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
758                                           .HmacKey(128)
759                                           .Digest(KM_DIGEST_SHA_2_256)
760                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
761    string message = "12345678901234567890123456789012";
762    string signature;
763    MacMessage(message, &signature, 256);
764    ASSERT_EQ(32U, signature.size());
765
766    EXPECT_EQ(0, GetParam()->keymaster0_calls());
767}
768
769TEST_P(SigningOperationsTest, HmacSha384Success) {
770    if (GetParam()->minimal_digest_set())
771        // Can't emulate other digests for HMAC.
772        return;
773
774    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
775                                           .HmacKey(128)
776                                           .Digest(KM_DIGEST_SHA_2_384)
777                                           .Authorization(TAG_MIN_MAC_LENGTH, 384)));
778
779    string message = "12345678901234567890123456789012";
780    string signature;
781    MacMessage(message, &signature, 384);
782    ASSERT_EQ(48U, signature.size());
783
784    EXPECT_EQ(0, GetParam()->keymaster0_calls());
785}
786
787TEST_P(SigningOperationsTest, HmacSha512Success) {
788    if (GetParam()->minimal_digest_set())
789        // Can't emulate other digests for HMAC.
790        return;
791
792    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
793                                           .HmacKey(128)
794                                           .Digest(KM_DIGEST_SHA_2_512)
795                                           .Authorization(TAG_MIN_MAC_LENGTH, 384)));
796    string message = "12345678901234567890123456789012";
797    string signature;
798    MacMessage(message, &signature, 512);
799    ASSERT_EQ(64U, signature.size());
800
801    EXPECT_EQ(0, GetParam()->keymaster0_calls());
802}
803
804TEST_P(SigningOperationsTest, HmacLengthInKey) {
805    // TODO(swillden): unified API should generate an error on key generation.
806    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
807                                           .HmacKey(128)
808                                           .Digest(KM_DIGEST_SHA_2_256)
809                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
810    string message = "12345678901234567890123456789012";
811    string signature;
812    MacMessage(message, &signature, 160);
813    ASSERT_EQ(20U, signature.size());
814
815    EXPECT_EQ(0, GetParam()->keymaster0_calls());
816}
817
818TEST_P(SigningOperationsTest, HmacRfc4231TestCase1) {
819    uint8_t key_data[] = {
820        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
821        0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
822    };
823    string message = "Hi There";
824    uint8_t sha_224_expected[] = {
825        0x89, 0x6f, 0xb1, 0x12, 0x8a, 0xbb, 0xdf, 0x19, 0x68, 0x32, 0x10, 0x7c, 0xd4, 0x9d,
826        0xf3, 0x3f, 0x47, 0xb4, 0xb1, 0x16, 0x99, 0x12, 0xba, 0x4f, 0x53, 0x68, 0x4b, 0x22,
827    };
828    uint8_t sha_256_expected[] = {
829        0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53, 0x5c, 0xa8, 0xaf,
830        0xce, 0xaf, 0x0b, 0xf1, 0x2b, 0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83,
831        0x3d, 0xa7, 0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7,
832    };
833    uint8_t sha_384_expected[] = {
834        0xaf, 0xd0, 0x39, 0x44, 0xd8, 0x48, 0x95, 0x62, 0x6b, 0x08, 0x25, 0xf4,
835        0xab, 0x46, 0x90, 0x7f, 0x15, 0xf9, 0xda, 0xdb, 0xe4, 0x10, 0x1e, 0xc6,
836        0x82, 0xaa, 0x03, 0x4c, 0x7c, 0xeb, 0xc5, 0x9c, 0xfa, 0xea, 0x9e, 0xa9,
837        0x07, 0x6e, 0xde, 0x7f, 0x4a, 0xf1, 0x52, 0xe8, 0xb2, 0xfa, 0x9c, 0xb6,
838    };
839    uint8_t sha_512_expected[] = {
840        0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0, 0xb4, 0x24, 0x1a,
841        0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2, 0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0,
842        0xb3, 0x05, 0x45, 0xe1, 0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7,
843        0x02, 0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d, 0x91, 0x4e,
844        0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20, 0x3a, 0x12, 0x68, 0x54,
845    };
846
847    string key = make_string(key_data);
848
849    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
850    if (!GetParam()->minimal_digest_set()) {
851        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
852        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
853        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
854    }
855
856    EXPECT_EQ(0, GetParam()->keymaster0_calls());
857}
858
859TEST_P(SigningOperationsTest, HmacRfc4231TestCase2) {
860    string key = "Jefe";
861    string message = "what do ya want for nothing?";
862    uint8_t sha_224_expected[] = {
863        0xa3, 0x0e, 0x01, 0x09, 0x8b, 0xc6, 0xdb, 0xbf, 0x45, 0x69, 0x0f, 0x3a, 0x7e, 0x9e,
864        0x6d, 0x0f, 0x8b, 0xbe, 0xa2, 0xa3, 0x9e, 0x61, 0x48, 0x00, 0x8f, 0xd0, 0x5e, 0x44,
865    };
866    uint8_t sha_256_expected[] = {
867        0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24,
868        0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27,
869        0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43,
870    };
871    uint8_t sha_384_expected[] = {
872        0xaf, 0x45, 0xd2, 0xe3, 0x76, 0x48, 0x40, 0x31, 0x61, 0x7f, 0x78, 0xd2,
873        0xb5, 0x8a, 0x6b, 0x1b, 0x9c, 0x7e, 0xf4, 0x64, 0xf5, 0xa0, 0x1b, 0x47,
874        0xe4, 0x2e, 0xc3, 0x73, 0x63, 0x22, 0x44, 0x5e, 0x8e, 0x22, 0x40, 0xca,
875        0x5e, 0x69, 0xe2, 0xc7, 0x8b, 0x32, 0x39, 0xec, 0xfa, 0xb2, 0x16, 0x49,
876    };
877    uint8_t sha_512_expected[] = {
878        0x16, 0x4b, 0x7a, 0x7b, 0xfc, 0xf8, 0x19, 0xe2, 0xe3, 0x95, 0xfb, 0xe7, 0x3b,
879        0x56, 0xe0, 0xa3, 0x87, 0xbd, 0x64, 0x22, 0x2e, 0x83, 0x1f, 0xd6, 0x10, 0x27,
880        0x0c, 0xd7, 0xea, 0x25, 0x05, 0x54, 0x97, 0x58, 0xbf, 0x75, 0xc0, 0x5a, 0x99,
881        0x4a, 0x6d, 0x03, 0x4f, 0x65, 0xf8, 0xf0, 0xe6, 0xfd, 0xca, 0xea, 0xb1, 0xa3,
882        0x4d, 0x4a, 0x6b, 0x4b, 0x63, 0x6e, 0x07, 0x0a, 0x38, 0xbc, 0xe7, 0x37,
883    };
884
885    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
886    if (!GetParam()->minimal_digest_set()) {
887        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
888        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
889        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
890        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
891    }
892
893    EXPECT_EQ(0, GetParam()->keymaster0_calls());
894}
895
896TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
897    string key(20, 0xaa);
898    string message(50, 0xdd);
899    uint8_t sha_224_expected[] = {
900        0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
901        0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
902    };
903    uint8_t sha_256_expected[] = {
904        0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
905        0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
906        0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
907    };
908    uint8_t sha_384_expected[] = {
909        0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
910        0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
911        0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
912        0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
913    };
914    uint8_t sha_512_expected[] = {
915        0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
916        0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
917        0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
918        0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
919        0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
920    };
921
922    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
923    if (!GetParam()->minimal_digest_set()) {
924        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
925        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
926        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
927        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
928    }
929
930    EXPECT_EQ(0, GetParam()->keymaster0_calls());
931}
932
933TEST_P(SigningOperationsTest, HmacRfc4231TestCase4) {
934    uint8_t key_data[25] = {
935        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
936        0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19,
937    };
938    string key = make_string(key_data);
939    string message(50, 0xcd);
940    uint8_t sha_224_expected[] = {
941        0x6c, 0x11, 0x50, 0x68, 0x74, 0x01, 0x3c, 0xac, 0x6a, 0x2a, 0xbc, 0x1b, 0xb3, 0x82,
942        0x62, 0x7c, 0xec, 0x6a, 0x90, 0xd8, 0x6e, 0xfc, 0x01, 0x2d, 0xe7, 0xaf, 0xec, 0x5a,
943    };
944    uint8_t sha_256_expected[] = {
945        0x82, 0x55, 0x8a, 0x38, 0x9a, 0x44, 0x3c, 0x0e, 0xa4, 0xcc, 0x81,
946        0x98, 0x99, 0xf2, 0x08, 0x3a, 0x85, 0xf0, 0xfa, 0xa3, 0xe5, 0x78,
947        0xf8, 0x07, 0x7a, 0x2e, 0x3f, 0xf4, 0x67, 0x29, 0x66, 0x5b,
948    };
949    uint8_t sha_384_expected[] = {
950        0x3e, 0x8a, 0x69, 0xb7, 0x78, 0x3c, 0x25, 0x85, 0x19, 0x33, 0xab, 0x62,
951        0x90, 0xaf, 0x6c, 0xa7, 0x7a, 0x99, 0x81, 0x48, 0x08, 0x50, 0x00, 0x9c,
952        0xc5, 0x57, 0x7c, 0x6e, 0x1f, 0x57, 0x3b, 0x4e, 0x68, 0x01, 0xdd, 0x23,
953        0xc4, 0xa7, 0xd6, 0x79, 0xcc, 0xf8, 0xa3, 0x86, 0xc6, 0x74, 0xcf, 0xfb,
954    };
955    uint8_t sha_512_expected[] = {
956        0xb0, 0xba, 0x46, 0x56, 0x37, 0x45, 0x8c, 0x69, 0x90, 0xe5, 0xa8, 0xc5, 0xf6,
957        0x1d, 0x4a, 0xf7, 0xe5, 0x76, 0xd9, 0x7f, 0xf9, 0x4b, 0x87, 0x2d, 0xe7, 0x6f,
958        0x80, 0x50, 0x36, 0x1e, 0xe3, 0xdb, 0xa9, 0x1c, 0xa5, 0xc1, 0x1a, 0xa2, 0x5e,
959        0xb4, 0xd6, 0x79, 0x27, 0x5c, 0xc5, 0x78, 0x80, 0x63, 0xa5, 0xf1, 0x97, 0x41,
960        0x12, 0x0c, 0x4f, 0x2d, 0xe2, 0xad, 0xeb, 0xeb, 0x10, 0xa2, 0x98, 0xdd,
961    };
962
963    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
964    if (!GetParam()->minimal_digest_set()) {
965        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
966        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
967        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
968        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
969    }
970
971    EXPECT_EQ(0, GetParam()->keymaster0_calls());
972}
973
974TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
975    string key(20, 0x0c);
976    string message = "Test With Truncation";
977
978    uint8_t sha_224_expected[] = {
979        0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
980        0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
981    };
982    uint8_t sha_256_expected[] = {
983        0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
984        0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
985    };
986    uint8_t sha_384_expected[] = {
987        0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
988        0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
989    };
990    uint8_t sha_512_expected[] = {
991        0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
992        0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
993    };
994
995    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
996    if (!GetParam()->minimal_digest_set()) {
997        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
998        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
999        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1000    }
1001
1002    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1003}
1004
1005TEST_P(SigningOperationsTest, HmacRfc4231TestCase6) {
1006    string key(131, 0xaa);
1007    string message = "Test Using Larger Than Block-Size Key - Hash Key First";
1008
1009    uint8_t sha_224_expected[] = {
1010        0x95, 0xe9, 0xa0, 0xdb, 0x96, 0x20, 0x95, 0xad, 0xae, 0xbe, 0x9b, 0x2d, 0x6f, 0x0d,
1011        0xbc, 0xe2, 0xd4, 0x99, 0xf1, 0x12, 0xf2, 0xd2, 0xb7, 0x27, 0x3f, 0xa6, 0x87, 0x0e,
1012    };
1013    uint8_t sha_256_expected[] = {
1014        0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26,
1015        0xaa, 0xcb, 0xf5, 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28,
1016        0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f, 0x0e, 0xe3, 0x7f, 0x54,
1017    };
1018    uint8_t sha_384_expected[] = {
1019        0x4e, 0xce, 0x08, 0x44, 0x85, 0x81, 0x3e, 0x90, 0x88, 0xd2, 0xc6, 0x3a,
1020        0x04, 0x1b, 0xc5, 0xb4, 0x4f, 0x9e, 0xf1, 0x01, 0x2a, 0x2b, 0x58, 0x8f,
1021        0x3c, 0xd1, 0x1f, 0x05, 0x03, 0x3a, 0xc4, 0xc6, 0x0c, 0x2e, 0xf6, 0xab,
1022        0x40, 0x30, 0xfe, 0x82, 0x96, 0x24, 0x8d, 0xf1, 0x63, 0xf4, 0x49, 0x52,
1023    };
1024    uint8_t sha_512_expected[] = {
1025        0x80, 0xb2, 0x42, 0x63, 0xc7, 0xc1, 0xa3, 0xeb, 0xb7, 0x14, 0x93, 0xc1, 0xdd,
1026        0x7b, 0xe8, 0xb4, 0x9b, 0x46, 0xd1, 0xf4, 0x1b, 0x4a, 0xee, 0xc1, 0x12, 0x1b,
1027        0x01, 0x37, 0x83, 0xf8, 0xf3, 0x52, 0x6b, 0x56, 0xd0, 0x37, 0xe0, 0x5f, 0x25,
1028        0x98, 0xbd, 0x0f, 0xd2, 0x21, 0x5d, 0x6a, 0x1e, 0x52, 0x95, 0xe6, 0x4f, 0x73,
1029        0xf6, 0x3f, 0x0a, 0xec, 0x8b, 0x91, 0x5a, 0x98, 0x5d, 0x78, 0x65, 0x98,
1030    };
1031
1032    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1033    if (!GetParam()->minimal_digest_set()) {
1034        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1035        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1036        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1037    }
1038
1039    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1040}
1041
1042TEST_P(SigningOperationsTest, HmacRfc4231TestCase7) {
1043    string key(131, 0xaa);
1044    string message = "This is a test using a larger than block-size key and a larger than "
1045                     "block-size data. The key needs to be hashed before being used by the HMAC "
1046                     "algorithm.";
1047
1048    uint8_t sha_224_expected[] = {
1049        0x3a, 0x85, 0x41, 0x66, 0xac, 0x5d, 0x9f, 0x02, 0x3f, 0x54, 0xd5, 0x17, 0xd0, 0xb3,
1050        0x9d, 0xbd, 0x94, 0x67, 0x70, 0xdb, 0x9c, 0x2b, 0x95, 0xc9, 0xf6, 0xf5, 0x65, 0xd1,
1051    };
1052    uint8_t sha_256_expected[] = {
1053        0x9b, 0x09, 0xff, 0xa7, 0x1b, 0x94, 0x2f, 0xcb, 0x27, 0x63, 0x5f,
1054        0xbc, 0xd5, 0xb0, 0xe9, 0x44, 0xbf, 0xdc, 0x63, 0x64, 0x4f, 0x07,
1055        0x13, 0x93, 0x8a, 0x7f, 0x51, 0x53, 0x5c, 0x3a, 0x35, 0xe2,
1056    };
1057    uint8_t sha_384_expected[] = {
1058        0x66, 0x17, 0x17, 0x8e, 0x94, 0x1f, 0x02, 0x0d, 0x35, 0x1e, 0x2f, 0x25,
1059        0x4e, 0x8f, 0xd3, 0x2c, 0x60, 0x24, 0x20, 0xfe, 0xb0, 0xb8, 0xfb, 0x9a,
1060        0xdc, 0xce, 0xbb, 0x82, 0x46, 0x1e, 0x99, 0xc5, 0xa6, 0x78, 0xcc, 0x31,
1061        0xe7, 0x99, 0x17, 0x6d, 0x38, 0x60, 0xe6, 0x11, 0x0c, 0x46, 0x52, 0x3e,
1062    };
1063    uint8_t sha_512_expected[] = {
1064        0xe3, 0x7b, 0x6a, 0x77, 0x5d, 0xc8, 0x7d, 0xba, 0xa4, 0xdf, 0xa9, 0xf9, 0x6e,
1065        0x5e, 0x3f, 0xfd, 0xde, 0xbd, 0x71, 0xf8, 0x86, 0x72, 0x89, 0x86, 0x5d, 0xf5,
1066        0xa3, 0x2d, 0x20, 0xcd, 0xc9, 0x44, 0xb6, 0x02, 0x2c, 0xac, 0x3c, 0x49, 0x82,
1067        0xb1, 0x0d, 0x5e, 0xeb, 0x55, 0xc3, 0xe4, 0xde, 0x15, 0x13, 0x46, 0x76, 0xfb,
1068        0x6d, 0xe0, 0x44, 0x60, 0x65, 0xc9, 0x74, 0x40, 0xfa, 0x8c, 0x6a, 0x58,
1069    };
1070
1071    CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_256, make_string(sha_256_expected));
1072    if (!GetParam()->minimal_digest_set()) {
1073        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_224, make_string(sha_224_expected));
1074        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_384, make_string(sha_384_expected));
1075        CheckHmacTestVector(key, message, KM_DIGEST_SHA_2_512, make_string(sha_512_expected));
1076    }
1077
1078    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1079}
1080
1081TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1082    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1083                                           .HmacKey(128)
1084                                           .Digest(KM_DIGEST_SHA_2_256)
1085                                           .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1086    AuthorizationSet begin_params(client_params());
1087    begin_params.push_back(TAG_MAC_LENGTH, 264);
1088    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1089    ASSERT_EQ(KM_ERROR_UNSUPPORTED_MAC_LENGTH,
1090              BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1091
1092    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1093}
1094
1095TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1096    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1097                                           .HmacKey(128)
1098                                           .Digest(KM_DIGEST_SHA_2_256)
1099                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1100    AuthorizationSet begin_params(client_params());
1101    begin_params.push_back(TAG_MAC_LENGTH, 120);
1102    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1103    ASSERT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
1104              BeginOperation(KM_PURPOSE_SIGN, begin_params, nullptr /* output_params */));
1105
1106    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1107}
1108
1109// TODO(swillden): Add more verification failure tests.
1110
1111typedef Keymaster2Test VerificationOperationsTest;
1112INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, VerificationOperationsTest, test_params);
1113
1114TEST_P(VerificationOperationsTest, RsaSuccess) {
1115    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1116                                           .RsaSigningKey(256, 3)
1117                                           .Digest(KM_DIGEST_NONE)
1118                                           .Padding(KM_PAD_NONE)));
1119    string message = "12345678901234567890123456789012";
1120    string signature;
1121    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1122    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1123
1124    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1125        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1126}
1127
1128TEST_P(VerificationOperationsTest, RsaPssSha256Success) {
1129    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1130                                           .RsaSigningKey(512, 3)
1131                                           .Digest(KM_DIGEST_SHA_2_256)
1132                                           .Padding(KM_PAD_RSA_PSS)));
1133    // Use large message, which won't work without digesting.
1134    string message(1024, 'a');
1135    string signature;
1136    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1137    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1138
1139    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1140        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1141}
1142
1143TEST_P(VerificationOperationsTest, RsaPssSha224Success) {
1144    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1145                                           .RsaSigningKey(512, 3)
1146                                           .Digest(KM_DIGEST_SHA_2_224)
1147                                           .Padding(KM_PAD_RSA_PSS)));
1148    // Use large message, which won't work without digesting.
1149    string message(1024, 'a');
1150    string signature;
1151    SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1152    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PSS);
1153
1154    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1155        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1156
1157    // Verify with OpenSSL.
1158    string pubkey;
1159    EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1160
1161    const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1162    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1163        d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1164    ASSERT_TRUE(pkey.get());
1165
1166    EVP_MD_CTX digest_ctx;
1167    EVP_MD_CTX_init(&digest_ctx);
1168    EVP_PKEY_CTX* pkey_ctx;
1169    EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1170                                      pkey.get()));
1171    EXPECT_EQ(1, EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING));
1172    EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1173    EXPECT_EQ(1,
1174              EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1175                                    signature.size()));
1176    EVP_MD_CTX_cleanup(&digest_ctx);
1177}
1178
1179TEST_P(VerificationOperationsTest, RsaPssSha256CorruptSignature) {
1180    GenerateKey(AuthorizationSetBuilder()
1181                    .RsaSigningKey(512, 3)
1182                    .Digest(KM_DIGEST_SHA_2_256)
1183                    .Padding(KM_PAD_RSA_PSS));
1184    string message(1024, 'a');
1185    string signature;
1186    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1187    ++signature[signature.size() / 2];
1188
1189    AuthorizationSet begin_params(client_params());
1190    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1191    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1192    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1193
1194    string result;
1195    size_t input_consumed;
1196    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1197    EXPECT_EQ(message.size(), input_consumed);
1198    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1199
1200    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1201        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1202}
1203
1204TEST_P(VerificationOperationsTest, RsaPssSha256CorruptInput) {
1205    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1206                                           .RsaSigningKey(512, 3)
1207                                           .Digest(KM_DIGEST_SHA_2_256)
1208                                           .Padding(KM_PAD_RSA_PSS)));
1209    // Use large message, which won't work without digesting.
1210    string message(1024, 'a');
1211    string signature;
1212    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PSS);
1213    ++message[message.size() / 2];
1214
1215    AuthorizationSet begin_params(client_params());
1216    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1217    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PSS);
1218    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1219
1220    string result;
1221    size_t input_consumed;
1222    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1223    EXPECT_EQ(message.size(), input_consumed);
1224    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1225
1226    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1227        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1228}
1229
1230TEST_P(VerificationOperationsTest, RsaPkcs1Sha256Success) {
1231    GenerateKey(AuthorizationSetBuilder()
1232                    .RsaSigningKey(512, 3)
1233                    .Digest(KM_DIGEST_SHA_2_256)
1234                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1235    string message(1024, 'a');
1236    string signature;
1237    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1238    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1239
1240    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1241        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1242}
1243
1244TEST_P(VerificationOperationsTest, RsaPks1Sha224Success) {
1245    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1246                                           .RsaSigningKey(512, 3)
1247                                           .Digest(KM_DIGEST_SHA_2_224)
1248                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1249    // Use large message, which won't work without digesting.
1250    string message(1024, 'a');
1251    string signature;
1252    SignMessage(message, &signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1253    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224, KM_PAD_RSA_PKCS1_1_5_SIGN);
1254
1255    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1256        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1257
1258    // Verify with OpenSSL.
1259    string pubkey;
1260    EXPECT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &pubkey));
1261
1262    const uint8_t* p = reinterpret_cast<const uint8_t*>(pubkey.data());
1263    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1264        d2i_PUBKEY(nullptr /* alloc new */, &p, pubkey.size()));
1265    ASSERT_TRUE(pkey.get());
1266
1267    EVP_MD_CTX digest_ctx;
1268    EVP_MD_CTX_init(&digest_ctx);
1269    EVP_PKEY_CTX* pkey_ctx;
1270    EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, EVP_sha224(), nullptr /* engine */,
1271                                      pkey.get()));
1272    EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(), message.size()));
1273    EXPECT_EQ(1,
1274              EVP_DigestVerifyFinal(&digest_ctx, reinterpret_cast<const uint8_t*>(signature.data()),
1275                                    signature.size()));
1276    EVP_MD_CTX_cleanup(&digest_ctx);
1277}
1278
1279TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptSignature) {
1280    GenerateKey(AuthorizationSetBuilder()
1281                    .RsaSigningKey(512, 3)
1282                    .Digest(KM_DIGEST_SHA_2_256)
1283                    .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN));
1284    string message(1024, 'a');
1285    string signature;
1286    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1287    ++signature[signature.size() / 2];
1288
1289    AuthorizationSet begin_params(client_params());
1290    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1291    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1292    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1293
1294    string result;
1295    size_t input_consumed;
1296    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1297    EXPECT_EQ(message.size(), input_consumed);
1298    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1299
1300    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1301        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1302}
1303
1304TEST_P(VerificationOperationsTest, RsaPkcs1Sha256CorruptInput) {
1305    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1306                                           .RsaSigningKey(512, 3)
1307                                           .Digest(KM_DIGEST_SHA_2_256)
1308                                           .Padding(KM_PAD_RSA_PKCS1_1_5_SIGN)));
1309    // Use large message, which won't work without digesting.
1310    string message(1024, 'a');
1311    string signature;
1312    SignMessage(message, &signature, KM_DIGEST_SHA_2_256, KM_PAD_RSA_PKCS1_1_5_SIGN);
1313    ++message[message.size() / 2];
1314
1315    AuthorizationSet begin_params(client_params());
1316    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
1317    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN);
1318    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1319
1320    string result;
1321    size_t input_consumed;
1322    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1323    EXPECT_EQ(message.size(), input_consumed);
1324    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1325
1326    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1327        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1328}
1329
1330TEST_P(VerificationOperationsTest, RsaAllDigestAndPadCombinations) {
1331    vector<keymaster_digest_t> digests = {
1332        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
1333        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1334    };
1335
1336    vector<keymaster_padding_t> padding_modes{
1337        KM_PAD_NONE, KM_PAD_RSA_PKCS1_1_5_SIGN, KM_PAD_RSA_PSS,
1338    };
1339
1340    int trial_count = 0;
1341    for (keymaster_padding_t padding_mode : padding_modes) {
1342        for (keymaster_digest_t digest : digests) {
1343            if (digest != KM_DIGEST_NONE && padding_mode == KM_PAD_NONE)
1344                // Digesting requires padding
1345                continue;
1346
1347            // Compute key & message size that will work.
1348            size_t key_bits = 0;
1349            size_t message_len = 1000;
1350
1351            if (digest == KM_DIGEST_NONE) {
1352                key_bits = 256;
1353                switch (padding_mode) {
1354                case KM_PAD_NONE:
1355                    // Match key size.
1356                    message_len = key_bits / 8;
1357                    break;
1358                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1359                    message_len = key_bits / 8 - 11;
1360                    break;
1361                case KM_PAD_RSA_PSS:
1362                    // PSS requires a digest.
1363                    continue;
1364                default:
1365                    FAIL() << "Missing padding";
1366                    break;
1367                }
1368            } else {
1369                size_t digest_bits;
1370                switch (digest) {
1371                case KM_DIGEST_MD5:
1372                    digest_bits = 128;
1373                    break;
1374                case KM_DIGEST_SHA1:
1375                    digest_bits = 160;
1376                    break;
1377                case KM_DIGEST_SHA_2_224:
1378                    digest_bits = 224;
1379                    break;
1380                case KM_DIGEST_SHA_2_256:
1381                    digest_bits = 256;
1382                    break;
1383                case KM_DIGEST_SHA_2_384:
1384                    digest_bits = 384;
1385                    break;
1386                case KM_DIGEST_SHA_2_512:
1387                    digest_bits = 512;
1388                    break;
1389                default:
1390                    FAIL() << "Missing digest";
1391                }
1392
1393                switch (padding_mode) {
1394                case KM_PAD_RSA_PKCS1_1_5_SIGN:
1395                    key_bits = digest_bits + 8 * (11 + 19);
1396                    break;
1397                case KM_PAD_RSA_PSS:
1398                    key_bits = digest_bits + 22 * 8;
1399                    break;
1400                default:
1401                    FAIL() << "Missing padding";
1402                    break;
1403                }
1404            }
1405
1406            GenerateKey(AuthorizationSetBuilder()
1407                            .RsaSigningKey(key_bits, 3)
1408                            .Digest(digest)
1409                            .Padding(padding_mode));
1410            string message(message_len, 'a');
1411            string signature;
1412            SignMessage(message, &signature, digest, padding_mode);
1413            VerifyMessage(message, signature, digest, padding_mode);
1414            ++trial_count;
1415        }
1416    }
1417
1418    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1419        EXPECT_EQ(trial_count * 4, GetParam()->keymaster0_calls());
1420}
1421
1422TEST_P(VerificationOperationsTest, EcdsaSuccess) {
1423    ASSERT_EQ(KM_ERROR_OK,
1424              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1425    string message = "12345678901234567890123456789012";
1426    string signature;
1427    SignMessage(message, &signature, KM_DIGEST_NONE);
1428    VerifyMessage(message, signature, KM_DIGEST_NONE);
1429
1430    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1431        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1432}
1433
1434TEST_P(VerificationOperationsTest, EcdsaTooShort) {
1435    ASSERT_EQ(KM_ERROR_OK,
1436              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE)));
1437    string message = "12345678901234567890";
1438    string signature;
1439    SignMessage(message, &signature, KM_DIGEST_NONE);
1440    VerifyMessage(message, signature, KM_DIGEST_NONE);
1441
1442    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1443        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1444}
1445
1446TEST_P(VerificationOperationsTest, EcdsaSlightlyTooLong) {
1447    ASSERT_EQ(KM_ERROR_OK,
1448              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(521).Digest(KM_DIGEST_NONE)));
1449
1450    string message(66, 'a');
1451    string signature;
1452    SignMessage(message, &signature, KM_DIGEST_NONE);
1453    VerifyMessage(message, signature, KM_DIGEST_NONE);
1454
1455    // Modifying low-order bits doesn't matter, because they didn't get signed.  Ugh.
1456    message[65] ^= 7;
1457    VerifyMessage(message, signature, KM_DIGEST_NONE);
1458
1459    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1460        EXPECT_EQ(5, GetParam()->keymaster0_calls());
1461}
1462
1463TEST_P(VerificationOperationsTest, EcdsaSha256Success) {
1464    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1465                                           .EcdsaSigningKey(256)
1466                                           .Digest(KM_DIGEST_SHA_2_256)
1467                                           .Digest(KM_DIGEST_NONE)));
1468    string message = "12345678901234567890123456789012";
1469    string signature;
1470    SignMessage(message, &signature, KM_DIGEST_SHA_2_256);
1471    VerifyMessage(message, signature, KM_DIGEST_SHA_2_256);
1472
1473    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1474        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1475
1476    // Just for giggles, try verifying with the wrong digest.
1477    AuthorizationSet begin_params(client_params());
1478    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1479    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1480
1481    string result;
1482    size_t input_consumed;
1483    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1484    EXPECT_EQ(message.size(), input_consumed);
1485    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1486}
1487
1488TEST_P(VerificationOperationsTest, EcdsaSha224Success) {
1489    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(
1490                               KM_DIGEST_SHA_2_224)));
1491
1492    string message = "12345678901234567890123456789012";
1493    string signature;
1494    SignMessage(message, &signature, KM_DIGEST_SHA_2_224);
1495    VerifyMessage(message, signature, KM_DIGEST_SHA_2_224);
1496
1497    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1498        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1499
1500    // Just for giggles, try verifying with the wrong digest.
1501    AuthorizationSet begin_params(client_params());
1502    begin_params.push_back(TAG_DIGEST, KM_DIGEST_NONE);
1503    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1504
1505    string result;
1506    size_t input_consumed;
1507    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1508    EXPECT_EQ(message.size(), input_consumed);
1509    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(signature, &result));
1510}
1511
1512TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndKeySizes) {
1513    keymaster_digest_t digests[] = {
1514        KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224, KM_DIGEST_SHA_2_256,
1515        KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
1516    };
1517    size_t key_sizes[] = {224, 256, 384, 521};
1518
1519    string message = "1234567890";
1520    string signature;
1521
1522    for (auto key_size : key_sizes) {
1523        AuthorizationSetBuilder builder;
1524        builder.EcdsaSigningKey(key_size);
1525        for (auto digest : digests)
1526            builder.Digest(digest);
1527        ASSERT_EQ(KM_ERROR_OK, GenerateKey(builder));
1528
1529        for (auto digest : digests) {
1530            SignMessage(message, &signature, digest);
1531            VerifyMessage(message, signature, digest);
1532        }
1533    }
1534
1535    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1536        EXPECT_EQ(static_cast<int>(array_length(key_sizes) * (1 + 3 * array_length(digests))),
1537                  GetParam()->keymaster0_calls());
1538}
1539
1540TEST_P(VerificationOperationsTest, HmacSha1Success) {
1541    if (GetParam()->minimal_digest_set())
1542        // Can't emulate missing digests for HMAC.
1543        return;
1544
1545    GenerateKey(AuthorizationSetBuilder()
1546                    .HmacKey(128)
1547                    .Digest(KM_DIGEST_SHA1)
1548                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1549    string message = "123456789012345678901234567890123456789012345678";
1550    string signature;
1551    MacMessage(message, &signature, 160);
1552    VerifyMac(message, signature);
1553
1554    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1555}
1556
1557TEST_P(VerificationOperationsTest, HmacSha224Success) {
1558    if (GetParam()->minimal_digest_set())
1559        // Can't emulate missing digests for HMAC.
1560        return;
1561
1562    GenerateKey(AuthorizationSetBuilder()
1563                    .HmacKey(128)
1564                    .Digest(KM_DIGEST_SHA_2_224)
1565                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1566    string message = "123456789012345678901234567890123456789012345678";
1567    string signature;
1568    MacMessage(message, &signature, 224);
1569    VerifyMac(message, signature);
1570
1571    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1572}
1573
1574TEST_P(VerificationOperationsTest, HmacSha256Success) {
1575    GenerateKey(AuthorizationSetBuilder()
1576                    .HmacKey(128)
1577                    .Digest(KM_DIGEST_SHA_2_256)
1578                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1579    string message = "123456789012345678901234567890123456789012345678";
1580    string signature;
1581    MacMessage(message, &signature, 256);
1582    VerifyMac(message, signature);
1583
1584    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1585}
1586
1587TEST_P(VerificationOperationsTest, HmacSha256TooShortMac) {
1588    GenerateKey(AuthorizationSetBuilder()
1589                    .HmacKey(128)
1590                    .Digest(KM_DIGEST_SHA_2_256)
1591                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1592    string message = "123456789012345678901234567890123456789012345678";
1593    string signature;
1594    MacMessage(message, &signature, 256);
1595
1596    // Shorten to 128 bits, should still work.
1597    signature.resize(128 / 8);
1598    VerifyMac(message, signature);
1599
1600    // Drop one more byte.
1601    signature.resize(signature.length() - 1);
1602
1603    AuthorizationSet begin_params(client_params());
1604    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_VERIFY, begin_params));
1605    string result;
1606    size_t input_consumed;
1607    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1608    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, FinishOperation(signature, &result));
1609
1610    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1611}
1612
1613TEST_P(VerificationOperationsTest, HmacSha384Success) {
1614    if (GetParam()->minimal_digest_set())
1615        // Can't emulate missing digests for HMAC.
1616        return;
1617
1618    GenerateKey(AuthorizationSetBuilder()
1619                    .HmacKey(128)
1620                    .Digest(KM_DIGEST_SHA_2_384)
1621                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1622    string message = "123456789012345678901234567890123456789012345678";
1623    string signature;
1624    MacMessage(message, &signature, 384);
1625    VerifyMac(message, signature);
1626
1627    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1628}
1629
1630TEST_P(VerificationOperationsTest, HmacSha512Success) {
1631    if (GetParam()->minimal_digest_set())
1632        // Can't emulate missing digests for HMAC.
1633        return;
1634
1635    GenerateKey(AuthorizationSetBuilder()
1636                    .HmacKey(128)
1637                    .Digest(KM_DIGEST_SHA_2_512)
1638                    .Authorization(TAG_MIN_MAC_LENGTH, 128));
1639    string message = "123456789012345678901234567890123456789012345678";
1640    string signature;
1641    MacMessage(message, &signature, 512);
1642    VerifyMac(message, signature);
1643
1644    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1645}
1646
1647typedef Keymaster2Test ExportKeyTest;
1648INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ExportKeyTest, test_params);
1649
1650TEST_P(ExportKeyTest, RsaSuccess) {
1651    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1652                                           .RsaSigningKey(256, 3)
1653                                           .Digest(KM_DIGEST_NONE)
1654                                           .Padding(KM_PAD_NONE)));
1655    string export_data;
1656    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1657    EXPECT_GT(export_data.length(), 0U);
1658
1659    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1660
1661    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1662        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1663}
1664
1665TEST_P(ExportKeyTest, EcdsaSuccess) {
1666    ASSERT_EQ(KM_ERROR_OK,
1667              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
1668    string export_data;
1669    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1670    EXPECT_GT(export_data.length(), 0U);
1671
1672    // TODO(swillden): Verify that the exported key is actually usable to verify signatures.
1673
1674    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1675        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1676}
1677
1678TEST_P(ExportKeyTest, RsaUnsupportedKeyFormat) {
1679    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1680                                           .RsaSigningKey(256, 3)
1681                                           .Digest(KM_DIGEST_NONE)
1682                                           .Padding(KM_PAD_NONE)));
1683    string export_data;
1684    ASSERT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1685
1686    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1687        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1688}
1689
1690TEST_P(ExportKeyTest, RsaCorruptedKeyBlob) {
1691    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
1692                                           .RsaSigningKey(256, 3)
1693                                           .Digest(KM_DIGEST_NONE)
1694                                           .Padding(KM_PAD_NONE)));
1695    corrupt_key_blob();
1696    string export_data;
1697    ASSERT_EQ(KM_ERROR_INVALID_KEY_BLOB, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1698
1699    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1700        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1701}
1702
1703TEST_P(ExportKeyTest, AesKeyExportFails) {
1704    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().AesEncryptionKey(128)));
1705    string export_data;
1706
1707    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_X509, &export_data));
1708    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_PKCS8, &export_data));
1709    EXPECT_EQ(KM_ERROR_UNSUPPORTED_KEY_FORMAT, ExportKey(KM_KEY_FORMAT_RAW, &export_data));
1710
1711    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1712}
1713
1714static string read_file(const string& file_name) {
1715    ifstream file_stream(file_name, std::ios::binary);
1716    istreambuf_iterator<char> file_begin(file_stream);
1717    istreambuf_iterator<char> file_end;
1718    return string(file_begin, file_end);
1719}
1720
1721typedef Keymaster2Test ImportKeyTest;
1722INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, ImportKeyTest, test_params);
1723
1724TEST_P(ImportKeyTest, RsaSuccess) {
1725    string pk8_key = read_file("rsa_privkey_pk8.der");
1726    ASSERT_EQ(633U, pk8_key.size());
1727
1728    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1729                                         .RsaSigningKey(1024, 65537)
1730                                         .Digest(KM_DIGEST_NONE)
1731                                         .Padding(KM_PAD_NONE),
1732                                     KM_KEY_FORMAT_PKCS8, pk8_key));
1733
1734    // Check values derived from the key.
1735    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1736                                                                                 : sw_enforced(),
1737                         TAG_ALGORITHM, KM_ALGORITHM_RSA));
1738    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1739                                                                                 : sw_enforced(),
1740                         TAG_KEY_SIZE, 1024));
1741    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA) ? hw_enforced()
1742                                                                                 : sw_enforced(),
1743                         TAG_RSA_PUBLIC_EXPONENT, 65537U));
1744
1745    // And values provided by AndroidKeymaster
1746    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1747        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1748    else
1749        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1750    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1751
1752    string message(1024 / 8, 'a');
1753    string signature;
1754    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
1755    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
1756
1757    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1758        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1759}
1760
1761TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1762    string pk8_key = read_file("rsa_privkey_pk8.der");
1763    ASSERT_EQ(633U, pk8_key.size());
1764    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1765              ImportKey(AuthorizationSetBuilder()
1766                            .RsaSigningKey(2048 /* Doesn't match key */, 3)
1767                            .Digest(KM_DIGEST_NONE)
1768                            .Padding(KM_PAD_NONE),
1769                        KM_KEY_FORMAT_PKCS8, pk8_key));
1770
1771    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1772}
1773
1774TEST_P(ImportKeyTest, RsaPublicExponenMismatch) {
1775    string pk8_key = read_file("rsa_privkey_pk8.der");
1776    ASSERT_EQ(633U, pk8_key.size());
1777    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1778              ImportKey(AuthorizationSetBuilder()
1779                            .RsaSigningKey(256, 3 /* Doesnt' match key */)
1780                            .Digest(KM_DIGEST_NONE)
1781                            .Padding(KM_PAD_NONE),
1782                        KM_KEY_FORMAT_PKCS8, pk8_key));
1783
1784    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1785}
1786
1787TEST_P(ImportKeyTest, EcdsaSuccess) {
1788    string pk8_key = read_file("ec_privkey_pk8.der");
1789    ASSERT_EQ(138U, pk8_key.size());
1790
1791    ASSERT_EQ(KM_ERROR_OK,
1792              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1793                        KM_KEY_FORMAT_PKCS8, pk8_key));
1794
1795    // Check values derived from the key.
1796    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1797                                                                                : sw_enforced(),
1798                         TAG_ALGORITHM, KM_ALGORITHM_EC));
1799    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1800                                                                                : sw_enforced(),
1801                         TAG_KEY_SIZE, 256));
1802
1803    // And values provided by AndroidKeymaster
1804    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1805        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1806    else
1807        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1808    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1809
1810    string message(32, 'a');
1811    string signature;
1812    SignMessage(message, &signature, KM_DIGEST_NONE);
1813    VerifyMessage(message, signature, KM_DIGEST_NONE);
1814
1815    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1816        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1817}
1818
1819TEST_P(ImportKeyTest, EcdsaSizeSpecified) {
1820    string pk8_key = read_file("ec_privkey_pk8.der");
1821    ASSERT_EQ(138U, pk8_key.size());
1822
1823    ASSERT_EQ(KM_ERROR_OK,
1824              ImportKey(AuthorizationSetBuilder().EcdsaSigningKey(256).Digest(KM_DIGEST_NONE),
1825                        KM_KEY_FORMAT_PKCS8, pk8_key));
1826
1827    // Check values derived from the key.
1828    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1829                                                                                : sw_enforced(),
1830                         TAG_ALGORITHM, KM_ALGORITHM_EC));
1831    EXPECT_TRUE(contains(GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC) ? hw_enforced()
1832                                                                                : sw_enforced(),
1833                         TAG_KEY_SIZE, 256));
1834
1835    // And values provided by AndroidKeymaster
1836    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1837        EXPECT_TRUE(contains(hw_enforced(), TAG_ORIGIN, KM_ORIGIN_UNKNOWN));
1838    else
1839        EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1840    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1841
1842    string message(32, 'a');
1843    string signature;
1844    SignMessage(message, &signature, KM_DIGEST_NONE);
1845    VerifyMessage(message, signature, KM_DIGEST_NONE);
1846
1847    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
1848        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1849}
1850
1851TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
1852    string pk8_key = read_file("ec_privkey_pk8.der");
1853    ASSERT_EQ(138U, pk8_key.size());
1854    ASSERT_EQ(KM_ERROR_IMPORT_PARAMETER_MISMATCH,
1855              ImportKey(AuthorizationSetBuilder()
1856                            .EcdsaSigningKey(224 /* Doesn't match key */)
1857                            .Digest(KM_DIGEST_NONE),
1858                        KM_KEY_FORMAT_PKCS8, pk8_key));
1859
1860    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1861}
1862
1863TEST_P(ImportKeyTest, AesKeySuccess) {
1864    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1865    string key(key_data, sizeof(key_data));
1866    ASSERT_EQ(KM_ERROR_OK,
1867              ImportKey(AuthorizationSetBuilder().AesEncryptionKey(128).EcbMode().Authorization(
1868                            TAG_PADDING, KM_PAD_PKCS7),
1869                        KM_KEY_FORMAT_RAW, key));
1870
1871    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1872    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1873
1874    string message = "Hello World!";
1875    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
1876    string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
1877    EXPECT_EQ(message, plaintext);
1878
1879    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1880}
1881
1882TEST_P(ImportKeyTest, HmacSha256KeySuccess) {
1883    char key_data[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
1884    string key(key_data, sizeof(key_data));
1885    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
1886                                         .HmacKey(sizeof(key_data) * 8)
1887                                         .Digest(KM_DIGEST_SHA_2_256)
1888                                         .Authorization(TAG_MIN_MAC_LENGTH, 256),
1889                                     KM_KEY_FORMAT_RAW, key));
1890
1891    EXPECT_TRUE(contains(sw_enforced(), TAG_ORIGIN, KM_ORIGIN_IMPORTED));
1892    EXPECT_TRUE(contains(sw_enforced(), KM_TAG_CREATION_DATETIME));
1893
1894    string message = "Hello World!";
1895    string signature;
1896    MacMessage(message, &signature, 256);
1897    VerifyMac(message, signature);
1898
1899    EXPECT_EQ(0, GetParam()->keymaster0_calls());
1900}
1901
1902typedef Keymaster2Test EncryptionOperationsTest;
1903INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, EncryptionOperationsTest, test_params);
1904
1905TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
1906    ASSERT_EQ(KM_ERROR_OK,
1907              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1908
1909    string message = "12345678901234567890123456789012";
1910    string ciphertext1 = EncryptMessage(string(message), KM_PAD_NONE);
1911    EXPECT_EQ(256U / 8, ciphertext1.size());
1912
1913    string ciphertext2 = EncryptMessage(string(message), KM_PAD_NONE);
1914    EXPECT_EQ(256U / 8, ciphertext2.size());
1915
1916    // Unpadded RSA is deterministic
1917    EXPECT_EQ(ciphertext1, ciphertext2);
1918
1919    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1920        EXPECT_EQ(3, GetParam()->keymaster0_calls());
1921}
1922
1923TEST_P(EncryptionOperationsTest, RsaNoPaddingTooShort) {
1924    ASSERT_EQ(KM_ERROR_OK,
1925              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1926
1927    string message = "1";
1928
1929    string ciphertext = EncryptMessage(message, KM_PAD_NONE);
1930    EXPECT_EQ(256U / 8, ciphertext.size());
1931
1932    string expected_plaintext = string(256 / 8 - 1, 0) + message;
1933    string plaintext = DecryptMessage(ciphertext, KM_PAD_NONE);
1934
1935    EXPECT_EQ(expected_plaintext, plaintext);
1936
1937    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1938        EXPECT_EQ(4, GetParam()->keymaster0_calls());
1939}
1940
1941TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
1942    ASSERT_EQ(KM_ERROR_OK,
1943              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1944
1945    string message = "123456789012345678901234567890123";
1946
1947    AuthorizationSet begin_params(client_params());
1948    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
1949    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1950
1951    string result;
1952    size_t input_consumed;
1953    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, UpdateOperation(message, &result, &input_consumed));
1954
1955    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1956        EXPECT_EQ(2, GetParam()->keymaster0_calls());
1957}
1958
1959TEST_P(EncryptionOperationsTest, RsaNoPaddingLargerThanModulus) {
1960    ASSERT_EQ(KM_ERROR_OK,
1961              GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(256, 3).Padding(KM_PAD_NONE)));
1962
1963    string exported;
1964    ASSERT_EQ(KM_ERROR_OK, ExportKey(KM_KEY_FORMAT_X509, &exported));
1965
1966    const uint8_t* p = reinterpret_cast<const uint8_t*>(exported.data());
1967    unique_ptr<EVP_PKEY, EVP_PKEY_Delete> pkey(
1968        d2i_PUBKEY(nullptr /* alloc new */, &p, exported.size()));
1969    unique_ptr<RSA, RSA_Delete> rsa(EVP_PKEY_get1_RSA(pkey.get()));
1970
1971    size_t modulus_len = BN_num_bytes(rsa->n);
1972    ASSERT_EQ(256U / 8, modulus_len);
1973    unique_ptr<uint8_t[]> modulus_buf(new uint8_t[modulus_len]);
1974    BN_bn2bin(rsa->n, modulus_buf.get());
1975
1976    // The modulus is too big to encrypt.
1977    string message(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
1978
1979    AuthorizationSet begin_params(client_params());
1980    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
1981    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1982
1983    string result;
1984    size_t input_consumed;
1985    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1986    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&result));
1987
1988    // One smaller than the modulus is okay.
1989    BN_sub(rsa->n, rsa->n, BN_value_one());
1990    modulus_len = BN_num_bytes(rsa->n);
1991    ASSERT_EQ(256U / 8, modulus_len);
1992    BN_bn2bin(rsa->n, modulus_buf.get());
1993    message = string(reinterpret_cast<const char*>(modulus_buf.get()), modulus_len);
1994    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
1995    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
1996    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&result));
1997
1998    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
1999        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2000}
2001
2002TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2003    size_t key_size = 768;
2004    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2005                                           .RsaEncryptionKey(key_size, 3)
2006                                           .Padding(KM_PAD_RSA_OAEP)
2007                                           .Digest(KM_DIGEST_SHA_2_256)));
2008
2009    string message = "Hello";
2010    string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2011    EXPECT_EQ(key_size / 8, ciphertext1.size());
2012
2013    string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2014    EXPECT_EQ(key_size / 8, ciphertext2.size());
2015
2016    // OAEP randomizes padding so every result should be different.
2017    EXPECT_NE(ciphertext1, ciphertext2);
2018
2019    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2020        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2021}
2022
2023TEST_P(EncryptionOperationsTest, RsaOaepSha224Success) {
2024    size_t key_size = 768;
2025    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2026                                           .RsaEncryptionKey(key_size, 3)
2027                                           .Padding(KM_PAD_RSA_OAEP)
2028                                           .Digest(KM_DIGEST_SHA_2_224)));
2029
2030    string message = "Hello";
2031    string ciphertext1 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2032    EXPECT_EQ(key_size / 8, ciphertext1.size());
2033
2034    string ciphertext2 = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2035    EXPECT_EQ(key_size / 8, ciphertext2.size());
2036
2037    // OAEP randomizes padding so every result should be different.
2038    EXPECT_NE(ciphertext1, ciphertext2);
2039
2040    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2041        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2042}
2043
2044TEST_P(EncryptionOperationsTest, RsaOaepRoundTrip) {
2045    size_t key_size = 768;
2046    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2047                                           .RsaEncryptionKey(key_size, 3)
2048                                           .Padding(KM_PAD_RSA_OAEP)
2049                                           .Digest(KM_DIGEST_SHA_2_256)));
2050    string message = "Hello World!";
2051    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2052    EXPECT_EQ(key_size / 8, ciphertext.size());
2053
2054    string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2055    EXPECT_EQ(message, plaintext);
2056
2057    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2058        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2059}
2060
2061TEST_P(EncryptionOperationsTest, RsaOaepSha224RoundTrip) {
2062    size_t key_size = 768;
2063    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2064                                           .RsaEncryptionKey(key_size, 3)
2065                                           .Padding(KM_PAD_RSA_OAEP)
2066                                           .Digest(KM_DIGEST_SHA_2_224)));
2067    string message = "Hello World!";
2068    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2069    EXPECT_EQ(key_size / 8, ciphertext.size());
2070
2071    string plaintext = DecryptMessage(ciphertext, KM_DIGEST_SHA_2_224, KM_PAD_RSA_OAEP);
2072    EXPECT_EQ(message, plaintext);
2073
2074    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2075        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2076}
2077
2078TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2079    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2080                                           .RsaEncryptionKey(512, 3)
2081                                           .Padding(KM_PAD_RSA_OAEP)
2082                                           .Digest(KM_DIGEST_NONE)));
2083    string message = "Hello World!";
2084
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_NONE);
2088    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2089
2090    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2091        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2092}
2093
2094TEST_P(EncryptionOperationsTest, RsaOaepUnauthorizedDigest) {
2095    if (GetParam()->minimal_digest_set())
2096        // We don't have two supported digests, so we can't try authorizing one and using another.
2097        return;
2098
2099    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2100                                           .RsaEncryptionKey(512, 3)
2101                                           .Padding(KM_PAD_RSA_OAEP)
2102                                           .Digest(KM_DIGEST_SHA_2_256)));
2103    string message = "Hello World!";
2104    // Works because encryption is a public key operation.
2105    EncryptMessage(string(message), KM_DIGEST_SHA1, KM_PAD_RSA_OAEP);
2106
2107    AuthorizationSet begin_params(client_params());
2108    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2109    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2110    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_DIGEST, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2111
2112    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2113        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2114}
2115
2116TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2117    if (GetParam()->minimal_digest_set())
2118        // We don't have two supported digests, so we can't try encrypting with one and decrypting
2119        // with another.
2120        return;
2121
2122    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2123                                           .RsaEncryptionKey(768, 3)
2124                                           .Padding(KM_PAD_RSA_OAEP)
2125                                           .Digest(KM_DIGEST_SHA_2_256)
2126                                           .Digest(KM_DIGEST_SHA_2_384)));
2127    string message = "Hello World!";
2128    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2129
2130    string result;
2131    size_t input_consumed;
2132    AuthorizationSet begin_params(client_params());
2133    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2134    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_384);
2135    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2136    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2137    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2138    EXPECT_EQ(0U, result.size());
2139
2140    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2141        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2142}
2143
2144TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2145    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2146                                           .RsaEncryptionKey(512, 3)
2147                                           .Padding(KM_PAD_RSA_OAEP)
2148                                           .Digest(KM_DIGEST_SHA1)));
2149    string message = "12345678901234567890123";
2150    string result;
2151    size_t input_consumed;
2152
2153    AuthorizationSet begin_params(client_params());
2154    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2155    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA1);
2156    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2157    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2158    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
2159    EXPECT_EQ(0U, result.size());
2160
2161    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2162        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2163}
2164
2165TEST_P(EncryptionOperationsTest, RsaOaepCorruptedDecrypt) {
2166    size_t key_size = 768;
2167    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2168                                           .RsaEncryptionKey(768, 3)
2169                                           .Padding(KM_PAD_RSA_OAEP)
2170                                           .Digest(KM_DIGEST_SHA_2_256)));
2171    string message = "Hello World!";
2172    string ciphertext = EncryptMessage(string(message), KM_DIGEST_SHA_2_256, KM_PAD_RSA_OAEP);
2173    EXPECT_EQ(key_size / 8, ciphertext.size());
2174
2175    // Corrupt the ciphertext
2176    ciphertext[key_size / 8 / 2]++;
2177
2178    string result;
2179    size_t input_consumed;
2180    AuthorizationSet begin_params(client_params());
2181    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_OAEP);
2182    begin_params.push_back(TAG_DIGEST, KM_DIGEST_SHA_2_256);
2183    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2184    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2185    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2186    EXPECT_EQ(0U, result.size());
2187
2188    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2189        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2190}
2191
2192TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2193    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2194                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2195    string message = "Hello World!";
2196    string ciphertext1 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2197    EXPECT_EQ(512U / 8, ciphertext1.size());
2198
2199    string ciphertext2 = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2200    EXPECT_EQ(512U / 8, ciphertext2.size());
2201
2202    // PKCS1 v1.5 randomizes padding so every result should be different.
2203    EXPECT_NE(ciphertext1, ciphertext2);
2204
2205    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2206        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2207}
2208
2209TEST_P(EncryptionOperationsTest, RsaPkcs1RoundTrip) {
2210    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2211                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2212    string message = "Hello World!";
2213    string ciphertext = EncryptMessage(message, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2214    EXPECT_EQ(512U / 8, ciphertext.size());
2215
2216    string plaintext = DecryptMessage(ciphertext, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2217    EXPECT_EQ(message, plaintext);
2218
2219    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2220        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2221}
2222
2223TEST_P(EncryptionOperationsTest, RsaRoundTripAllCombinations) {
2224    size_t key_size = 2048;
2225    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2226                                           .RsaEncryptionKey(key_size, 3)
2227                                           .Padding(KM_PAD_RSA_PKCS1_1_5_ENCRYPT)
2228                                           .Padding(KM_PAD_RSA_OAEP)
2229                                           .Digest(KM_DIGEST_NONE)
2230                                           .Digest(KM_DIGEST_MD5)
2231                                           .Digest(KM_DIGEST_SHA1)
2232                                           .Digest(KM_DIGEST_SHA_2_224)
2233                                           .Digest(KM_DIGEST_SHA_2_256)
2234                                           .Digest(KM_DIGEST_SHA_2_384)
2235                                           .Digest(KM_DIGEST_SHA_2_512)));
2236
2237    string message = "Hello World!";
2238
2239    keymaster_padding_t padding_modes[] = {KM_PAD_RSA_OAEP, KM_PAD_RSA_PKCS1_1_5_ENCRYPT};
2240    keymaster_digest_t digests[] = {
2241        KM_DIGEST_NONE,      KM_DIGEST_MD5,       KM_DIGEST_SHA1,      KM_DIGEST_SHA_2_224,
2242        KM_DIGEST_SHA_2_256, KM_DIGEST_SHA_2_384, KM_DIGEST_SHA_2_512,
2243    };
2244
2245    for (auto padding : padding_modes)
2246        for (auto digest : digests) {
2247            if (padding == KM_PAD_RSA_OAEP && digest == KM_DIGEST_NONE)
2248                // OAEP requires a digest.
2249                continue;
2250
2251            string ciphertext = EncryptMessage(message, digest, padding);
2252            EXPECT_EQ(key_size / 8, ciphertext.size());
2253
2254            string plaintext = DecryptMessage(ciphertext, digest, padding);
2255            EXPECT_EQ(message, plaintext);
2256        }
2257
2258    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2259        EXPECT_EQ(40, GetParam()->keymaster0_calls());
2260}
2261
2262TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2263    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2264                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2265    string message = "123456789012345678901234567890123456789012345678901234";
2266    string result;
2267    size_t input_consumed;
2268
2269    AuthorizationSet begin_params(client_params());
2270    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2271    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2272    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &result, &input_consumed));
2273    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&result));
2274    EXPECT_EQ(0U, result.size());
2275
2276    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2277        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2278}
2279
2280TEST_P(EncryptionOperationsTest, RsaPkcs1CorruptedDecrypt) {
2281    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder().RsaEncryptionKey(512, 3).Padding(
2282                               KM_PAD_RSA_PKCS1_1_5_ENCRYPT)));
2283    string message = "Hello World!";
2284    string ciphertext = EncryptMessage(string(message), KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2285    EXPECT_EQ(512U / 8, ciphertext.size());
2286
2287    // Corrupt the ciphertext
2288    ciphertext[512 / 8 / 2]++;
2289
2290    string result;
2291    size_t input_consumed;
2292    AuthorizationSet begin_params(client_params());
2293    begin_params.push_back(TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT);
2294    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2295    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &result, &input_consumed));
2296    EXPECT_EQ(KM_ERROR_UNKNOWN_ERROR, FinishOperation(&result));
2297    EXPECT_EQ(0U, result.size());
2298
2299    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2300        EXPECT_EQ(4, GetParam()->keymaster0_calls());
2301}
2302
2303TEST_P(EncryptionOperationsTest, RsaEncryptWithSigningKey) {
2304    ASSERT_EQ(KM_ERROR_OK,
2305              GenerateKey(AuthorizationSetBuilder().RsaSigningKey(256, 3).Padding(KM_PAD_NONE)));
2306
2307    AuthorizationSet begin_params(client_params());
2308    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2309    ASSERT_EQ(KM_ERROR_INCOMPATIBLE_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2310
2311    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_RSA))
2312        EXPECT_EQ(2, GetParam()->keymaster0_calls());
2313}
2314
2315TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2316    ASSERT_EQ(KM_ERROR_OK,
2317              GenerateKey(AuthorizationSetBuilder().EcdsaSigningKey(224).Digest(KM_DIGEST_NONE)));
2318    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2319    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2320
2321    if (GetParam()->algorithm_in_km0_hardware(KM_ALGORITHM_EC))
2322        EXPECT_EQ(3, GetParam()->keymaster0_calls());
2323}
2324
2325TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2326    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2327                                           .HmacKey(128)
2328                                           .Digest(KM_DIGEST_SHA_2_256)
2329                                           .Padding(KM_PAD_NONE)
2330                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2331    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_ENCRYPT));
2332    ASSERT_EQ(KM_ERROR_UNSUPPORTED_PURPOSE, BeginOperation(KM_PURPOSE_DECRYPT));
2333
2334    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2335}
2336
2337TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2338    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2339                                           .AesEncryptionKey(128)
2340                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2341                                           .Padding(KM_PAD_NONE)));
2342    // Two-block message.
2343    string message = "12345678901234567890123456789012";
2344    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
2345    EXPECT_EQ(message.size(), ciphertext1.size());
2346
2347    string ciphertext2 = EncryptMessage(string(message), KM_MODE_ECB, KM_PAD_NONE);
2348    EXPECT_EQ(message.size(), ciphertext2.size());
2349
2350    // ECB is deterministic.
2351    EXPECT_EQ(ciphertext1, ciphertext2);
2352
2353    string plaintext = DecryptMessage(ciphertext1, KM_MODE_ECB, KM_PAD_NONE);
2354    EXPECT_EQ(message, plaintext);
2355
2356    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2357}
2358
2359TEST_P(EncryptionOperationsTest, AesEcbNotAuthorized) {
2360    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2361                                           .AesEncryptionKey(128)
2362                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2363                                           .Padding(KM_PAD_NONE)));
2364    // Two-block message.
2365    string message = "12345678901234567890123456789012";
2366    AuthorizationSet begin_params(client_params());
2367    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2368    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2369    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_BLOCK_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2370
2371    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2372}
2373
2374TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2375    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2376                                           .AesEncryptionKey(128)
2377                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2378                                           .Padding(KM_PAD_NONE)));
2379    // Message is slightly shorter than two blocks.
2380    string message = "1234567890123456789012345678901";
2381
2382    AuthorizationSet begin_params(client_params());
2383    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2384    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2385    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2386    string ciphertext;
2387    size_t input_consumed;
2388    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(message, &ciphertext, &input_consumed));
2389    EXPECT_EQ(message.size(), input_consumed);
2390    EXPECT_EQ(KM_ERROR_INVALID_INPUT_LENGTH, FinishOperation(&ciphertext));
2391
2392    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2393}
2394
2395TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2396    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2397                                           .AesEncryptionKey(128)
2398                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2399                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2400
2401    // Try various message lengths; all should work.
2402    for (size_t i = 0; i < 32; ++i) {
2403        string message(i, 'a');
2404        string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2405        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2406        string plaintext = DecryptMessage(ciphertext, KM_MODE_ECB, KM_PAD_PKCS7);
2407        EXPECT_EQ(message, plaintext);
2408    }
2409
2410    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2411}
2412
2413TEST_P(EncryptionOperationsTest, AesEcbNoPaddingKeyWithPkcs7Padding) {
2414    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2415                                           .AesEncryptionKey(128)
2416                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2417                                           .Authorization(TAG_PADDING, KM_PAD_NONE)));
2418
2419    // Try various message lengths; all should fail.
2420    for (size_t i = 0; i < 32; ++i) {
2421        AuthorizationSet begin_params(client_params());
2422        begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2423        begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2424        EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE,
2425                  BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2426    }
2427
2428    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2429}
2430
2431TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2432    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2433                                           .AesEncryptionKey(128)
2434                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_ECB)
2435                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2436
2437    string message = "a";
2438    string ciphertext = EncryptMessage(message, KM_MODE_ECB, KM_PAD_PKCS7);
2439    EXPECT_EQ(16U, ciphertext.size());
2440    EXPECT_NE(ciphertext, message);
2441    ++ciphertext[ciphertext.size() / 2];
2442
2443    AuthorizationSet begin_params(client_params());
2444    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
2445    begin_params.push_back(TAG_PADDING, KM_PAD_PKCS7);
2446    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2447    string plaintext;
2448    size_t input_consumed;
2449    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext, &plaintext, &input_consumed));
2450    EXPECT_EQ(ciphertext.size(), input_consumed);
2451    EXPECT_EQ(KM_ERROR_INVALID_ARGUMENT, FinishOperation(&plaintext));
2452
2453    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2454}
2455
2456TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2457    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2458                                           .AesEncryptionKey(128)
2459                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2460                                           .Padding(KM_PAD_NONE)));
2461    string message = "123";
2462    string iv1;
2463    string ciphertext1 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv1);
2464    EXPECT_EQ(message.size(), ciphertext1.size());
2465    EXPECT_EQ(16U, iv1.size());
2466
2467    string iv2;
2468    string ciphertext2 = EncryptMessage(message, KM_MODE_CTR, KM_PAD_NONE, &iv2);
2469    EXPECT_EQ(message.size(), ciphertext2.size());
2470    EXPECT_EQ(16U, iv2.size());
2471
2472    // IVs should be random, so ciphertexts should differ.
2473    EXPECT_NE(iv1, iv2);
2474    EXPECT_NE(ciphertext1, ciphertext2);
2475
2476    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CTR, KM_PAD_NONE, iv1);
2477    EXPECT_EQ(message, plaintext);
2478
2479    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2480}
2481
2482TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
2483    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2484                                           .AesEncryptionKey(128)
2485                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2486                                           .Padding(KM_PAD_NONE)));
2487
2488    int increment = 15;
2489    string message(239, 'a');
2490    AuthorizationSet input_params(client_params());
2491    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2492    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2493    AuthorizationSet output_params;
2494    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2495
2496    string ciphertext;
2497    size_t input_consumed;
2498    for (size_t i = 0; i < message.size(); i += increment)
2499        EXPECT_EQ(KM_ERROR_OK,
2500                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2501    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2502    EXPECT_EQ(message.size(), ciphertext.size());
2503
2504    // Move TAG_NONCE into input_params
2505    input_params.Reinitialize(output_params);
2506    input_params.push_back(client_params());
2507    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2508    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2509    output_params.Clear();
2510
2511    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2512    string plaintext;
2513    for (size_t i = 0; i < ciphertext.size(); i += increment)
2514        EXPECT_EQ(KM_ERROR_OK,
2515                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2516    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2517    EXPECT_EQ(ciphertext.size(), plaintext.size());
2518    EXPECT_EQ(message, plaintext);
2519
2520    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2521}
2522
2523struct AesCtrSp80038aTestVector {
2524    const char* key;
2525    const char* nonce;
2526    const char* plaintext;
2527    const char* ciphertext;
2528};
2529
2530// These test vectors are taken from
2531// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2532static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2533    // AES-128
2534    {
2535        "2b7e151628aed2a6abf7158809cf4f3c", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2536        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2537        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2538        "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2539        "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2540    },
2541    // AES-192
2542    {
2543        "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b", "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2544        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2545        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2546        "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
2547        "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
2548    },
2549    // AES-256
2550    {
2551        "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
2552        "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2553        "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2554        "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2555        "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
2556        "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
2557    },
2558};
2559
2560TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
2561    for (size_t i = 0; i < 3; i++) {
2562        const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
2563        const string key = hex2str(test.key);
2564        const string nonce = hex2str(test.nonce);
2565        const string plaintext = hex2str(test.plaintext);
2566        const string ciphertext = hex2str(test.ciphertext);
2567        CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
2568    }
2569
2570    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2571}
2572
2573TEST_P(EncryptionOperationsTest, AesCtrInvalidPaddingMode) {
2574    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2575                                           .AesEncryptionKey(128)
2576                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2577                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2578    AuthorizationSet begin_params(client_params());
2579    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2580    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2581    EXPECT_EQ(KM_ERROR_INCOMPATIBLE_PADDING_MODE, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
2582
2583    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2584}
2585
2586TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
2587    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2588                                           .AesEncryptionKey(128)
2589                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CTR)
2590                                           .Authorization(TAG_CALLER_NONCE)
2591                                           .Padding(KM_PAD_NONE)));
2592
2593    AuthorizationSet input_params(client_params());
2594    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CTR);
2595    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2596    input_params.push_back(TAG_NONCE, "123", 3);
2597    EXPECT_EQ(KM_ERROR_INVALID_NONCE, BeginOperation(KM_PURPOSE_ENCRYPT, input_params));
2598
2599    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2600}
2601
2602TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
2603    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2604                                           .AesEncryptionKey(128)
2605                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2606                                           .Padding(KM_PAD_NONE)));
2607    // Two-block message.
2608    string message = "12345678901234567890123456789012";
2609    string iv1;
2610    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2611    EXPECT_EQ(message.size(), ciphertext1.size());
2612
2613    string iv2;
2614    string ciphertext2 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv2);
2615    EXPECT_EQ(message.size(), ciphertext2.size());
2616
2617    // IVs should be random, so ciphertexts should differ.
2618    EXPECT_NE(iv1, iv2);
2619    EXPECT_NE(ciphertext1, ciphertext2);
2620
2621    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2622    EXPECT_EQ(message, plaintext);
2623
2624    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2625}
2626
2627TEST_P(EncryptionOperationsTest, AesCallerNonce) {
2628    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2629                                           .AesEncryptionKey(128)
2630                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2631                                           .Authorization(TAG_CALLER_NONCE)
2632                                           .Padding(KM_PAD_NONE)));
2633    string message = "12345678901234567890123456789012";
2634    string iv1;
2635    // Don't specify nonce, should get a random one.
2636    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2637    EXPECT_EQ(message.size(), ciphertext1.size());
2638    EXPECT_EQ(16U, iv1.size());
2639
2640    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2641    EXPECT_EQ(message, plaintext);
2642
2643    // Now specify a nonce, should also work.
2644    AuthorizationSet input_params(client_params());
2645    AuthorizationSet update_params;
2646    AuthorizationSet output_params;
2647    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2648    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2649    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2650    string ciphertext2 =
2651        ProcessMessage(KM_PURPOSE_ENCRYPT, message, input_params, update_params, &output_params);
2652
2653    // Decrypt with correct nonce.
2654    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2655                               &output_params);
2656    EXPECT_EQ(message, plaintext);
2657
2658    // Now try with wrong nonce.
2659    input_params.Reinitialize(client_params());
2660    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2661    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2662    input_params.push_back(TAG_NONCE, "aaaaaaaaaaaaaaaa", 16);
2663    plaintext = ProcessMessage(KM_PURPOSE_DECRYPT, ciphertext2, input_params, update_params,
2664                               &output_params);
2665    EXPECT_NE(message, plaintext);
2666
2667    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2668}
2669
2670TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
2671    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2672                                           .AesEncryptionKey(128)
2673                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2674                                           .Padding(KM_PAD_NONE)));
2675
2676    string message = "12345678901234567890123456789012";
2677    string iv1;
2678    // Don't specify nonce, should get a random one.
2679    string ciphertext1 = EncryptMessage(message, KM_MODE_CBC, KM_PAD_NONE, &iv1);
2680    EXPECT_EQ(message.size(), ciphertext1.size());
2681    EXPECT_EQ(16U, iv1.size());
2682
2683    string plaintext = DecryptMessage(ciphertext1, KM_MODE_CBC, KM_PAD_NONE, iv1);
2684    EXPECT_EQ(message, plaintext);
2685
2686    // Now specify a nonce, should fail.
2687    AuthorizationSet input_params(client_params());
2688    AuthorizationSet update_params;
2689    AuthorizationSet output_params;
2690    input_params.push_back(TAG_NONCE, "abcdefghijklmnop", 16);
2691    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2692    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2693
2694    EXPECT_EQ(KM_ERROR_CALLER_NONCE_PROHIBITED,
2695              BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2696
2697    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2698}
2699
2700TEST_P(EncryptionOperationsTest, AesCbcIncrementalNoPadding) {
2701    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2702                                           .AesEncryptionKey(128)
2703                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2704                                           .Padding(KM_PAD_NONE)));
2705
2706    int increment = 15;
2707    string message(240, 'a');
2708    AuthorizationSet input_params(client_params());
2709    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2710    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2711    AuthorizationSet output_params;
2712    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, input_params, &output_params));
2713
2714    string ciphertext;
2715    size_t input_consumed;
2716    for (size_t i = 0; i < message.size(); i += increment)
2717        EXPECT_EQ(KM_ERROR_OK,
2718                  UpdateOperation(message.substr(i, increment), &ciphertext, &input_consumed));
2719    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2720    EXPECT_EQ(message.size(), ciphertext.size());
2721
2722    // Move TAG_NONCE into input_params
2723    input_params.Reinitialize(output_params);
2724    input_params.push_back(client_params());
2725    input_params.push_back(TAG_BLOCK_MODE, KM_MODE_CBC);
2726    input_params.push_back(TAG_PADDING, KM_PAD_NONE);
2727    output_params.Clear();
2728
2729    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, input_params, &output_params));
2730    string plaintext;
2731    for (size_t i = 0; i < ciphertext.size(); i += increment)
2732        EXPECT_EQ(KM_ERROR_OK,
2733                  UpdateOperation(ciphertext.substr(i, increment), &plaintext, &input_consumed));
2734    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2735    EXPECT_EQ(ciphertext.size(), plaintext.size());
2736    EXPECT_EQ(message, plaintext);
2737
2738    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2739}
2740
2741TEST_P(EncryptionOperationsTest, AesCbcPkcs7Padding) {
2742    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2743                                           .AesEncryptionKey(128)
2744                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_CBC)
2745                                           .Authorization(TAG_PADDING, KM_PAD_PKCS7)));
2746
2747    // Try various message lengths; all should work.
2748    for (size_t i = 0; i < 32; ++i) {
2749        string message(i, 'a');
2750        string iv;
2751        string ciphertext = EncryptMessage(message, KM_MODE_CBC, KM_PAD_PKCS7, &iv);
2752        EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2753        string plaintext = DecryptMessage(ciphertext, KM_MODE_CBC, KM_PAD_PKCS7, iv);
2754        EXPECT_EQ(message, plaintext);
2755    }
2756
2757    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2758}
2759
2760TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
2761    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2762                                           .AesEncryptionKey(128)
2763                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2764                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2765                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2766    string aad = "foobar";
2767    string message = "123456789012345678901234567890123456";
2768    AuthorizationSet begin_params(client_params());
2769    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2770    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2771    begin_params.push_back(TAG_MAC_LENGTH, 128);
2772
2773    AuthorizationSet update_params;
2774    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2775
2776    // Encrypt
2777    AuthorizationSet begin_out_params;
2778    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2779    string ciphertext;
2780    size_t input_consumed;
2781    AuthorizationSet update_out_params;
2782    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2783                                           &input_consumed));
2784    EXPECT_EQ(message.size(), input_consumed);
2785    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2786
2787    // Grab nonce
2788    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2789    begin_params.push_back(begin_out_params);
2790
2791    // Decrypt.
2792    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2793    string plaintext;
2794    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2795                                           &plaintext, &input_consumed));
2796    EXPECT_EQ(ciphertext.size(), input_consumed);
2797    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2798
2799    EXPECT_EQ(message, plaintext);
2800    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2801}
2802
2803TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
2804    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2805                                           .AesEncryptionKey(128)
2806                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2807                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2808                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2809    string aad = "foobar";
2810    string message = "123456789012345678901234567890123456";
2811    AuthorizationSet begin_params(client_params());
2812    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2813    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2814    begin_params.push_back(TAG_MAC_LENGTH, 96);
2815
2816    AuthorizationSet update_params;
2817    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2818
2819    AuthorizationSet begin_out_params;
2820    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH,
2821              BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2822
2823    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2824}
2825
2826TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
2827    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2828                                           .AesEncryptionKey(128)
2829                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2830                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2831                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2832    string aad = "foobar";
2833    string message = "123456789012345678901234567890123456";
2834    AuthorizationSet begin_params(client_params());
2835    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2836    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2837    begin_params.push_back(TAG_MAC_LENGTH, 128);
2838
2839    AuthorizationSet update_params;
2840    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2841
2842    // Encrypt
2843    AuthorizationSet begin_out_params;
2844    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2845    string ciphertext;
2846    size_t input_consumed;
2847    AuthorizationSet update_out_params;
2848    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
2849                                           &input_consumed));
2850    EXPECT_EQ(message.size(), input_consumed);
2851    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2852
2853    // Grab nonce
2854    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2855    begin_params.Reinitialize(client_params());
2856    begin_params.push_back(begin_out_params);
2857    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2858    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2859    begin_params.push_back(TAG_MAC_LENGTH, 96);
2860
2861    // Decrypt.
2862    EXPECT_EQ(KM_ERROR_INVALID_MAC_LENGTH, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2863
2864    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2865}
2866
2867TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
2868    uint8_t nonce[] = {
2869        0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
2870    };
2871    uint8_t ciphertext[] = {
2872        0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc, 0xd2, 0xcb, 0x16,
2873        0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78, 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a,
2874        0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d, 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76,
2875        0x76, 0x5e, 0xfb, 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
2876        0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
2877    };
2878    string ciphertext_str(reinterpret_cast<char*>(ciphertext), sizeof(ciphertext));
2879
2880    AuthorizationSet begin_params(client_params());
2881    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2882    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2883    begin_params.push_back(TAG_MAC_LENGTH, 128);
2884    begin_params.push_back(TAG_NONCE, nonce, sizeof(nonce));
2885
2886    string plaintext;
2887    size_t input_consumed;
2888
2889    // Import correct key and decrypt
2890    uint8_t good_key[] = {
2891        0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
2892        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
2893    };
2894    string good_key_str(reinterpret_cast<char*>(good_key), sizeof(good_key));
2895    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
2896                                         .AesEncryptionKey(128)
2897                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2898                                         .Authorization(TAG_PADDING, KM_PAD_NONE)
2899                                         .Authorization(TAG_CALLER_NONCE)
2900                                         .Authorization(TAG_MIN_MAC_LENGTH, 128),
2901                                     KM_KEY_FORMAT_RAW, good_key_str));
2902    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2903    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
2904    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2905
2906    // Import bad key and decrypt
2907    uint8_t bad_key[] = {
2908        0xbb, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
2909        0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
2910    };
2911    string bad_key_str(reinterpret_cast<char*>(bad_key), sizeof(bad_key));
2912    ASSERT_EQ(KM_ERROR_OK, ImportKey(AuthorizationSetBuilder()
2913                                         .AesEncryptionKey(128)
2914                                         .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2915                                         .Authorization(TAG_PADDING, KM_PAD_NONE)
2916                                         .Authorization(TAG_MIN_MAC_LENGTH, 128),
2917                                     KM_KEY_FORMAT_RAW, bad_key_str));
2918    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2919    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(ciphertext_str, &plaintext, &input_consumed));
2920    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
2921
2922    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2923}
2924
2925TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
2926    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2927                                           .AesEncryptionKey(128)
2928                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2929                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2930                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2931    string aad = "123456789012345678";
2932    string empty_message;
2933    AuthorizationSet begin_params(client_params());
2934    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2935    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2936    begin_params.push_back(TAG_MAC_LENGTH, 128);
2937
2938    AuthorizationSet update_params;
2939    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
2940
2941    // Encrypt
2942    AuthorizationSet begin_out_params;
2943    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2944    string ciphertext;
2945    size_t input_consumed;
2946    AuthorizationSet update_out_params;
2947    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, empty_message, &update_out_params,
2948                                           &ciphertext, &input_consumed));
2949    EXPECT_EQ(0U, input_consumed);
2950    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
2951
2952    // Grab nonce
2953    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
2954    begin_params.push_back(begin_out_params);
2955
2956    // Decrypt.
2957    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
2958    string plaintext;
2959    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
2960                                           &plaintext, &input_consumed));
2961    EXPECT_EQ(ciphertext.size(), input_consumed);
2962    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
2963
2964    EXPECT_EQ(empty_message, plaintext);
2965    EXPECT_EQ(0, GetParam()->keymaster0_calls());
2966}
2967
2968TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
2969    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
2970                                           .AesEncryptionKey(128)
2971                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
2972                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
2973                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2974    AuthorizationSet begin_params(client_params());
2975    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
2976    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
2977    begin_params.push_back(TAG_MAC_LENGTH, 128);
2978
2979    AuthorizationSet update_params;
2980    update_params.push_back(TAG_ASSOCIATED_DATA, "b", 1);
2981
2982    // Encrypt
2983    AuthorizationSet begin_out_params;
2984    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
2985    string ciphertext;
2986    size_t input_consumed;
2987    AuthorizationSet update_out_params;
2988
2989    // Send AAD, incrementally
2990    for (int i = 0; i < 1000; ++i) {
2991        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &ciphertext,
2992                                               &input_consumed));
2993        EXPECT_EQ(0U, input_consumed);
2994        EXPECT_EQ(0U, ciphertext.size());
2995    }
2996
2997    // Now send data, incrementally, no data.
2998    AuthorizationSet empty_params;
2999    for (int i = 0; i < 1000; ++i) {
3000        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, "a", &update_out_params, &ciphertext,
3001                                               &input_consumed));
3002        EXPECT_EQ(1U, input_consumed);
3003    }
3004    EXPECT_EQ(1000U, ciphertext.size());
3005
3006    // And finish.
3007    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3008    EXPECT_EQ(1016U, ciphertext.size());
3009
3010    // Grab nonce
3011    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3012    begin_params.push_back(begin_out_params);
3013
3014    // Decrypt.
3015    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3016    string plaintext;
3017
3018    // Send AAD, incrementally, no data
3019    for (int i = 0; i < 1000; ++i) {
3020        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "", &update_out_params, &plaintext,
3021                                               &input_consumed));
3022        EXPECT_EQ(0U, input_consumed);
3023        EXPECT_EQ(0U, plaintext.size());
3024    }
3025
3026    // Now send data, incrementally.
3027    for (size_t i = 0; i < ciphertext.length(); ++i) {
3028        EXPECT_EQ(KM_ERROR_OK, UpdateOperation(empty_params, string(ciphertext.data() + i, 1),
3029                                               &update_out_params, &plaintext, &input_consumed));
3030        EXPECT_EQ(1U, input_consumed);
3031    }
3032    EXPECT_EQ(1000U, plaintext.size());
3033    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3034
3035    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3036}
3037
3038TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3039    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3040                                           .AesEncryptionKey(128)
3041                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3042                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3043                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3044    string message = "123456789012345678901234567890123456";
3045    AuthorizationSet begin_params(client_params());
3046    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3047    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3048    begin_params.push_back(TAG_MAC_LENGTH, 128);
3049    AuthorizationSet begin_out_params;
3050
3051    AuthorizationSet update_params;
3052    update_params.push_back(TAG_ASSOCIATED_DATA, "foo", 3);
3053
3054    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3055
3056    // No data, AAD only.
3057    string ciphertext;
3058    size_t input_consumed;
3059    AuthorizationSet update_out_params;
3060    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, "" /* message */, &update_out_params,
3061                                           &ciphertext, &input_consumed));
3062    EXPECT_EQ(0U, input_consumed);
3063
3064    // AAD and data.
3065    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3066                                           &input_consumed));
3067    EXPECT_EQ(message.size(), input_consumed);
3068    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3069
3070    // Grab nonce.
3071    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3072    begin_params.push_back(begin_out_params);
3073
3074    // Decrypt
3075    update_params.Clear();
3076    update_params.push_back(TAG_ASSOCIATED_DATA, "foofoo", 6);
3077
3078    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params));
3079    string plaintext;
3080    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3081                                           &plaintext, &input_consumed));
3082    EXPECT_EQ(ciphertext.size(), input_consumed);
3083    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&plaintext));
3084
3085    EXPECT_EQ(message, plaintext);
3086    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3087}
3088
3089TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3090    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3091                                           .AesEncryptionKey(128)
3092                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3093                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3094                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3095    string message = "12345678901234567890123456789012";
3096    AuthorizationSet begin_params(client_params());
3097    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3098    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3099    begin_params.push_back(TAG_MAC_LENGTH, 128);
3100
3101    AuthorizationSet update_params;
3102    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3103
3104    AuthorizationSet finish_params;
3105    AuthorizationSet finish_out_params;
3106
3107    // Encrypt
3108    AuthorizationSet begin_out_params;
3109    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3110    AuthorizationSet update_out_params;
3111    string ciphertext;
3112    size_t input_consumed;
3113    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3114                                           &input_consumed));
3115    EXPECT_EQ(message.size(), input_consumed);
3116    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3117
3118    // Grab nonce
3119    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3120    begin_params.push_back(begin_out_params);
3121
3122    update_params.Clear();
3123    update_params.push_back(TAG_ASSOCIATED_DATA, "barfoo" /* Wrong AAD */, 6);
3124
3125    // Decrypt.
3126    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3127    string plaintext;
3128    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3129                                           &plaintext, &input_consumed));
3130    EXPECT_EQ(ciphertext.size(), input_consumed);
3131    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3132
3133    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3134}
3135
3136TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3137    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3138                                           .AesEncryptionKey(128)
3139                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3140                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3141                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3142    string message = "12345678901234567890123456789012";
3143    AuthorizationSet begin_params(client_params());
3144    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3145    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3146    begin_params.push_back(TAG_MAC_LENGTH, 128);
3147
3148    AuthorizationSet update_params;
3149    update_params.push_back(TAG_ASSOCIATED_DATA, "foobar", 6);
3150
3151    // Encrypt
3152    AuthorizationSet begin_out_params;
3153    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3154    AuthorizationSet update_out_params;
3155    string ciphertext;
3156    size_t input_consumed;
3157    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3158                                           &input_consumed));
3159    EXPECT_EQ(message.size(), input_consumed);
3160    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3161
3162    begin_params.push_back(TAG_NONCE, "123456789012", 12);
3163
3164    // Decrypt
3165    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3166    string plaintext;
3167    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3168                                           &plaintext, &input_consumed));
3169    EXPECT_EQ(ciphertext.size(), input_consumed);
3170    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3171
3172    // With wrong nonce, should have gotten garbage plaintext.
3173    EXPECT_NE(message, plaintext);
3174    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3175}
3176
3177TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3178    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3179                                           .AesEncryptionKey(128)
3180                                           .Authorization(TAG_BLOCK_MODE, KM_MODE_GCM)
3181                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3182                                           .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3183    string aad = "foobar";
3184    string message = "123456789012345678901234567890123456";
3185    AuthorizationSet begin_params(client_params());
3186    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_GCM);
3187    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3188    begin_params.push_back(TAG_MAC_LENGTH, 128);
3189    AuthorizationSet begin_out_params;
3190
3191    AuthorizationSet update_params;
3192    update_params.push_back(TAG_ASSOCIATED_DATA, aad.data(), aad.size());
3193
3194    // Encrypt
3195    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params, &begin_out_params));
3196    AuthorizationSet update_out_params;
3197    string ciphertext;
3198    size_t input_consumed;
3199    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, message, &update_out_params, &ciphertext,
3200                                           &input_consumed));
3201    EXPECT_EQ(message.size(), input_consumed);
3202    EXPECT_EQ(KM_ERROR_OK, FinishOperation(&ciphertext));
3203
3204    // Corrupt tag
3205    (*ciphertext.rbegin())++;
3206
3207    // Grab nonce.
3208    EXPECT_NE(-1, begin_out_params.find(TAG_NONCE));
3209    begin_params.push_back(begin_out_params);
3210
3211    // Decrypt.
3212    EXPECT_EQ(KM_ERROR_OK, BeginOperation(KM_PURPOSE_DECRYPT, begin_params, &begin_out_params));
3213    string plaintext;
3214    EXPECT_EQ(KM_ERROR_OK, UpdateOperation(update_params, ciphertext, &update_out_params,
3215                                           &plaintext, &input_consumed));
3216    EXPECT_EQ(ciphertext.size(), input_consumed);
3217    EXPECT_EQ(KM_ERROR_VERIFICATION_FAILED, FinishOperation(&plaintext));
3218
3219    EXPECT_EQ(message, plaintext);
3220    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3221}
3222
3223typedef Keymaster2Test MaxOperationsTest;
3224INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, MaxOperationsTest, test_params);
3225
3226TEST_P(MaxOperationsTest, TestLimit) {
3227    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3228                                           .AesEncryptionKey(128)
3229                                           .EcbMode()
3230                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3231                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3232
3233    string message = "1234567890123456";
3234    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3235    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3236    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3237
3238    // Fourth time should fail.
3239    AuthorizationSet begin_params(client_params());
3240    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3241    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3242    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3243
3244    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3245}
3246
3247TEST_P(MaxOperationsTest, TestAbort) {
3248    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3249                                           .AesEncryptionKey(128)
3250                                           .EcbMode()
3251                                           .Authorization(TAG_PADDING, KM_PAD_NONE)
3252                                           .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
3253
3254    string message = "1234567890123456";
3255    string ciphertext1 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3256    string ciphertext2 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3257    string ciphertext3 = EncryptMessage(message, KM_MODE_ECB, KM_PAD_NONE);
3258
3259    // Fourth time should fail.
3260    AuthorizationSet begin_params(client_params());
3261    begin_params.push_back(TAG_BLOCK_MODE, KM_MODE_ECB);
3262    begin_params.push_back(TAG_PADDING, KM_PAD_NONE);
3263    EXPECT_EQ(KM_ERROR_KEY_MAX_OPS_EXCEEDED, BeginOperation(KM_PURPOSE_ENCRYPT, begin_params));
3264
3265    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3266}
3267
3268typedef Keymaster2Test AddEntropyTest;
3269INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AddEntropyTest, test_params);
3270
3271TEST_P(AddEntropyTest, AddEntropy) {
3272    // There's no obvious way to test that entropy is actually added, but we can test that the API
3273    // doesn't blow up or return an error.
3274    EXPECT_EQ(KM_ERROR_OK,
3275              device()->add_rng_entropy(device(), reinterpret_cast<const uint8_t*>("foo"), 3));
3276
3277    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3278}
3279
3280typedef Keymaster2Test Keymaster0AdapterTest;
3281INSTANTIATE_TEST_CASE_P(
3282    AndroidKeymasterTest, Keymaster0AdapterTest,
3283    ::testing::Values(
3284        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(true /* support_ec */)),
3285        InstanceCreatorPtr(new Keymaster0AdapterTestInstanceCreator(false /* support_ec */))));
3286
3287TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1RsaBlob) {
3288    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
3289    // key data.
3290    string km1_sw = read_file("km1_sw_rsa_512.blob");
3291    EXPECT_EQ(486U, km1_sw.length());
3292
3293    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3294    memcpy(key_data, km1_sw.data(), km1_sw.length());
3295    set_key_blob(key_data, km1_sw.length());
3296
3297    string message(64, 'a');
3298    string signature;
3299    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3300
3301    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3302}
3303
3304TEST_P(Keymaster0AdapterTest, UnversionedSoftwareKeymaster1RsaBlob) {
3305    // Load and use an old-style Keymaster1 software key blob, without the version byte.  These
3306    // blobs contain OCB-encrypted key data.
3307    string km1_sw = read_file("km1_sw_rsa_512_unversioned.blob");
3308    EXPECT_EQ(477U, km1_sw.length());
3309
3310    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3311    memcpy(key_data, km1_sw.data(), km1_sw.length());
3312    set_key_blob(key_data, km1_sw.length());
3313
3314    string message(64, 'a');
3315    string signature;
3316    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3317
3318    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3319}
3320
3321TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster1EcdsaBlob) {
3322    // Load and use an old-style Keymaster1 software key blob.  These blobs contain OCB-encrypted
3323    // key data.
3324    string km1_sw = read_file("km1_sw_ecdsa_256.blob");
3325    EXPECT_EQ(270U, km1_sw.length());
3326
3327    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km1_sw.length()));
3328    memcpy(key_data, km1_sw.data(), km1_sw.length());
3329    set_key_blob(key_data, km1_sw.length());
3330
3331    string message(32, static_cast<char>(0xFF));
3332    string signature;
3333    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3334
3335    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3336}
3337
3338struct Malloc_Delete {
3339    void operator()(void* p) { free(p); }
3340};
3341
3342TEST_P(Keymaster0AdapterTest, OldSoftwareKeymaster0RsaBlob) {
3343    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3344    string km0_sw = read_file("km0_sw_rsa_512.blob");
3345    EXPECT_EQ(333U, km0_sw.length());
3346
3347    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3348    memcpy(key_data, km0_sw.data(), km0_sw.length());
3349    set_key_blob(key_data, km0_sw.length());
3350
3351    string message(64, 'a');
3352    string signature;
3353    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3354
3355    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3356}
3357
3358TEST_P(Keymaster0AdapterTest, OldSwKeymaster0RsaBlobGetCharacteristics) {
3359    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3360    string km0_sw = read_file("km0_sw_rsa_512.blob");
3361    EXPECT_EQ(333U, km0_sw.length());
3362
3363    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3364    memcpy(key_data, km0_sw.data(), km0_sw.length());
3365    set_key_blob(key_data, km0_sw.length());
3366
3367    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
3368    EXPECT_TRUE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3369    EXPECT_TRUE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
3370    EXPECT_TRUE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3371    EXPECT_TRUE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3372    EXPECT_TRUE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
3373    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
3374    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
3375    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
3376    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
3377
3378    EXPECT_EQ(0, GetParam()->keymaster0_calls());
3379}
3380
3381TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlob) {
3382    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3383    string km0_sw = read_file("km0_sw_rsa_512.blob");
3384    EXPECT_EQ(333U, km0_sw.length());
3385
3386    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3387    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3388    EXPECT_EQ('P', km0_sw[0]);
3389    km0_sw[0] = 'Q';
3390
3391    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3392    memcpy(key_data, km0_sw.data(), km0_sw.length());
3393    set_key_blob(key_data, km0_sw.length());
3394
3395    string message(64, 'a');
3396    string signature;
3397    SignMessage(message, &signature, KM_DIGEST_NONE, KM_PAD_NONE);
3398    VerifyMessage(message, signature, KM_DIGEST_NONE, KM_PAD_NONE);
3399
3400    EXPECT_EQ(5, GetParam()->keymaster0_calls());
3401}
3402
3403TEST_P(Keymaster0AdapterTest, OldHwKeymaster0RsaBlobGetCharacteristics) {
3404    // Load and use an old softkeymaster blob.  These blobs contain PKCS#8 key data.
3405    string km0_sw = read_file("km0_sw_rsa_512.blob");
3406    EXPECT_EQ(333U, km0_sw.length());
3407
3408    // The keymaster0 wrapper swaps the old softkeymaster leading 'P' for a 'Q' to make the key not
3409    // be recognized as a software key.  Do the same here to pretend this is a hardware key.
3410    EXPECT_EQ('P', km0_sw[0]);
3411    km0_sw[0] = 'Q';
3412
3413    uint8_t* key_data = reinterpret_cast<uint8_t*>(malloc(km0_sw.length()));
3414    memcpy(key_data, km0_sw.data(), km0_sw.length());
3415    set_key_blob(key_data, km0_sw.length());
3416
3417    EXPECT_EQ(KM_ERROR_OK, GetCharacteristics());
3418    EXPECT_TRUE(contains(hw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3419    EXPECT_TRUE(contains(hw_enforced(), TAG_KEY_SIZE, 512));
3420    EXPECT_TRUE(contains(hw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3421    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3422    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_MD5));
3423    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA1));
3424    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_224));
3425    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_256));
3426    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_384));
3427    EXPECT_TRUE(contains(hw_enforced(), TAG_DIGEST, KM_DIGEST_SHA_2_512));
3428    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_NONE));
3429    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_ENCRYPT));
3430    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PKCS1_1_5_SIGN));
3431    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_OAEP));
3432    EXPECT_TRUE(contains(hw_enforced(), TAG_PADDING, KM_PAD_RSA_PSS));
3433    EXPECT_EQ(15U, hw_enforced().size());
3434
3435    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_SIGN));
3436    EXPECT_TRUE(contains(sw_enforced(), TAG_PURPOSE, KM_PURPOSE_VERIFY));
3437    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_ALL_USERS));
3438    EXPECT_TRUE(sw_enforced().GetTagValue(TAG_NO_AUTH_REQUIRED));
3439
3440    EXPECT_FALSE(contains(sw_enforced(), TAG_ALGORITHM, KM_ALGORITHM_RSA));
3441    EXPECT_FALSE(contains(sw_enforced(), TAG_KEY_SIZE, 512));
3442    EXPECT_FALSE(contains(sw_enforced(), TAG_RSA_PUBLIC_EXPONENT, 3));
3443    EXPECT_FALSE(contains(sw_enforced(), TAG_DIGEST, KM_DIGEST_NONE));
3444    EXPECT_FALSE(contains(sw_enforced(), TAG_PADDING, KM_PAD_NONE));
3445
3446    EXPECT_EQ(1, GetParam()->keymaster0_calls());
3447}
3448
3449typedef Keymaster2Test AttestationTest;
3450INSTANTIATE_TEST_CASE_P(AndroidKeymasterTest, AttestationTest, test_params);
3451
3452static X509* parse_cert_blob(const keymaster_blob_t& blob) {
3453    const uint8_t* p = blob.data;
3454    return d2i_X509(nullptr, &p, blob.data_length);
3455}
3456
3457static bool verify_chain(const keymaster_cert_chain_t& chain) {
3458    for (size_t i = 0; i < chain.entry_count - 1; ++i) {
3459        keymaster_blob_t& key_cert_blob = chain.entries[i];
3460        keymaster_blob_t& signing_cert_blob = chain.entries[i + 1];
3461
3462        X509_Ptr key_cert(parse_cert_blob(key_cert_blob));
3463        X509_Ptr signing_cert(parse_cert_blob(signing_cert_blob));
3464        EXPECT_TRUE(!!key_cert.get() && !!signing_cert.get());
3465        if (!key_cert.get() || !signing_cert.get())
3466            return false;
3467
3468        EVP_PKEY_Ptr signing_pubkey(X509_get_pubkey(signing_cert.get()));
3469        EXPECT_TRUE(!!signing_pubkey.get());
3470        if (!signing_pubkey.get())
3471            return false;
3472
3473        EXPECT_EQ(1, X509_verify(key_cert.get(), signing_pubkey.get()))
3474            << "Verification of certificate " << i << " failed";
3475    }
3476
3477    return true;
3478}
3479
3480// Extract attestation record from cert. Returned object is still part of cert; don't free it
3481// separately.
3482static ASN1_OCTET_STRING* get_attestation_record(X509* certificate) {
3483    ASN1_OBJECT_Ptr oid(OBJ_txt2obj(kAttestionRecordOid, 1 /* dotted string format */));
3484    EXPECT_TRUE(!!oid.get());
3485    if (!oid.get())
3486        return nullptr;
3487
3488    int location = X509_get_ext_by_OBJ(certificate, oid.get(), -1 /* search from beginning */);
3489    EXPECT_NE(-1, location);
3490    if (location == -1)
3491        return nullptr;
3492
3493    X509_EXTENSION* attest_rec_ext = X509_get_ext(certificate, location);
3494    EXPECT_TRUE(!!attest_rec_ext);
3495    if (!attest_rec_ext)
3496        return nullptr;
3497
3498    ASN1_OCTET_STRING* attest_rec = X509_EXTENSION_get_data(attest_rec_ext);
3499    EXPECT_TRUE(!!attest_rec);
3500    return attest_rec;
3501}
3502
3503static bool verify_attestation_record(AuthorizationSet expected_sw_enforced,
3504                                      AuthorizationSet expected_tee_enforced,
3505                                      const keymaster_blob_t& attestation_cert) {
3506
3507    X509_Ptr cert(parse_cert_blob(attestation_cert));
3508    EXPECT_TRUE(!!cert.get());
3509    if (!cert.get())
3510        return false;
3511
3512    ASN1_OCTET_STRING* attest_rec = get_attestation_record(cert.get());
3513    EXPECT_TRUE(!!attest_rec);
3514    if (!attest_rec)
3515        return false;
3516
3517    AuthorizationSet att_sw_enforced;
3518    AuthorizationSet att_tee_enforced;
3519    EXPECT_EQ(KM_ERROR_OK, parse_attestation_record(attest_rec->data, attest_rec->length,
3520                                                    &att_sw_enforced, &att_tee_enforced));
3521
3522    // Add TAG_USER_ID to the attestation sw-enforced list, because user IDs are not included in
3523    // attestations, since they're meaningless off-device.
3524    uint32_t user_id;
3525    if (expected_sw_enforced.GetTagValue(TAG_USER_ID, &user_id))
3526        att_sw_enforced.push_back(TAG_USER_ID, user_id);
3527    if (expected_tee_enforced.GetTagValue(TAG_USER_ID, &user_id))
3528        att_tee_enforced.push_back(TAG_USER_ID, user_id);
3529
3530    att_sw_enforced.Sort();
3531    expected_sw_enforced.Sort();
3532    EXPECT_EQ(expected_sw_enforced, att_sw_enforced);
3533
3534    att_tee_enforced.Sort();
3535    expected_tee_enforced.Sort();
3536    EXPECT_EQ(expected_tee_enforced, att_tee_enforced);
3537
3538    return true;
3539}
3540
3541TEST_P(AttestationTest, RsaSignedWithRsa) {
3542    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3543                                           .RsaSigningKey(256, 3)
3544                                           .Digest(KM_DIGEST_NONE)
3545                                           .Padding(KM_PAD_NONE)));
3546
3547    keymaster_cert_chain_t cert_chain;
3548    EXPECT_EQ(KM_ERROR_OK, AttestKey(KM_ALGORITHM_RSA, &cert_chain));
3549    EXPECT_EQ(3U, cert_chain.entry_count);
3550    EXPECT_TRUE(verify_chain(cert_chain));
3551    EXPECT_TRUE(verify_attestation_record(sw_enforced(), hw_enforced(), cert_chain.entries[0]));
3552
3553    keymaster_free_cert_chain(&cert_chain);
3554}
3555
3556TEST_P(AttestationTest, RsaSignedWithEc) {
3557    ASSERT_EQ(KM_ERROR_OK, GenerateKey(AuthorizationSetBuilder()
3558                                           .RsaSigningKey(256, 3)
3559                                           .Digest(KM_DIGEST_NONE)
3560                                           .Padding(KM_PAD_NONE)));
3561
3562    keymaster_cert_chain_t cert_chain;
3563    EXPECT_EQ(KM_ERROR_OK, AttestKey(KM_ALGORITHM_EC, &cert_chain));
3564    EXPECT_EQ(3U, cert_chain.entry_count);
3565    EXPECT_TRUE(verify_chain(cert_chain));
3566    EXPECT_TRUE(verify_attestation_record(sw_enforced(), hw_enforced(), cert_chain.entries[0]));
3567
3568    keymaster_free_cert_chain(&cert_chain);
3569}
3570
3571TEST(SoftKeymasterWrapperTest, CheckKeymaster2Device) {
3572    // Make a good fake device, and wrap it.
3573    SoftKeymasterDevice* good_fake(new SoftKeymasterDevice(new TestKeymasterContext));
3574
3575    // Wrap it and check it.
3576    SoftKeymasterDevice* good_fake_wrapper(new SoftKeymasterDevice(new TestKeymasterContext));
3577    good_fake_wrapper->SetHardwareDevice(good_fake->keymaster_device());
3578    EXPECT_TRUE(good_fake_wrapper->Keymaster1DeviceIsGood());
3579
3580    // Close and clean up wrapper and wrapped
3581    good_fake_wrapper->keymaster_device()->common.close(good_fake_wrapper->hw_device());
3582
3583    // Make a "bad" (doesn't support all digests) device;
3584    keymaster1_device_t* sha256_only_fake = make_device_sha256_only(
3585        (new SoftKeymasterDevice(new TestKeymasterContext("256")))->keymaster_device());
3586
3587    // Wrap it and check it.
3588    SoftKeymasterDevice* sha256_only_fake_wrapper(
3589        (new SoftKeymasterDevice(new TestKeymasterContext)));
3590    sha256_only_fake_wrapper->SetHardwareDevice(sha256_only_fake);
3591    EXPECT_FALSE(sha256_only_fake_wrapper->Keymaster1DeviceIsGood());
3592
3593    // Close and clean up wrapper and wrapped
3594    sha256_only_fake_wrapper->keymaster_device()->common.close(
3595        sha256_only_fake_wrapper->hw_device());
3596}
3597
3598}  // namespace test
3599}  // namespace keymaster
3600