summaryrefslogtreecommitdiff
path: root/android_keymaster/android_keymaster.cpp
blob: f4e1dd98ce587fe4ae2aae157158404c70af0ca4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
/*
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <keymaster/android_keymaster.h>

#include <utility>
#include <vector>

#include <assert.h>
#include <string.h>

#include <stddef.h>

#include <cppbor.h>
#include <cppbor_parse.h>

#include <keymaster/UniquePtr.h>
#include <keymaster/android_keymaster_utils.h>
#include <keymaster/attestation_context.h>
#include <keymaster/cppcose/cppcose.h>
#include <keymaster/key.h>
#include <keymaster/key_blob_utils/ae.h>
#include <keymaster/key_factory.h>
#include <keymaster/keymaster_context.h>
#include <keymaster/km_date.h>
#include <keymaster/km_openssl/openssl_err.h>
#include <keymaster/km_openssl/openssl_utils.h>
#include <keymaster/logger.h>
#include <keymaster/operation.h>
#include <keymaster/operation_table.h>
#include <keymaster/remote_provisioning_utils.h>
#include <keymaster/secure_deletion_secret_storage.h>

namespace keymaster {

namespace {

using cppcose::constructCoseEncrypt;
using cppcose::constructCoseMac0;
using cppcose::CoseKey;
using cppcose::EC2;
using cppcose::ES256;
using cppcose::generateCoseMac0Mac;
using cppcose::kAesGcmNonceLength;
using cppcose::P256;
using cppcose::x25519_HKDF_DeriveKey;

template <keymaster_tag_t T>
keymaster_error_t CheckPatchLevel(const AuthorizationSet& tee_enforced,
                                  const AuthorizationSet& sw_enforced, TypedTag<KM_UINT, T> tag,
                                  uint32_t current_patchlevel) {
    uint32_t key_patchlevel;
    if (tee_enforced.GetTagValue(tag, &key_patchlevel) ||
        sw_enforced.GetTagValue(tag, &key_patchlevel)) {
        if (key_patchlevel < current_patchlevel) {
            return KM_ERROR_KEY_REQUIRES_UPGRADE;
        } else if (key_patchlevel > current_patchlevel) {
            LOG_E("Key blob invalid! key patchlevel %lu is > current patchlevel %lu",
                  (unsigned long)key_patchlevel, (unsigned long)current_patchlevel);
            return KM_ERROR_INVALID_KEY_BLOB;
        }
    }
    return KM_ERROR_OK;
}

keymaster_error_t CheckVersionInfo(const AuthorizationSet& tee_enforced,
                                   const AuthorizationSet& sw_enforced,
                                   const KeymasterContext& context) {
    uint32_t os_version;
    uint32_t os_patchlevel;
    context.GetSystemVersion(&os_version, &os_patchlevel);

    keymaster_error_t err =
        CheckPatchLevel(tee_enforced, sw_enforced, TAG_OS_PATCHLEVEL, os_patchlevel);
    if (err != KM_ERROR_OK) return err;

    // Also check the vendor and boot patchlevels if available.
    auto vendor_patchlevel = context.GetVendorPatchlevel();
    if (vendor_patchlevel.has_value()) {
        err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_VENDOR_PATCHLEVEL,
                              vendor_patchlevel.value());
        if (err != KM_ERROR_OK) return err;
    }
    auto boot_patchlevel = context.GetBootPatchlevel();
    if (boot_patchlevel.has_value()) {
        err = CheckPatchLevel(tee_enforced, sw_enforced, TAG_BOOT_PATCHLEVEL,
                              boot_patchlevel.value());
        if (err != KM_ERROR_OK) return err;
    }

    return KM_ERROR_OK;
}

const keymaster_key_param_t kKeyMintEcdsaP256Params[] = {
    Authorization(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY),
    Authorization(TAG_ALGORITHM, KM_ALGORITHM_EC), Authorization(TAG_KEY_SIZE, 256),
    Authorization(TAG_DIGEST, KM_DIGEST_SHA_2_256), Authorization(TAG_EC_CURVE, KM_EC_CURVE_P_256),
    Authorization(TAG_NO_AUTH_REQUIRED),
    // The certificate generated by KM will be discarded, these values don't matter.
    Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0), Authorization(TAG_CERTIFICATE_NOT_AFTER, 0)};

cppcose::HmacSha256Function getMacFunction(bool test_mode,
                                           RemoteProvisioningContext* rem_prov_ctx) {
    if (test_mode) {
        return [](const cppcose::bytevec& input) {
            const cppcose::bytevec macKey(32);
            return cppcose::generateHmacSha256(macKey, input);
        };
    }

    return [rem_prov_ctx](const cppcose::bytevec& input) -> cppcose::ErrMsgOr<cppcose::HmacSha256> {
        auto mac = rem_prov_ctx->GenerateHmacSha256(input);
        if (!mac) {
            return "Remote provisioning context failed to sign MAC.";
        }
        return *mac;
    };
}

std::pair<const uint8_t*, size_t> blob2Pair(const keymaster_blob_t& blob) {
    return {blob.data, blob.data_length};
}

constexpr int kMaxChallengeSizeV2 = 64;
constexpr int kP256AffinePointSize = 32;
constexpr int kRoTVersion1 = 40001;

}  // anonymous namespace

AndroidKeymaster::AndroidKeymaster(KeymasterContext* context, size_t operation_table_size,
                                   int32_t message_version)
    : context_(context), operation_table_(new(std::nothrow) OperationTable(operation_table_size)),
      message_version_(message_version) {}

AndroidKeymaster::~AndroidKeymaster() {}

AndroidKeymaster::AndroidKeymaster(AndroidKeymaster&& other)
    : context_(std::move(other.context_)), operation_table_(std::move(other.operation_table_)),
      message_version_(other.message_version_) {}

// TODO(swillden): Unify support analysis.  Right now, we have per-keytype methods that determine if
// specific modes, padding, etc. are supported for that key type, and AndroidKeymaster also has
// methods that return the same information.  They'll get out of sync.  Best to put the knowledge in
// the keytypes and provide some mechanism for AndroidKeymaster to query the keytypes for the
// information.

template <typename T>
bool check_supported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
                     SupportedResponse<T>* response) {
    if (context.GetKeyFactory(algorithm) == nullptr) {
        response->error = KM_ERROR_UNSUPPORTED_ALGORITHM;
        return false;
    }
    return true;
}

void AndroidKeymaster::GetVersion(const GetVersionRequest&, GetVersionResponse* rsp) {
    if (rsp == nullptr) return;

    rsp->major_ver = 2;
    rsp->minor_ver = 0;
    rsp->subminor_ver = 0;
    rsp->error = KM_ERROR_OK;
}

GetVersion2Response AndroidKeymaster::GetVersion2(const GetVersion2Request& req) {
    GetVersion2Response rsp;
    rsp.km_version = context_->GetKmVersion();
    rsp.km_date = kKmDate;
    rsp.max_message_version = MessageVersion(rsp.km_version, rsp.km_date);
    rsp.error = KM_ERROR_OK;

    // Determine what message version we should use.
    message_version_ = NegotiateMessageVersion(req, rsp);

    LOG_D("GetVersion2 results: %d, %d, %d, %d", rsp.km_version, rsp.km_date,
          rsp.max_message_version, message_version_);
    return rsp;
}

void AndroidKeymaster::SupportedAlgorithms(const SupportedAlgorithmsRequest& /* request */,
                                           SupportedAlgorithmsResponse* response) {
    if (response == nullptr) return;

    response->error = KM_ERROR_OK;

    size_t algorithm_count = 0;
    const keymaster_algorithm_t* algorithms = context_->GetSupportedAlgorithms(&algorithm_count);
    if (algorithm_count == 0) return;
    response->results_length = algorithm_count;
    response->results = dup_array(algorithms, algorithm_count);
    if (!response->results) response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
}

template <typename T>
void GetSupported(const KeymasterContext& context, keymaster_algorithm_t algorithm,
                  keymaster_purpose_t purpose,
                  const T* (OperationFactory::*get_supported_method)(size_t* count) const,
                  SupportedResponse<T>* response) {
    if (response == nullptr || !check_supported(context, algorithm, response)) return;

    const OperationFactory* factory = context.GetOperationFactory(algorithm, purpose);
    if (!factory) {
        response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
        return;
    }

    size_t count;
    const T* supported = (factory->*get_supported_method)(&count);
    response->SetResults(supported, count);
}

void AndroidKeymaster::SupportedBlockModes(const SupportedBlockModesRequest& request,
                                           SupportedBlockModesResponse* response) {
    GetSupported(*context_, request.algorithm, request.purpose,
                 &OperationFactory::SupportedBlockModes, response);
}

void AndroidKeymaster::SupportedPaddingModes(const SupportedPaddingModesRequest& request,
                                             SupportedPaddingModesResponse* response) {
    GetSupported(*context_, request.algorithm, request.purpose,
                 &OperationFactory::SupportedPaddingModes, response);
}

void AndroidKeymaster::SupportedDigests(const SupportedDigestsRequest& request,
                                        SupportedDigestsResponse* response) {
    GetSupported(*context_, request.algorithm, request.purpose, &OperationFactory::SupportedDigests,
                 response);
}

void AndroidKeymaster::SupportedImportFormats(const SupportedImportFormatsRequest& request,
                                              SupportedImportFormatsResponse* response) {
    if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;

    size_t count;
    const keymaster_key_format_t* formats =
        context_->GetKeyFactory(request.algorithm)->SupportedImportFormats(&count);
    response->SetResults(formats, count);
}

void AndroidKeymaster::SupportedExportFormats(const SupportedExportFormatsRequest& request,
                                              SupportedExportFormatsResponse* response) {
    if (response == nullptr || !check_supported(*context_, request.algorithm, response)) return;

    size_t count;
    const keymaster_key_format_t* formats =
        context_->GetKeyFactory(request.algorithm)->SupportedExportFormats(&count);
    response->SetResults(formats, count);
}

GetHmacSharingParametersResponse AndroidKeymaster::GetHmacSharingParameters() {
    GetHmacSharingParametersResponse response(message_version());
    KeymasterEnforcement* policy = context_->enforcement_policy();
    if (!policy) {
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }

    response.error = policy->GetHmacSharingParameters(&response.params);
    return response;
}

ComputeSharedHmacResponse
AndroidKeymaster::ComputeSharedHmac(const ComputeSharedHmacRequest& request) {
    ComputeSharedHmacResponse response(message_version());
    KeymasterEnforcement* policy = context_->enforcement_policy();
    if (!policy) {
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }
    response.error = policy->ComputeSharedHmac(request.params_array, &response.sharing_check);

    return response;
}

VerifyAuthorizationResponse
AndroidKeymaster::VerifyAuthorization(const VerifyAuthorizationRequest& request) {
    KeymasterEnforcement* policy = context_->enforcement_policy();
    if (!policy) {
        VerifyAuthorizationResponse response(message_version());
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }

    return policy->VerifyAuthorization(request);
}

void AndroidKeymaster::GenerateTimestampToken(GenerateTimestampTokenRequest& request,
                                              GenerateTimestampTokenResponse* response) {
    KeymasterEnforcement* policy = context_->enforcement_policy();
    if (!policy) {
        response->error = KM_ERROR_UNIMPLEMENTED;
    } else {
        response->token.challenge = request.challenge;
        response->error = policy->GenerateTimestampToken(&response->token);
    }
}

void AndroidKeymaster::AddRngEntropy(const AddEntropyRequest& request,
                                     AddEntropyResponse* response) {
    response->error = context_->AddRngEntropy(request.random_data.peek_read(),
                                              request.random_data.available_read());
}

const KeyFactory* get_key_factory(const AuthorizationSet& key_description,
                                  const KeymasterContext& context,  //
                                  keymaster_error_t* error) {
    keymaster_algorithm_t algorithm;
    const KeyFactory* factory{};
    if (!key_description.GetTagValue(TAG_ALGORITHM, &algorithm) ||
        !(factory = context.GetKeyFactory(algorithm))) {
        *error = KM_ERROR_UNSUPPORTED_ALGORITHM;
    }
    return factory;
}

void AndroidKeymaster::GenerateKey(const GenerateKeyRequest& request,
                                   GenerateKeyResponse* response) {
    if (response == nullptr) return;

    const KeyFactory* factory =
        get_key_factory(request.key_description, *context_, &response->error);
    if (!factory) return;

    UniquePtr<Key> attest_key;
    if (request.attestation_signing_key_blob.key_material_size) {
        attest_key = LoadKey(request.attestation_signing_key_blob, request.attest_key_params,
                             &response->error);
        if (response->error != KM_ERROR_OK) return;
    }

    if (request.key_description.Contains(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY) &&
        request.key_description.GetTagCount(TAG_PURPOSE) > 1) {
        // ATTEST_KEY cannot be combined with any other purpose.
        response->error = KM_ERROR_INCOMPATIBLE_PURPOSE;
        return;
    }

    response->enforced.Clear();
    response->unenforced.Clear();
    response->error = factory->GenerateKey(request.key_description,
                                           std::move(attest_key),  //
                                           request.issuer_subject,
                                           &response->key_blob,  //
                                           &response->enforced,
                                           &response->unenforced,  //
                                           &response->certificate_chain);
}

constexpr int kRkpVersionWithoutSuperencryption = 3;

void AndroidKeymaster::GenerateRkpKey(const GenerateRkpKeyRequest& request,
                                      GenerateRkpKeyResponse* response) {
    if (response == nullptr) return;

    auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
    if (!rem_prov_ctx) {
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    GetHwInfoResponse hwInfo(message_version());
    rem_prov_ctx->GetHwInfo(&hwInfo);
    if (hwInfo.version >= kRkpVersionWithoutSuperencryption && request.test_mode) {
        response->error = static_cast<keymaster_error_t>(kStatusRemoved);
        return;
    }

    // Generate the keypair that will become the attestation key.
    GenerateKeyRequest gen_key_request(message_version_);
    gen_key_request.key_description.Reinitialize(kKeyMintEcdsaP256Params,
                                                 array_length(kKeyMintEcdsaP256Params));
    GenerateKeyResponse gen_key_response(message_version_);
    GenerateKey(gen_key_request, &gen_key_response);
    if (gen_key_response.error != KM_ERROR_OK) {
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    // Retrieve the certificate and parse it to build a COSE_Key
    if (gen_key_response.certificate_chain.entry_count != 1) {
        // Error: Need the single non-signed certificate with the public key in it.
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }
    std::vector<uint8_t> x_coord(kP256AffinePointSize);
    std::vector<uint8_t> y_coord(kP256AffinePointSize);
    response->error =
        GetEcdsa256KeyFromCert(gen_key_response.certificate_chain.begin(), x_coord.data(),
                               x_coord.size(), y_coord.data(), y_coord.size());
    if (response->error != KM_ERROR_OK) {
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    cppbor::Map cose_public_key_map = cppbor::Map()
                                          .add(CoseKey::KEY_TYPE, EC2)
                                          .add(CoseKey::ALGORITHM, ES256)
                                          .add(CoseKey::CURVE, P256)
                                          .add(CoseKey::PUBKEY_X, x_coord)
                                          .add(CoseKey::PUBKEY_Y, y_coord);
    if (request.test_mode) {
        cose_public_key_map.add(CoseKey::TEST_KEY, cppbor::Null());
    }

    std::vector<uint8_t> cosePublicKey = cose_public_key_map.canonicalize().encode();

    auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
    auto macedKey = constructCoseMac0(macFunction, {} /* externalAad */, cosePublicKey);
    if (!macedKey) {
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }
    std::vector<uint8_t> enc = macedKey->encode();
    response->maced_public_key = KeymasterBlob(enc.data(), enc.size());
    response->key_blob = std::move(gen_key_response.key_blob);
    response->error = KM_ERROR_OK;
}

void AndroidKeymaster::GenerateCsr(const GenerateCsrRequest& request,
                                   GenerateCsrResponse* response) {
    if (response == nullptr) return;

    auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
    if (!rem_prov_ctx) {
        LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    GetHwInfoResponse hwInfo(message_version());
    rem_prov_ctx->GetHwInfo(&hwInfo);
    if (hwInfo.version >= kRkpVersionWithoutSuperencryption) {
        response->error = static_cast<keymaster_error_t>(kStatusRemoved);
        return;
    }

    auto macFunction = getMacFunction(request.test_mode, rem_prov_ctx);
    auto pubKeysToSign = validateAndExtractPubkeys(request.test_mode, request.num_keys,
                                                   request.keys_to_sign_array, macFunction);
    if (!pubKeysToSign.isOk()) {
        LOG_E("Failed to validate and extract the public keys for the CSR", 0);
        response->error = static_cast<keymaster_error_t>(pubKeysToSign.moveError());
        return;
    }

    std::vector<uint8_t> ephemeral_mac_key(SHA256_DIGEST_LENGTH, 0 /* value */);
    if (GenerateRandom(ephemeral_mac_key.data(), ephemeral_mac_key.size()) != KM_ERROR_OK) {
        LOG_E("Failed to generate a random mac key.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    auto ephemeral_mac_function = [&ephemeral_mac_key](const cppcose::bytevec& input) {
        return cppcose::generateHmacSha256(ephemeral_mac_key, input);
    };

    auto pubKeysToSignMac = generateCoseMac0Mac(ephemeral_mac_function, std::vector<uint8_t>{},
                                                pubKeysToSign->encode());
    if (!pubKeysToSignMac) {
        LOG_E("Failed to generate COSE_Mac0 over the public keys to sign.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }
    response->keys_to_sign_mac = KeymasterBlob(pubKeysToSignMac->data(), pubKeysToSignMac->size());

    std::unique_ptr<cppbor::Map> device_info_map =
        rem_prov_ctx->CreateDeviceInfo(2 /* csrVersion */);
    std::vector<uint8_t> device_info = device_info_map->encode();
    response->device_info_blob = KeymasterBlob(device_info.data(), device_info.size());
    auto protectedDataPayload = rem_prov_ctx->BuildProtectedDataPayload(
        request.test_mode,  //
        ephemeral_mac_key /* Payload */,
        cppbor::Array() /* AAD */
            .add(std::pair(request.challenge.begin(),
                           request.challenge.end() - request.challenge.begin()))
            .add(std::move(device_info_map))
            .add(std::pair(pubKeysToSignMac->data(), pubKeysToSignMac->size()))
            .encode());
    if (!protectedDataPayload) {
        LOG_E("Failed to construct ProtectedData: %s", protectedDataPayload.moveMessage().c_str());
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    std::vector<uint8_t> ephemeralPrivKey(X25519_PRIVATE_KEY_LEN);
    std::vector<uint8_t> ephemeralPubKey(X25519_PUBLIC_VALUE_LEN);
    X25519_keypair(ephemeralPubKey.data(), ephemeralPrivKey.data());

    auto eek = validateAndExtractEekPubAndId(request.test_mode, request.endpoint_enc_cert_chain);
    if (!eek.isOk()) {
        LOG_E("Failed to validate and extract the endpoint encryption key.", 0);
        response->error = static_cast<keymaster_error_t>(eek.moveError());
        return;
    }

    auto sessionKey =
        x25519_HKDF_DeriveKey(ephemeralPubKey, ephemeralPrivKey, eek->first, true /* senderIsA */);
    if (!sessionKey) {
        LOG_E("Failed to derive the session key.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    std::vector<uint8_t> nonce(kAesGcmNonceLength, 0 /* value */);
    if (GenerateRandom(nonce.data(), nonce.size()) != KM_ERROR_OK) {
        LOG_E("Failed to generate a random nonce.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }
    auto coseEncrypted = constructCoseEncrypt(*sessionKey,                       //
                                              nonce,                             //
                                              protectedDataPayload.moveValue(),  //
                                              {},                                // aad
                                              buildCertReqRecipients(ephemeralPubKey, eek->second));

    if (!coseEncrypted) {
        LOG_E("Failed to construct a COSE_Encrypt ProtectedData structure", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }
    std::vector<uint8_t> payload = coseEncrypted->encode();
    response->protected_data_blob = KeymasterBlob(payload.data(), payload.size());
    response->error = KM_ERROR_OK;
}

void AndroidKeymaster::GenerateCsrV2(const GenerateCsrV2Request& request,
                                     GenerateCsrV2Response* response) {

    if (response == nullptr) return;

    if (request.challenge.size() > kMaxChallengeSizeV2) {
        LOG_E("Challenge is too large. %zu expected. %zu actual.",
              kMaxChallengeSizeV2,        //
              request.challenge.size());  //
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
    if (rem_prov_ctx == nullptr) {
        LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    auto macFunction = getMacFunction(false /* test_mode */, rem_prov_ctx);
    auto pubKeys = validateAndExtractPubkeys(false /* test_mode */, request.num_keys,
                                             request.keys_to_sign_array, macFunction);
    if (!pubKeys.isOk()) {
        LOG_E("Failed to validate and extract the public keys for the CSR", 0);
        response->error = static_cast<keymaster_error_t>(pubKeys.moveError());
        return;
    }

    auto csr = rem_prov_ctx->BuildCsr(
        std::vector(request.challenge.begin(), request.challenge.end()), std::move(*pubKeys));
    if (!csr) {
        LOG_E("Failed to build CSR", 0);
        response->error = static_cast<keymaster_error_t>(kStatusFailed);
        return;
    }

    auto csr_blob = csr->encode();
    response->csr = KeymasterBlob(csr_blob.data(), csr_blob.size());
    response->error = KM_ERROR_OK;
}

void AndroidKeymaster::GetKeyCharacteristics(const GetKeyCharacteristicsRequest& request,
                                             GetKeyCharacteristicsResponse* response) {
    if (response == nullptr) return;

    UniquePtr<Key> key;
    response->error =
        context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
    if (response->error != KM_ERROR_OK) return;

    // scavenge the key object for the auth lists
    response->enforced = std::move(key->hw_enforced());
    response->unenforced = std::move(key->sw_enforced());

    response->error = CheckVersionInfo(response->enforced, response->unenforced, *context_);
}

void AndroidKeymaster::BeginOperation(const BeginOperationRequest& request,
                                      BeginOperationResponse* response) {
    if (response == nullptr) return;
    response->op_handle = 0;

    UniquePtr<Key> key = LoadKey(request.key_blob, request.additional_params, &response->error);
    if (!key) return;

    response->error = KM_ERROR_UNKNOWN_ERROR;
    keymaster_algorithm_t key_algorithm;
    if (!key->authorizations().GetTagValue(TAG_ALGORITHM, &key_algorithm)) return;

    response->error = KM_ERROR_UNSUPPORTED_PURPOSE;
    OperationFactory* factory = key->key_factory()->GetOperationFactory(request.purpose);
    if (!factory) return;

    uint32_t sd_slot = key->secure_deletion_slot();

    OperationPtr operation(
        factory->CreateOperation(std::move(*key), request.additional_params, &response->error));
    if (operation.get() == nullptr) return;

    operation->set_secure_deletion_slot(sd_slot);

    if (operation->authorizations().Contains(TAG_TRUSTED_CONFIRMATION_REQUIRED)) {
        if (!operation->create_confirmation_verifier_buffer()) {
            response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
            return;
        }
    }

    if (context_->enforcement_policy()) {
        km_id_t key_id;
        response->error = KM_ERROR_UNKNOWN_ERROR;
        if (!context_->enforcement_policy()->CreateKeyId(request.key_blob, &key_id)) return;
        operation->set_key_id(key_id);
        response->error = context_->enforcement_policy()->AuthorizeOperation(
            request.purpose, key_id, operation->authorizations(), request.additional_params,
            0 /* op_handle */, true /* is_begin_operation */);
        if (response->error != KM_ERROR_OK) return;
    }

    response->output_params.Clear();
    response->error = operation->Begin(request.additional_params, &response->output_params);
    if (response->error != KM_ERROR_OK) return;

    response->op_handle = operation->operation_handle();
    response->error = operation_table_->Add(std::move(operation));
}

void AndroidKeymaster::UpdateOperation(const UpdateOperationRequest& request,
                                       UpdateOperationResponse* response) {
    if (response == nullptr) return;

    response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
    Operation* operation = operation_table_->Find(request.op_handle);
    if (operation == nullptr) return;

    Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
    if (confirmation_verifier_buffer != nullptr) {
        size_t input_num_bytes = request.input.available_read();
        if (input_num_bytes + confirmation_verifier_buffer->available_read() >
            kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
            response->error = KM_ERROR_INVALID_ARGUMENT;
            operation_table_->Delete(request.op_handle);
            return;
        }
        if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
            response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
            operation_table_->Delete(request.op_handle);
            return;
        }
        confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
    }

    if (context_->enforcement_policy()) {
        response->error = context_->enforcement_policy()->AuthorizeOperation(
            operation->purpose(), operation->key_id(), operation->authorizations(),
            request.additional_params, request.op_handle, false /* is_begin_operation */);
        if (response->error != KM_ERROR_OK) {
            operation_table_->Delete(request.op_handle);
            return;
        }
    }

    response->error =
        operation->Update(request.additional_params, request.input, &response->output_params,
                          &response->output, &response->input_consumed);
    if (response->error != KM_ERROR_OK) {
        // Any error invalidates the operation.
        operation_table_->Delete(request.op_handle);
    }
}

void AndroidKeymaster::FinishOperation(const FinishOperationRequest& request,
                                       FinishOperationResponse* response) {
    if (response == nullptr) return;

    response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
    Operation* operation = operation_table_->Find(request.op_handle);
    if (operation == nullptr) return;

    Buffer* confirmation_verifier_buffer = operation->get_confirmation_verifier_buffer();
    if (confirmation_verifier_buffer != nullptr) {
        size_t input_num_bytes = request.input.available_read();
        if (input_num_bytes + confirmation_verifier_buffer->available_read() >
            kConfirmationMessageMaxSize + kConfirmationTokenMessageTagSize) {
            response->error = KM_ERROR_INVALID_ARGUMENT;
            operation_table_->Delete(request.op_handle);
            return;
        }
        if (!confirmation_verifier_buffer->reserve(input_num_bytes)) {
            response->error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
            operation_table_->Delete(request.op_handle);
            return;
        }
        confirmation_verifier_buffer->write(request.input.peek_read(), input_num_bytes);
    }

    if (context_->enforcement_policy()) {
        response->error = context_->enforcement_policy()->AuthorizeOperation(
            operation->purpose(), operation->key_id(), operation->authorizations(),
            request.additional_params, request.op_handle, false /* is_begin_operation */);
        if (response->error != KM_ERROR_OK) {
            operation_table_->Delete(request.op_handle);
            return;
        }
    }

    response->error = operation->Finish(request.additional_params, request.input, request.signature,
                                        &response->output_params, &response->output);
    if (response->error != KM_ERROR_OK) {
        operation_table_->Delete(request.op_handle);
        return;
    }

    // Invalidate the single use key from secure storage after finish.
    if (operation->hw_enforced().Contains(TAG_USAGE_COUNT_LIMIT, 1)) {
        if (context_->secure_deletion_secret_storage() != nullptr) {
            context_->secure_deletion_secret_storage()->DeleteKey(
                operation->secure_deletion_slot());
        } else if (context_->secure_key_storage() != nullptr) {
            context_->secure_key_storage()->DeleteKey(operation->key_id());
        }
    }

    // If the operation succeeded and TAG_TRUSTED_CONFIRMATION_REQUIRED was
    // set, the input must be checked against the confirmation token.
    if (response->error == KM_ERROR_OK && confirmation_verifier_buffer != nullptr) {
        keymaster_blob_t confirmation_token_blob;
        if (!request.additional_params.GetTagValue(TAG_CONFIRMATION_TOKEN,
                                                   &confirmation_token_blob)) {
            response->error = KM_ERROR_NO_USER_CONFIRMATION;
            response->output.Clear();
        } else {
            if (confirmation_token_blob.data_length != kConfirmationTokenSize) {
                LOG_E("TAG_CONFIRMATION_TOKEN wrong size, was %zd expected %zd",
                      confirmation_token_blob.data_length, kConfirmationTokenSize);
                response->error = KM_ERROR_INVALID_ARGUMENT;
                response->output.Clear();
            } else {
                keymaster_error_t verification_result = context_->CheckConfirmationToken(
                    confirmation_verifier_buffer->begin(),
                    confirmation_verifier_buffer->available_read(), confirmation_token_blob.data);
                if (verification_result != KM_ERROR_OK) {
                    response->error = verification_result;
                    response->output.Clear();
                }
            }
        }
    }

    operation_table_->Delete(request.op_handle);
}

void AndroidKeymaster::AbortOperation(const AbortOperationRequest& request,
                                      AbortOperationResponse* response) {
    if (!response) return;

    Operation* operation = operation_table_->Find(request.op_handle);
    if (!operation) {
        response->error = KM_ERROR_INVALID_OPERATION_HANDLE;
        return;
    }

    response->error = operation->Abort();
    operation_table_->Delete(request.op_handle);
}

void AndroidKeymaster::ExportKey(const ExportKeyRequest& request, ExportKeyResponse* response) {
    if (response == nullptr) return;

    UniquePtr<Key> key;
    response->error =
        context_->ParseKeyBlob(KeymasterKeyBlob(request.key_blob), request.additional_params, &key);
    if (response->error != KM_ERROR_OK) return;

    UniquePtr<uint8_t[]> out_key;
    size_t size;
    response->error = key->formatted_key_material(request.key_format, &out_key, &size);
    if (response->error == KM_ERROR_OK) {
        response->key_data = out_key.release();
        response->key_data_length = size;
    }
}

void AndroidKeymaster::AttestKey(const AttestKeyRequest& request, AttestKeyResponse* response) {
    if (!response) return;

    UniquePtr<Key> key = LoadKey(request.key_blob, request.attest_params, &response->error);
    if (!key) return;

    keymaster_blob_t attestation_application_id;
    if (request.attest_params.GetTagValue(TAG_ATTESTATION_APPLICATION_ID,
                                          &attestation_application_id)) {
        key->sw_enforced().push_back(TAG_ATTESTATION_APPLICATION_ID, attestation_application_id);
    }

    response->certificate_chain =
        context_->GenerateAttestation(*key, request.attest_params, {} /* attestation_signing_key */,
                                      {} /* issuer_subject */, &response->error);
}

void AndroidKeymaster::UpgradeKey(const UpgradeKeyRequest& request, UpgradeKeyResponse* response) {
    if (!response) return;

    KeymasterKeyBlob upgraded_key;
    response->error = context_->UpgradeKeyBlob(KeymasterKeyBlob(request.key_blob),
                                               request.upgrade_params, &upgraded_key);
    if (response->error != KM_ERROR_OK) return;
    response->upgraded_key = upgraded_key.release();
}

void AndroidKeymaster::ImportKey(const ImportKeyRequest& request, ImportKeyResponse* response) {
    if (response == nullptr) return;

    const KeyFactory* factory =
        get_key_factory(request.key_description, *context_, &response->error);
    if (!factory) return;

    if (context_->enforcement_policy() &&
        request.key_description.GetTagValue(TAG_EARLY_BOOT_ONLY) &&
        !context_->enforcement_policy()->in_early_boot()) {
        response->error = KM_ERROR_EARLY_BOOT_ENDED;
        return;
    }

    UniquePtr<Key> attest_key;
    if (request.attestation_signing_key_blob.key_material_size) {

        attest_key =
            LoadKey(request.attestation_signing_key_blob, {} /* params */, &response->error);
        if (response->error != KM_ERROR_OK) return;
    }

    if (request.key_description.Contains(TAG_PURPOSE, KM_PURPOSE_ATTEST_KEY) &&
        request.key_description.GetTagCount(TAG_PURPOSE) > 1) {
        // ATTEST_KEY cannot be combined with any other purpose.
        response->error = KM_ERROR_INCOMPATIBLE_PURPOSE;
        return;
    }

    response->error = factory->ImportKey(request.key_description,  //
                                         request.key_format,       //
                                         request.key_data,         //
                                         std::move(attest_key),    //
                                         request.issuer_subject,   //
                                         &response->key_blob,      //
                                         &response->enforced,      //
                                         &response->unenforced,    //
                                         &response->certificate_chain);
}

void AndroidKeymaster::DeleteKey(const DeleteKeyRequest& request, DeleteKeyResponse* response) {
    if (!response) return;
    response->error = context_->DeleteKey(KeymasterKeyBlob(request.key_blob));
}

void AndroidKeymaster::DeleteAllKeys(const DeleteAllKeysRequest&, DeleteAllKeysResponse* response) {
    if (!response) return;
    response->error = context_->DeleteAllKeys();
}

void AndroidKeymaster::Configure(const ConfigureRequest& request, ConfigureResponse* response) {
    if (!response) return;
    response->error = context_->SetSystemVersion(request.os_version, request.os_patchlevel);
}

ConfigureVendorPatchlevelResponse
AndroidKeymaster::ConfigureVendorPatchlevel(const ConfigureVendorPatchlevelRequest& request) {
    ConfigureVendorPatchlevelResponse rsp(message_version());
    rsp.error = context_->SetVendorPatchlevel(request.vendor_patchlevel);
    return rsp;
}

ConfigureBootPatchlevelResponse
AndroidKeymaster::ConfigureBootPatchlevel(const ConfigureBootPatchlevelRequest& request) {
    ConfigureBootPatchlevelResponse rsp(message_version());
    rsp.error = context_->SetBootPatchlevel(request.boot_patchlevel);
    return rsp;
}

ConfigureVerifiedBootInfoResponse
AndroidKeymaster::ConfigureVerifiedBootInfo(const ConfigureVerifiedBootInfoRequest& request) {
    ConfigureVerifiedBootInfoResponse rsp(message_version());
    rsp.error = context_->SetVerifiedBootInfo(request.boot_state, request.bootloader_state,
                                              request.vbmeta_digest);
    return rsp;
}

bool AndroidKeymaster::has_operation(keymaster_operation_handle_t op_handle) const {
    return operation_table_->Find(op_handle) != nullptr;
}

UniquePtr<Key> AndroidKeymaster::LoadKey(const keymaster_key_blob_t& key_blob,
                                         const AuthorizationSet& additional_params,
                                         keymaster_error_t* error) {
    if (!error) return {};

    UniquePtr<Key> key;
    KeymasterKeyBlob key_material;
    *error = context_->ParseKeyBlob(KeymasterKeyBlob(key_blob), additional_params, &key);
    if (*error != KM_ERROR_OK) return {};

    *error = CheckVersionInfo(key->hw_enforced(), key->sw_enforced(), *context_);
    if (*error != KM_ERROR_OK) return {};

    return key;
}

void AndroidKeymaster::ImportWrappedKey(const ImportWrappedKeyRequest& request,
                                        ImportWrappedKeyResponse* response) {
    if (!response) return;

    KeymasterKeyBlob secret_key;
    AuthorizationSet key_description;
    keymaster_key_format_t key_format;

    response->error =
        context_->UnwrapKey(request.wrapped_key, request.wrapping_key, request.additional_params,
                            request.masking_key, &key_description, &key_format, &secret_key);

    if (response->error != KM_ERROR_OK) {
        return;
    }

    int sid_idx = key_description.find(TAG_USER_SECURE_ID);
    if (sid_idx != -1) {
        uint8_t sids = key_description[sid_idx].long_integer;
        if (!key_description.erase(sid_idx)) {
            response->error = KM_ERROR_UNKNOWN_ERROR;
            return;
        }
        if (sids & HW_AUTH_PASSWORD) {
            key_description.push_back(TAG_USER_SECURE_ID, request.password_sid);
        }
        if (sids & HW_AUTH_FINGERPRINT) {
            key_description.push_back(TAG_USER_SECURE_ID, request.biometric_sid);
        }

        if (context_->GetKmVersion() >= KmVersion::KEYMINT_1) {
            key_description.push_back(TAG_CERTIFICATE_NOT_BEFORE, 0);
            key_description.push_back(TAG_CERTIFICATE_NOT_AFTER, kUndefinedExpirationDateTime);
        }
    }

    const KeyFactory* factory = get_key_factory(key_description, *context_, &response->error);
    if (!factory) return;

    response->error = factory->ImportKey(key_description,          //
                                         key_format,               //
                                         secret_key,               //
                                         {} /* attest_key */,      //
                                         {} /* issuer_subject */,  //
                                         &response->key_blob,      //
                                         &response->enforced,      //
                                         &response->unenforced,    //
                                         &response->certificate_chain);
}

EarlyBootEndedResponse AndroidKeymaster::EarlyBootEnded() {
    EarlyBootEndedResponse response(message_version());
    response.error = KM_ERROR_UNIMPLEMENTED;

    if (context_->enforcement_policy()) {
        context_->enforcement_policy()->early_boot_ended();
        response.error = KM_ERROR_OK;
    }

    return response;
}

DeviceLockedResponse AndroidKeymaster::DeviceLocked(const DeviceLockedRequest& request) {
    DeviceLockedResponse response(message_version());
    response.error = KM_ERROR_UNIMPLEMENTED;

    if (context_->enforcement_policy()) {
        context_->enforcement_policy()->device_locked(request.passwordOnly);
        response.error = KM_ERROR_OK;
    }

    return response;
}

GetRootOfTrustResponse AndroidKeymaster::GetRootOfTrust(const GetRootOfTrustRequest& request) {
    GetRootOfTrustResponse response(message_version());

    if (!context_->attestation_context()) {
        LOG_E("Have no attestation context, cannot get RootOfTrust", 0);
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }

    const AttestationContext::VerifiedBootParams* vbParams =
        context_->attestation_context()->GetVerifiedBootParams(&response.error);
    if (response.error != KM_ERROR_OK) {
        LOG_E("Error retrieving verified boot params: %lu", response.error);
        return response;
    }

    auto boot_patch_level = context_->GetBootPatchlevel();
    if (!boot_patch_level) {
        LOG_E("Error retrieving boot patch level: %lu", response.error);
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }

    if (!context_->enforcement_policy()) {
        LOG_E("Have no enforcement policy, cannot get RootOfTrust", 0);
        response.error = KM_ERROR_UNIMPLEMENTED;
        return response;
    }

    auto macFunction =
        [&](const std::vector<uint8_t>& data) -> cppcose::ErrMsgOr<cppcose::HmacSha256> {
        auto mac = context_->enforcement_policy()->ComputeHmac(data);
        if (!mac) return "Failed to compute HMAC";
        return *std::move(mac);
    };

    auto maced_root_of_trust = cppcose::constructCoseMac0(
        macFunction,  //
        request.challenge,
        cppbor::SemanticTag(kRoTVersion1, cppbor::Array(                                //
                                              blob2Pair(vbParams->verified_boot_key),   //
                                              vbParams->device_locked,                  //
                                              vbParams->verified_boot_state,            //
                                              blob2Pair(vbParams->verified_boot_hash),  //
                                              *boot_patch_level))
            .encode());

    if (!maced_root_of_trust) {
        LOG_E("Error MACing RoT: %s", maced_root_of_trust.message().c_str());
        response.error = KM_ERROR_UNKNOWN_ERROR;
    } else {
        response.error = KM_ERROR_OK;
        response.rootOfTrust =
            cppbor::SemanticTag(cppcose::kCoseMac0SemanticTag, *std::move(maced_root_of_trust))
                .encode();
    }

    return response;
}

GetHwInfoResponse AndroidKeymaster::GetHwInfo() {
    GetHwInfoResponse response(message_version());

    auto rem_prov_ctx = context_->GetRemoteProvisioningContext();
    if (!rem_prov_ctx) {
        LOG_E("Couldn't get a pointer to the remote provisioning context, returned null.", 0);
        response.error = static_cast<keymaster_error_t>(kStatusFailed);
        return response;
    }

    rem_prov_ctx->GetHwInfo(&response);
    response.error = KM_ERROR_OK;
    return response;
}

SetAttestationIdsResponse
AndroidKeymaster::SetAttestationIds(const SetAttestationIdsRequest& request) {
    SetAttestationIdsResponse response(message_version());
    response.error = context_->SetAttestationIds(request);
    return response;
}

SetAttestationIdsKM3Response
AndroidKeymaster::SetAttestationIdsKM3(const SetAttestationIdsKM3Request& request) {
    SetAttestationIdsKM3Response response(message_version());
    response.error = context_->SetAttestationIdsKM3(request);
    return response;
}

}  // namespace keymaster