summaryrefslogtreecommitdiff
path: root/include/keymaster/android_keymaster_messages.h
blob: 7d430434c9706f0cf2af5e9feacfe6acf49c4502 (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
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
/*
 * 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.
 */

#pragma once

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

#include <string>
#include <string_view>
#include <vector>

#include <keymaster/android_keymaster_utils.h>
#include <keymaster/authorization_set.h>
#include <keymaster/km_version.h>

namespace keymaster {

// Commands
enum AndroidKeymasterCommand : uint32_t {
    GENERATE_KEY = 0,
    BEGIN_OPERATION = 1,
    UPDATE_OPERATION = 2,
    FINISH_OPERATION = 3,
    ABORT_OPERATION = 4,
    IMPORT_KEY = 5,
    EXPORT_KEY = 6,
    GET_VERSION = 7,
    ADD_RNG_ENTROPY = 8,
    GET_SUPPORTED_ALGORITHMS = 9,
    GET_SUPPORTED_BLOCK_MODES = 10,
    GET_SUPPORTED_PADDING_MODES = 11,
    GET_SUPPORTED_DIGESTS = 12,
    GET_SUPPORTED_IMPORT_FORMATS = 13,
    GET_SUPPORTED_EXPORT_FORMATS = 14,
    GET_KEY_CHARACTERISTICS = 15,
    ATTEST_KEY = 16,
    UPGRADE_KEY = 17,
    CONFIGURE = 18,
    GET_HMAC_SHARING_PARAMETERS = 19,
    COMPUTE_SHARED_HMAC = 20,
    VERIFY_AUTHORIZATION = 21,
    DELETE_KEY = 22,
    DELETE_ALL_KEYS = 23,
    DESTROY_ATTESTATION_IDS = 24,
    IMPORT_WRAPPED_KEY = 25,
    EARLY_BOOT_ENDED = 26,
    DEVICE_LOCKED = 27,
    GET_VERSION_2 = 28,
    GENERATE_RKP_KEY = 29,
    GENERATE_CSR = 30,
    GENERATE_TIMESTAMP_TOKEN = 31,
    CONFIGURE_VENDOR_PATCHLEVEL = 32,
    CONFIGURE_BOOT_PATCHLEVEL = 33,
    CONFIGURE_VERIFIED_BOOT_INFO = 34,
};

/**
 * Keymaster message versions are tied to keymaster versions.  We map the keymaster version to a
 * sequential "message version".  The actual message formatting differences are implemented in the
 * message classes. Note that it is not necessary to increase the message version when new messages
 * are added, only when the serialized format of one or more messages changes.  A message version
 * argument is provided to the message constructor and when the serialization/deserialization
 * methods are called the implementations of those methods should examine the message version and
 * generate/parse the byte stream accordingly.
 *
 * The original design of message versioning uses the GetVersion message, sent from client (e.g. HAL
 * service) to server (e.g. trusted app), and then relies on the client to identify what messages to
 * send.  This architecture assumes that the client is never older than the server.  This assumption
 * turned out not to be true in general.
 *
 * The current approach performs a mutual exchange of message version info between client and
 * server, using the GetVersion2 message.  In addition, it defers the specification of the message
 * ID to the message classes, so a message class can use a different ID when necessary.  ID changes
 * should be rare, in fact the only time they should be required is during the switch from
 * GetVersion to GetVersion2.
 *
 * Assuming both client and server support GetVersion2, the approach is as follows:
 *
 * 1.  Client sends GetVersion2Request, containing its maximum message version, c_max.
 * 2.  Server replies with GetVersion2Response, containing its maximum message version, s_max.
 * 3.  Both sides proceed to create all messages with version min(c_max, s_max).
 *
 * To enable this, the client must always send GetVersion2 as its first message.  If the server
 * doesn't support GetVersion2, it will reply with an error of some sort (the details are likely
 * environment-specific).  If the client gets this error, it must respond by sending GetVersion, and
 * then must configure its message version according to the response.  Note that an acceptable
 * response to a too-old server version is to return an error to the caller of the client, informing
 * it of the problem.
 *
 * On the server side, a server that supports GetVersion2 must also support GetVersion.  If it
 * received GetVersion2 it should proceed as outline above, and expect that the client will not send
 * GetVersion.  If it received GetVersion, it must assume that the client does not support
 * GetVersion2 and reply that it is version 2.0.0 and use the corresponding message version (3).
 */
constexpr int32_t kInvalidMessageVersion = -1;
constexpr int32_t kMaxMessageVersion = 4;
constexpr int32_t kDefaultMessageVersion = 3;

/**
 * MessageVersion returns the message version for a specified KM version and, possibly, KM release
 * date in YYYYMMDD format (it's not recommended to change message formats within a KM version, but
 * it could happen).
 */
inline int32_t MessageVersion(KmVersion version, uint32_t /* km_date */ = 0) {
    switch (version) {
    case KmVersion::KEYMASTER_1:
        return 1;
    case KmVersion::KEYMASTER_1_1:
        return 2;
    case KmVersion::KEYMASTER_2:
    case KmVersion::KEYMASTER_3:
    case KmVersion::KEYMASTER_4:
    case KmVersion::KEYMASTER_4_1:
        return 3;
    case KmVersion::KEYMINT_1:
    case KmVersion::KEYMINT_2:
        return 4;
    }
    return kInvalidMessageVersion;
}

/**
 * NegotiateMessageVersion implements the client side of the GetVersion protocol, determining the
 * appropriate message version from the values returned by the server.
 */
struct GetVersionResponse;
int32_t NegotiateMessageVersion(const GetVersionResponse& response, keymaster_error_t* error);

/**
 * This MessageVersion overload determines the message version to use given the provided client and
 * server messages.  If the client gets an error when it sends GetVersion2Request, it should send
 * GetVersionRequest and use the above overload.  If the server receives GetVersionRequest, it
 * should assume it should use message version 3 and return GetVersionResponse(2, 0, 0).
 */
struct GetVersion2Request;
struct GetVersion2Response;
int32_t NegotiateMessageVersion(const GetVersion2Request& request,
                                const GetVersion2Response& response);

struct KeymasterMessage : public Serializable {
    explicit KeymasterMessage(int32_t ver) : message_version(ver) { assert(ver >= 0); }

    // The message version that should be used for this message.  This indicates how the data is
    // serialized/deserialized. Commonly, higher message versions serialize/deserialize additional
    // arguments, though there is no specific rule limiting later version to adding parameters.
    const int32_t message_version;
};

/**
 * All responses include an error value, and if the error is not KM_ERROR_OK, return no additional
 * data.
 */
struct KeymasterResponse : public KeymasterMessage {
    explicit KeymasterResponse(int32_t ver)
        : KeymasterMessage(ver), error(KM_ERROR_UNKNOWN_ERROR) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    virtual size_t NonErrorSerializedSize() const = 0;
    virtual uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const = 0;
    virtual bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) = 0;

    keymaster_error_t error;
};

// Abstract base for empty requests.
struct EmptyKeymasterRequest : public KeymasterMessage {
    explicit EmptyKeymasterRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return 0; }
    uint8_t* Serialize(uint8_t* buf, const uint8_t*) const override { return buf; }
    bool Deserialize(const uint8_t**, const uint8_t*) override { return true; };
};

// Empty response.
struct EmptyKeymasterResponse : public KeymasterResponse {
    explicit EmptyKeymasterResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override { return 0; }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
    bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedAlgorithmsRequest : public KeymasterMessage {
    explicit SupportedAlgorithmsRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return 0; };
    uint8_t* Serialize(uint8_t* buf, const uint8_t* /* end */) const override { return buf; }
    bool Deserialize(const uint8_t** /* buf_ptr */, const uint8_t* /* end */) override {
        return true;
    }
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedByAlgorithmRequest : public KeymasterMessage {
    explicit SupportedByAlgorithmRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(uint32_t); };
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint32_to_buf(buf, end, algorithm);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &algorithm);
    }

    keymaster_algorithm_t algorithm;
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedImportFormatsRequest : public SupportedByAlgorithmRequest {
    explicit SupportedImportFormatsRequest(int32_t ver) : SupportedByAlgorithmRequest(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedExportFormatsRequest : public SupportedByAlgorithmRequest {
    explicit SupportedExportFormatsRequest(int32_t ver) : SupportedByAlgorithmRequest(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedByAlgorithmAndPurposeRequest : public KeymasterMessage {
    explicit SupportedByAlgorithmAndPurposeRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(uint32_t) * 2; };
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_uint32_to_buf(buf, end, algorithm);
        return append_uint32_to_buf(buf, end, purpose);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &algorithm) &&
               copy_uint32_from_buf(buf_ptr, end, &purpose);
    }

    keymaster_algorithm_t algorithm;
    keymaster_purpose_t purpose;
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedBlockModesRequest : public SupportedByAlgorithmAndPurposeRequest {
    explicit SupportedBlockModesRequest(int32_t ver) : SupportedByAlgorithmAndPurposeRequest(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedPaddingModesRequest : public SupportedByAlgorithmAndPurposeRequest {
    explicit SupportedPaddingModesRequest(int32_t ver)
        : SupportedByAlgorithmAndPurposeRequest(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedDigestsRequest : public SupportedByAlgorithmAndPurposeRequest {
    explicit SupportedDigestsRequest(int32_t ver) : SupportedByAlgorithmAndPurposeRequest(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
template <typename T> struct SupportedResponse : public KeymasterResponse {
    explicit SupportedResponse(int32_t ver)
        : KeymasterResponse(ver), results(nullptr), results_length(0) {}
    ~SupportedResponse() { delete[] results; }

    template <size_t N> void SetResults(const T (&arr)[N]) { SetResults(arr, N); }

    void SetResults(const T* arr, size_t n) {
        delete[] results;
        results_length = 0;
        results = dup_array(arr, n);
        if (results == nullptr) {
            error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
        } else {
            results_length = n;
            error = KM_ERROR_OK;
        }
    }

    size_t NonErrorSerializedSize() const override {
        return sizeof(uint32_t) + results_length * sizeof(uint32_t);
    }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint32_array_to_buf(buf, end, results, results_length);
    }
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        delete[] results;
        results = nullptr;
        UniquePtr<T[]> tmp;
        if (!copy_uint32_array_from_buf(buf_ptr, end, &tmp, &results_length)) return false;
        results = tmp.release();
        return true;
    }

    T* results;
    size_t results_length;
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedAlgorithmsResponse : public SupportedResponse<keymaster_algorithm_t> {
    explicit SupportedAlgorithmsResponse(int32_t ver)
        : SupportedResponse<keymaster_algorithm_t>(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedBlockModesResponse : public SupportedResponse<keymaster_block_mode_t> {
    explicit SupportedBlockModesResponse(int32_t ver)
        : SupportedResponse<keymaster_block_mode_t>(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedPaddingModesResponse : public SupportedResponse<keymaster_padding_t> {
    explicit SupportedPaddingModesResponse(int32_t ver)
        : SupportedResponse<keymaster_padding_t>(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedDigestsResponse : public SupportedResponse<keymaster_digest_t> {
    explicit SupportedDigestsResponse(int32_t ver) : SupportedResponse<keymaster_digest_t>(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedImportFormatsResponse : public SupportedResponse<keymaster_key_format_t> {
    explicit SupportedImportFormatsResponse(int32_t ver)
        : SupportedResponse<keymaster_key_format_t>(ver) {}
};

// TODO(swillden): Remove when Keymaster1 is deleted
struct SupportedExportFormatsResponse : public SupportedResponse<keymaster_key_format_t> {
    explicit SupportedExportFormatsResponse(int32_t ver)
        : SupportedResponse<keymaster_key_format_t>(ver) {}
};

struct GenerateKeyRequest : public KeymasterMessage {
    explicit GenerateKeyRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    AuthorizationSet key_description;
    KeymasterKeyBlob attestation_signing_key_blob;
    AuthorizationSet attest_key_params;
    KeymasterBlob issuer_subject;
};

struct GenerateKeyResponse : public KeymasterResponse {
    explicit GenerateKeyResponse(int32_t ver)
        : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterKeyBlob key_blob;
    AuthorizationSet enforced;
    AuthorizationSet unenforced;
    CertificateChain certificate_chain;
};

struct GenerateRkpKeyRequest : KeymasterMessage {
    explicit GenerateRkpKeyRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(uint8_t); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_to_buf(buf, end, &test_mode, sizeof(uint8_t));
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_from_buf(buf_ptr, end, &test_mode, sizeof(uint8_t));
    }

    bool test_mode = false;
};

struct GenerateRkpKeyResponse : public KeymasterResponse {
    explicit GenerateRkpKeyResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterKeyBlob key_blob;
    KeymasterBlob maced_public_key;
};

struct GenerateCsrRequest : public KeymasterMessage {
    explicit GenerateCsrRequest(int32_t ver) : KeymasterMessage(ver) {}

    ~GenerateCsrRequest() override { delete[] keys_to_sign_array; }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
    void SetKeyToSign(uint32_t index, const void* data, size_t length);
    void SetEndpointEncCertChain(const void* data, size_t length);
    void SetChallenge(const void* data, size_t length);

    bool test_mode = false;
    size_t num_keys = 0;
    KeymasterBlob* keys_to_sign_array = nullptr;
    KeymasterBlob endpoint_enc_cert_chain;
    KeymasterBlob challenge;
};

struct GenerateCsrResponse : public KeymasterResponse {
    explicit GenerateCsrResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterBlob keys_to_sign_mac;
    KeymasterBlob device_info_blob;
    KeymasterBlob protected_data_blob;
};

struct GetKeyCharacteristicsRequest : public KeymasterMessage {
    explicit GetKeyCharacteristicsRequest(int32_t ver) : KeymasterMessage(ver) {
        key_blob.key_material = nullptr;
        key_blob.key_material_size = 0;
    }
    ~GetKeyCharacteristicsRequest();

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_key_blob_t key_blob;
    AuthorizationSet additional_params;
};

struct GetKeyCharacteristicsResponse : public KeymasterResponse {
    explicit GetKeyCharacteristicsResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    AuthorizationSet enforced;
    AuthorizationSet unenforced;
};

struct BeginOperationRequest : public KeymasterMessage {
    explicit BeginOperationRequest(int32_t ver) : KeymasterMessage(ver) {
        key_blob.key_material = nullptr;
        key_blob.key_material_size = 0;
    }
    ~BeginOperationRequest() { delete[] key_blob.key_material; }

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_purpose_t purpose;
    keymaster_key_blob_t key_blob;
    AuthorizationSet additional_params;
};

struct BeginOperationResponse : public KeymasterResponse {
    explicit BeginOperationResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_operation_handle_t op_handle;
    AuthorizationSet output_params;
};

struct UpdateOperationRequest : public KeymasterMessage {
    explicit UpdateOperationRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_operation_handle_t op_handle;
    Buffer input;
    AuthorizationSet additional_params;
};

struct UpdateOperationResponse : public KeymasterResponse {
    explicit UpdateOperationResponse(int32_t ver) : KeymasterResponse(ver), input_consumed(0) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    Buffer output;
    size_t input_consumed;
    AuthorizationSet output_params;
};

struct FinishOperationRequest : public KeymasterMessage {
    explicit FinishOperationRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_operation_handle_t op_handle;
    Buffer input;
    Buffer signature;
    AuthorizationSet additional_params;
};

struct FinishOperationResponse : public KeymasterResponse {
    explicit FinishOperationResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    Buffer output;
    AuthorizationSet output_params;
};

struct AbortOperationRequest : public KeymasterMessage {
    explicit AbortOperationRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(uint64_t); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint64_to_buf(buf, end, op_handle);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint64_from_buf(buf_ptr, end, &op_handle);
    }

    keymaster_operation_handle_t op_handle;
};

using AbortOperationResponse = EmptyKeymasterResponse;

struct AddEntropyRequest : public KeymasterMessage {
    explicit AddEntropyRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    Buffer random_data;
};

using AddEntropyResponse = EmptyKeymasterResponse;

struct ImportKeyRequest : public KeymasterMessage {
    explicit ImportKeyRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    AuthorizationSet key_description;
    keymaster_key_format_t key_format;
    KeymasterKeyBlob key_data;
    KeymasterKeyBlob attestation_signing_key_blob;
    AuthorizationSet attest_key_params;
    KeymasterBlob issuer_subject;
};

struct ImportKeyResponse : public KeymasterResponse {
    explicit ImportKeyResponse(int32_t ver)
        : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}
    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterKeyBlob key_blob;
    AuthorizationSet enforced;
    AuthorizationSet unenforced;
    CertificateChain certificate_chain;
};

struct ExportKeyRequest : public KeymasterMessage {
    explicit ExportKeyRequest(int32_t ver) : KeymasterMessage(ver) {
        key_blob.key_material = nullptr;
        key_blob.key_material_size = 0;
    }
    ~ExportKeyRequest() { delete[] key_blob.key_material; }

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    AuthorizationSet additional_params;
    keymaster_key_format_t key_format;
    keymaster_key_blob_t key_blob;
};

struct ExportKeyResponse : public KeymasterResponse {
    explicit ExportKeyResponse(int32_t ver) : KeymasterResponse(ver), key_data(nullptr) {}
    ~ExportKeyResponse() { delete[] key_data; }

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    uint8_t* key_data;
    size_t key_data_length;
};

struct DeleteKeyRequest : public KeymasterMessage {
    explicit DeleteKeyRequest(int32_t ver) : KeymasterMessage(ver) {
        key_blob.key_material = nullptr;
        key_blob.key_material_size = 0;
    }
    ~DeleteKeyRequest() { delete[] key_blob.key_material; }

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_key_blob_t key_blob;
};

using DeleteKeyResponse = EmptyKeymasterResponse;

struct DeleteAllKeysRequest : public EmptyKeymasterRequest {
    explicit DeleteAllKeysRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
};

using DeleteAllKeysResponse = EmptyKeymasterResponse;

struct GetVersionRequest : public EmptyKeymasterRequest {
    // GetVersionRequest ctor takes a version arg so it has the same signature as others, but the
    // value is ignored because it is not not versionable.
    explicit GetVersionRequest(uint32_t /* ver */ = 0)
        : EmptyKeymasterRequest(0 /* not versionable */) {}
};

struct GetVersionResponse : public KeymasterResponse {
    // GetVersionResponse ctor takes a version arg so it has the same signature as others, but the
    // value is ignored because it is not not versionable.
    explicit GetVersionResponse(uint32_t /* ver */ = 0)
        : KeymasterResponse(0 /* not versionable */), major_ver(0), minor_ver(0), subminor_ver(0) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    uint8_t major_ver;
    uint8_t minor_ver;
    uint8_t subminor_ver;
};

struct AttestKeyRequest : public KeymasterMessage {
    explicit AttestKeyRequest(int32_t ver) : KeymasterMessage(ver) {
        key_blob.key_material = nullptr;
        key_blob.key_material_size = 0;
    }
    ~AttestKeyRequest();

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_key_blob_t key_blob;
    AuthorizationSet attest_params;
};

struct AttestKeyResponse : public KeymasterResponse {
    explicit AttestKeyResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    CertificateChain certificate_chain;
};

struct UpgradeKeyRequest : public KeymasterMessage {
    explicit UpgradeKeyRequest(int32_t ver) : KeymasterMessage(ver) { key_blob = {nullptr, 0}; }
    ~UpgradeKeyRequest();

    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_key_blob_t key_blob;
    AuthorizationSet upgrade_params;
};

struct UpgradeKeyResponse : public KeymasterResponse {
    explicit UpgradeKeyResponse(int32_t ver) : KeymasterResponse(ver) {
        upgraded_key = {nullptr, 0};
    }
    ~UpgradeKeyResponse();

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    keymaster_key_blob_t upgraded_key;
};

struct ConfigureRequest : public KeymasterMessage {
    explicit ConfigureRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(os_version) + sizeof(os_patchlevel); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_uint32_to_buf(buf, end, os_version);
        return append_uint32_to_buf(buf, end, os_patchlevel);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &os_version) &&
               copy_uint32_from_buf(buf_ptr, end, &os_patchlevel);
    }

    uint32_t os_version;
    uint32_t os_patchlevel;  // YYYYMM
};

using ConfigureResponse = EmptyKeymasterResponse;

struct HmacSharingParameters : public Serializable {
    HmacSharingParameters() : seed({}) { memset(nonce, 0, sizeof(nonce)); }
    HmacSharingParameters(HmacSharingParameters&& other) {
        seed = move(other.seed);
        memcpy(nonce, other.nonce, sizeof(nonce));
    }

    void SetSeed(KeymasterBlob&& value) { seed = move(value); }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterBlob seed{};
    uint8_t nonce[32];
};

struct HmacSharingParametersArray : public Serializable {
    HmacSharingParametersArray() : params_array(nullptr), num_params(0) {}
    HmacSharingParametersArray(HmacSharingParametersArray&& other) {
        delete[] params_array;
        params_array = other.params_array;
        num_params = other.num_params;
        other.params_array = nullptr;
        other.num_params = 0;
    }
    ~HmacSharingParametersArray() override { delete[] params_array; }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    HmacSharingParameters* params_array;
    size_t num_params;
};

struct GetHmacSharingParametersRequest : public EmptyKeymasterRequest {
    explicit GetHmacSharingParametersRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
};

struct GetHmacSharingParametersResponse : public KeymasterResponse {
    explicit GetHmacSharingParametersResponse(int32_t ver) : KeymasterResponse(ver) {}
    GetHmacSharingParametersResponse(GetHmacSharingParametersResponse&& other)
        : KeymasterResponse(other.message_version), params(move(other.params)) {}

    void SetSeed(KeymasterBlob&& seed_data) { params.SetSeed(move(seed_data)); }

    size_t NonErrorSerializedSize() const override { return params.SerializedSize(); }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
        return params.Serialize(buf, end);
    }
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return params.Deserialize(buf_ptr, end);
    }

    HmacSharingParameters params;
};

struct ComputeSharedHmacRequest : public KeymasterMessage {
    explicit ComputeSharedHmacRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return params_array.SerializedSize(); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return params_array.Serialize(buf, end);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return params_array.Deserialize(buf_ptr, end);
    }

    HmacSharingParametersArray params_array;
};

struct ComputeSharedHmacResponse : public KeymasterResponse {
    explicit ComputeSharedHmacResponse(int32_t ver) : KeymasterResponse(ver) {}
    ComputeSharedHmacResponse(ComputeSharedHmacResponse&& other) : KeymasterResponse(move(other)) {
        sharing_check = move(other.sharing_check);
    }

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterBlob sharing_check;
};

struct ImportWrappedKeyRequest : public KeymasterMessage {
    explicit ImportWrappedKeyRequest(int32_t ver) : KeymasterMessage(ver) {}

    void SetWrappedMaterial(const void* key_material, size_t length);
    void SetWrappingMaterial(const void* key_material, size_t length);
    void SetMaskingKeyMaterial(const void* key_material, size_t length);

    void SetKeyMaterial(const keymaster_key_blob_t& wrapped, const keymaster_key_blob_t& wrapping) {
        SetWrappedMaterial(wrapped.key_material, wrapped.key_material_size);
        SetWrappingMaterial(wrapping.key_material, wrapping.key_material_size);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterKeyBlob wrapped_key;
    KeymasterKeyBlob wrapping_key;
    KeymasterKeyBlob masking_key;
    AuthorizationSet additional_params;
    uint64_t password_sid;
    uint64_t biometric_sid;
};

struct ImportWrappedKeyResponse : public KeymasterResponse {
    explicit ImportWrappedKeyResponse(int32_t ver = kDefaultMessageVersion)
        : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}
    void SetKeyMaterial(const void* key_material, size_t length);
    void SetKeyMaterial(const keymaster_key_blob_t& blob) {
        SetKeyMaterial(blob.key_material, blob.key_material_size);
    }

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    KeymasterKeyBlob key_blob;
    AuthorizationSet enforced;
    AuthorizationSet unenforced;
    CertificateChain certificate_chain;
};

struct HardwareAuthToken : public Serializable {
    HardwareAuthToken() = default;
    HardwareAuthToken(HardwareAuthToken&& other) {
        challenge = other.challenge;
        user_id = other.user_id;
        authenticator_id = other.authenticator_id;
        authenticator_type = other.authenticator_type;
        timestamp = other.timestamp;
        mac = move(other.mac);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    uint64_t challenge{};
    uint64_t user_id{};
    uint64_t authenticator_id{};
    hw_authenticator_type_t authenticator_type{};
    uint64_t timestamp{};
    KeymasterBlob mac;
};

struct VerificationToken : public Serializable {
    VerificationToken() = default;
    VerificationToken(VerificationToken&& other) {
        challenge = other.challenge;
        timestamp = other.timestamp;
        parameters_verified = move(other.parameters_verified);
        security_level = other.security_level;
        mac = move(other.mac);
    }

    size_t SerializedSize() const override;
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    uint64_t challenge{};
    uint64_t timestamp{};
    AuthorizationSet parameters_verified{};
    keymaster_security_level_t security_level{};
    KeymasterBlob mac{};
};

struct VerifyAuthorizationRequest : public KeymasterMessage {
    explicit VerifyAuthorizationRequest(int32_t ver) : KeymasterMessage(ver) {}
    VerifyAuthorizationRequest(VerifyAuthorizationRequest&& other) = default;

    size_t SerializedSize() const override {
        return sizeof(challenge) + parameters_to_verify.SerializedSize() +
               auth_token.SerializedSize();
    }

    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_uint64_to_buf(buf, end, challenge);
        buf = parameters_to_verify.Serialize(buf, end);
        return auth_token.Serialize(buf, end);
    }

    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return (copy_uint64_from_buf(buf_ptr, end, &challenge) &&
                parameters_to_verify.Deserialize(buf_ptr, end) &&
                auth_token.Deserialize(buf_ptr, end));
    }

    uint64_t challenge{};
    AuthorizationSet parameters_to_verify;
    HardwareAuthToken auth_token;
};

struct VerifyAuthorizationResponse : public KeymasterResponse {
    explicit VerifyAuthorizationResponse(int32_t ver) : KeymasterResponse(ver) {}
    VerifyAuthorizationResponse(VerifyAuthorizationResponse&& other) = default;

    size_t NonErrorSerializedSize() const override {
        return sizeof(error) + token.SerializedSize();
    }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_uint32_to_buf(buf, end, error);
        return token.Serialize(buf, end);
    }
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &error) && token.Deserialize(buf_ptr, end);
    }

    VerificationToken token;
};

struct EarlyBootEndedRequest : public EmptyKeymasterRequest {
    explicit EarlyBootEndedRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
};

struct EarlyBootEndedResponse : public KeymasterResponse {
    explicit EarlyBootEndedResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override { return 0; }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
    bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
};

struct DeviceLockedRequest : public KeymasterMessage {
    explicit DeviceLockedRequest(int32_t ver) : KeymasterMessage(ver) {}
    explicit DeviceLockedRequest(int32_t ver, bool passwordOnly_, VerificationToken&& token_)
        : KeymasterMessage(ver), passwordOnly(passwordOnly_), token(move(token_)) {}

    size_t SerializedSize() const override { return 1; }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        if (buf < end) *buf++ = passwordOnly ? 1 : 0;
        return token.Serialize(buf, end);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        if (*buf_ptr >= end) return false;
        passwordOnly = !!*(*buf_ptr)++;
        return token.Deserialize(buf_ptr, end);
    }

    bool passwordOnly;
    VerificationToken token;
};

struct DeviceLockedResponse : public KeymasterResponse {
    explicit DeviceLockedResponse(int32_t ver) : KeymasterResponse(ver) {}

    size_t NonErrorSerializedSize() const override { return 0; }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
    bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
};

struct GetVersion2Request : public KeymasterMessage {
    // GetVersion2Request ctor takes a version arg so it has the same signature as others, but the
    // value is ignored because it's not versionable.
    explicit GetVersion2Request(uint32_t /* ver */ = 0)
        : KeymasterMessage(0 /* not versionable */) {}

    size_t SerializedSize() const override { return sizeof(uint32_t); /* max message version */ }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint32_to_buf(buf, end, max_message_version);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &max_message_version);
    }

    uint32_t max_message_version = kDefaultMessageVersion;
};

struct GetVersion2Response : public KeymasterResponse {
    // GetVersion2Request ctor takes a version arg so it has the same signature as others, but the
    // value is ignored because it's not versionable.
    explicit GetVersion2Response(uint32_t /* ver */ = 0)
        : KeymasterResponse(0 /* not versionable */) {}

    size_t NonErrorSerializedSize() const override;
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override;
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;

    uint32_t max_message_version;
    KmVersion km_version;
    uint32_t km_date;
};

struct TimestampToken : public Serializable {
    explicit TimestampToken() = default;
    TimestampToken(TimestampToken&& other) {
        challenge = other.challenge;
        timestamp = other.timestamp;
        security_level = other.security_level;
        mac = move(other.mac);
    }
    size_t SerializedSize() const override {
        return sizeof(challenge) + sizeof(timestamp) + sizeof(security_level) +
               mac.SerializedSize();
    }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_uint64_to_buf(buf, end, challenge);
        buf = append_uint64_to_buf(buf, end, timestamp);
        buf = append_uint32_to_buf(buf, end, security_level);
        return mac.Serialize(buf, end);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint64_from_buf(buf_ptr, end, &challenge) &&
               copy_uint64_from_buf(buf_ptr, end, &timestamp) &&
               copy_uint32_from_buf(buf_ptr, end, &security_level) && mac.Deserialize(buf_ptr, end);
    }
    uint64_t challenge{};
    uint64_t timestamp{};
    keymaster_security_level_t security_level{};
    KeymasterBlob mac{};
};

struct GenerateTimestampTokenRequest : public KeymasterMessage {
    explicit GenerateTimestampTokenRequest(int32_t ver) : KeymasterMessage(ver), challenge{} {}
    size_t SerializedSize() const override { return sizeof(challenge); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint64_to_buf(buf, end, challenge);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint64_from_buf(buf_ptr, end, &challenge);
    }
    uint64_t challenge;
};

struct GenerateTimestampTokenResponse : public KeymasterResponse {
    explicit GenerateTimestampTokenResponse(int32_t ver) : KeymasterResponse(ver), token{} {}
    size_t NonErrorSerializedSize() const override { return token.SerializedSize(); }
    uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
        return token.Serialize(buf, end);
    }
    bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return token.Deserialize(buf_ptr, end);
    }
    TimestampToken token;
};

struct SetAttestationIdsRequest : public KeymasterMessage {
    explicit SetAttestationIdsRequest(int32_t ver) : KeymasterMessage(ver) {}
    size_t SerializedSize() const override {
        return brand.SerializedSize()           //
               + device.SerializedSize()        //
               + product.SerializedSize()       //
               + serial.SerializedSize()        //
               + imei.SerializedSize()          //
               + meid.SerializedSize()          //
               + manufacturer.SerializedSize()  //
               + model.SerializedSize();
    }

    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = brand.Serialize(buf, end);
        buf = device.Serialize(buf, end);
        buf = product.Serialize(buf, end);
        buf = serial.Serialize(buf, end);
        buf = imei.Serialize(buf, end);
        buf = meid.Serialize(buf, end);
        buf = manufacturer.Serialize(buf, end);
        return model.Serialize(buf, end);
    }

    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return brand.Deserialize(buf_ptr, end)            //
               && device.Deserialize(buf_ptr, end)        //
               && product.Deserialize(buf_ptr, end)       //
               && serial.Deserialize(buf_ptr, end)        //
               && imei.Deserialize(buf_ptr, end)          //
               && meid.Deserialize(buf_ptr, end)          //
               && manufacturer.Deserialize(buf_ptr, end)  //
               && model.Deserialize(buf_ptr, end);        //
    }

    Buffer brand;
    Buffer device;
    Buffer product;
    Buffer serial;
    Buffer imei;
    Buffer meid;
    Buffer manufacturer;
    Buffer model;
};

using SetAttestationIdsResponse = EmptyKeymasterResponse;

struct ConfigureVendorPatchlevelRequest : public KeymasterMessage {
    explicit ConfigureVendorPatchlevelRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(vendor_patchlevel); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint32_to_buf(buf, end, vendor_patchlevel);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &vendor_patchlevel);
    }

    uint32_t vendor_patchlevel{};  // YYYYMMDD
};

using ConfigureVendorPatchlevelResponse = EmptyKeymasterResponse;

struct ConfigureBootPatchlevelRequest : public KeymasterMessage {
    explicit ConfigureBootPatchlevelRequest(int32_t ver) : KeymasterMessage(ver) {}

    size_t SerializedSize() const override { return sizeof(boot_patchlevel); }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        return append_uint32_to_buf(buf, end, boot_patchlevel);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_uint32_from_buf(buf_ptr, end, &boot_patchlevel);
    }

    uint32_t boot_patchlevel{};  // YYYYMMDD
};

using ConfigureBootPatchlevelResponse = EmptyKeymasterResponse;

struct ConfigureVerifiedBootInfoRequest : public KeymasterMessage {
    explicit ConfigureVerifiedBootInfoRequest(int32_t ver)
        : ConfigureVerifiedBootInfoRequest(ver, {}, {}, {}) {}

    ConfigureVerifiedBootInfoRequest(int32_t ver, std::string_view boot_state_param,
                                     std::string_view bootloader_state_param,
                                     std::vector<uint8_t> vbmeta_digest_param)
        : KeymasterMessage(ver), boot_state(boot_state_param),
          bootloader_state(bootloader_state_param), vbmeta_digest(std::move(vbmeta_digest_param)) {}

    size_t SerializedSize() const override {
        return sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t)  // buffer sizes
               + boot_state.size() + bootloader_state.size() + vbmeta_digest.size();
    }
    uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
        buf = append_collection_to_buf(buf, end, boot_state);
        buf = append_collection_to_buf(buf, end, bootloader_state);
        return append_collection_to_buf(buf, end, vbmeta_digest);
    }
    bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
        return copy_collection_from_buf(buf_ptr, end, &boot_state) &&
               copy_collection_from_buf(buf_ptr, end, &bootloader_state) &&
               copy_collection_from_buf(buf_ptr, end, &vbmeta_digest);
    }

    std::string boot_state;
    std::string bootloader_state;
    std::vector<uint8_t> vbmeta_digest;
};

using ConfigureVerifiedBootInfoResponse = EmptyKeymasterResponse;

}  // namespace keymaster