1 /*
2  * Copyright 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <assert.h>
20 #include <stdint.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include <string>
25 #include <string_view>
26 #include <utility>
27 #include <vector>
28 
29 #include <keymaster/android_keymaster_utils.h>
30 #include <keymaster/authorization_set.h>
31 #include <keymaster/km_version.h>
32 
33 namespace keymaster {
34 
35 // Commands
36 enum AndroidKeymasterCommand : uint32_t {
37     GENERATE_KEY = 0,
38     BEGIN_OPERATION = 1,
39     UPDATE_OPERATION = 2,
40     FINISH_OPERATION = 3,
41     ABORT_OPERATION = 4,
42     IMPORT_KEY = 5,
43     EXPORT_KEY = 6,
44     GET_VERSION = 7,
45     ADD_RNG_ENTROPY = 8,
46     GET_SUPPORTED_ALGORITHMS = 9,
47     GET_SUPPORTED_BLOCK_MODES = 10,
48     GET_SUPPORTED_PADDING_MODES = 11,
49     GET_SUPPORTED_DIGESTS = 12,
50     GET_SUPPORTED_IMPORT_FORMATS = 13,
51     GET_SUPPORTED_EXPORT_FORMATS = 14,
52     GET_KEY_CHARACTERISTICS = 15,
53     ATTEST_KEY = 16,
54     UPGRADE_KEY = 17,
55     CONFIGURE = 18,
56     GET_HMAC_SHARING_PARAMETERS = 19,
57     COMPUTE_SHARED_HMAC = 20,
58     VERIFY_AUTHORIZATION = 21,
59     DELETE_KEY = 22,
60     DELETE_ALL_KEYS = 23,
61     DESTROY_ATTESTATION_IDS = 24,
62     IMPORT_WRAPPED_KEY = 25,
63     EARLY_BOOT_ENDED = 26,
64     DEVICE_LOCKED = 27,
65     GET_VERSION_2 = 28,
66     GENERATE_RKP_KEY = 29,
67     GENERATE_CSR = 30,
68     GENERATE_TIMESTAMP_TOKEN = 31,
69     CONFIGURE_VENDOR_PATCHLEVEL = 32,
70     CONFIGURE_BOOT_PATCHLEVEL = 33,
71     CONFIGURE_VERIFIED_BOOT_INFO = 34,
72     GET_ROOT_OF_TRUST = 35,
73     GET_HW_INFO = 36,
74     GENERATE_CSR_V2 = 37,
75     SET_ATTESTATION_IDS = 38,
76     SET_ATTESTATION_IDS_KM3 = 39,
77 };
78 
79 /**
80  * Keymaster message versions are tied to keymaster versions.  We map the keymaster version to a
81  * sequential "message version".  The actual message formatting differences are implemented in the
82  * message classes. Note that it is not necessary to increase the message version when new messages
83  * are added, only when the serialized format of one or more messages changes.  A message version
84  * argument is provided to the message constructor and when the serialization/deserialization
85  * methods are called the implementations of those methods should examine the message version and
86  * generate/parse the byte stream accordingly.
87  *
88  * The original design of message versioning uses the GetVersion message, sent from client (e.g. HAL
89  * service) to server (e.g. trusted app), and then relies on the client to identify what messages to
90  * send.  This architecture assumes that the client is never older than the server.  This assumption
91  * turned out not to be true in general.
92  *
93  * The current approach performs a mutual exchange of message version info between client and
94  * server, using the GetVersion2 message.  In addition, it defers the specification of the message
95  * ID to the message classes, so a message class can use a different ID when necessary.  ID changes
96  * should be rare, in fact the only time they should be required is during the switch from
97  * GetVersion to GetVersion2.
98  *
99  * Assuming both client and server support GetVersion2, the approach is as follows:
100  *
101  * 1.  Client sends GetVersion2Request, containing its maximum message version, c_max.
102  * 2.  Server replies with GetVersion2Response, containing its maximum message version, s_max.
103  * 3.  Both sides proceed to create all messages with version min(c_max, s_max).
104  *
105  * To enable this, the client must always send GetVersion2 as its first message.  If the server
106  * doesn't support GetVersion2, it will reply with an error of some sort (the details are likely
107  * environment-specific).  If the client gets this error, it must respond by sending GetVersion, and
108  * then must configure its message version according to the response.  Note that an acceptable
109  * response to a too-old server version is to return an error to the caller of the client, informing
110  * it of the problem.
111  *
112  * On the server side, a server that supports GetVersion2 must also support GetVersion.  If it
113  * received GetVersion2 it should proceed as outline above, and expect that the client will not send
114  * GetVersion.  If it received GetVersion, it must assume that the client does not support
115  * GetVersion2 and reply that it is version 2.0.0 and use the corresponding message version (3).
116  */
117 constexpr int32_t kInvalidMessageVersion = -1;
118 constexpr int32_t kMaxMessageVersion = 4;
119 constexpr int32_t kDefaultMessageVersion = 3;
120 
121 /**
122  * MessageVersion returns the message version for a specified KM version and, possibly, KM release
123  * date in YYYYMMDD format (it's not recommended to change message formats within a KM version, but
124  * it could happen).
125  */
126 inline int32_t MessageVersion(KmVersion version, uint32_t /* km_date */ = 0) {
127     switch (version) {
128     case KmVersion::KEYMASTER_1:
129         return 1;
130     case KmVersion::KEYMASTER_1_1:
131         return 2;
132     case KmVersion::KEYMASTER_2:
133     case KmVersion::KEYMASTER_3:
134     case KmVersion::KEYMASTER_4:
135     case KmVersion::KEYMASTER_4_1:
136         return 3;
137     case KmVersion::KEYMINT_1:
138     case KmVersion::KEYMINT_2:
139     case KmVersion::KEYMINT_3:
140         return 4;
141     }
142     return kInvalidMessageVersion;
143 }
144 
145 /**
146  * NegotiateMessageVersion implements the client side of the GetVersion protocol, determining the
147  * appropriate message version from the values returned by the server.
148  */
149 struct GetVersionResponse;
150 int32_t NegotiateMessageVersion(const GetVersionResponse& response, keymaster_error_t* error);
151 
152 /**
153  * This MessageVersion overload determines the message version to use given the provided client and
154  * server messages.  If the client gets an error when it sends GetVersion2Request, it should send
155  * GetVersionRequest and use the above overload.  If the server receives GetVersionRequest, it
156  * should assume it should use message version 3 and return GetVersionResponse(2, 0, 0).
157  */
158 struct GetVersion2Request;
159 struct GetVersion2Response;
160 int32_t NegotiateMessageVersion(const GetVersion2Request& request,
161                                 const GetVersion2Response& response);
162 
163 struct KeymasterMessage : public Serializable {
KeymasterMessageKeymasterMessage164     explicit KeymasterMessage(int32_t ver) : message_version(ver) { assert(ver >= 0); }
165 
166     // The message version that should be used for this message.  This indicates how the data is
167     // serialized/deserialized. Commonly, higher message versions serialize/deserialize additional
168     // arguments, though there is no specific rule limiting later version to adding parameters.
169     const int32_t message_version;
170 };
171 
172 /**
173  * All responses include an error value, and if the error is not KM_ERROR_OK, return no additional
174  * data.
175  */
176 struct KeymasterResponse : public KeymasterMessage {
KeymasterResponseKeymasterResponse177     explicit KeymasterResponse(int32_t ver)
178         : KeymasterMessage(ver), error(KM_ERROR_UNKNOWN_ERROR) {}
179 
180     size_t SerializedSize() const override;
181     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
182     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
183 
184     virtual size_t NonErrorSerializedSize() const = 0;
185     virtual uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const = 0;
186     virtual bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) = 0;
187 
188     keymaster_error_t error;
189 };
190 
191 // Abstract base for empty requests.
192 struct EmptyKeymasterRequest : public KeymasterMessage {
EmptyKeymasterRequestEmptyKeymasterRequest193     explicit EmptyKeymasterRequest(int32_t ver) : KeymasterMessage(ver) {}
194 
SerializedSizeEmptyKeymasterRequest195     size_t SerializedSize() const override { return 0; }
SerializeEmptyKeymasterRequest196     uint8_t* Serialize(uint8_t* buf, const uint8_t*) const override { return buf; }
DeserializeEmptyKeymasterRequest197     bool Deserialize(const uint8_t**, const uint8_t*) override { return true; };
198 };
199 
200 // Empty response.
201 struct EmptyKeymasterResponse : public KeymasterResponse {
EmptyKeymasterResponseEmptyKeymasterResponse202     explicit EmptyKeymasterResponse(int32_t ver) : KeymasterResponse(ver) {}
203 
NonErrorSerializedSizeEmptyKeymasterResponse204     size_t NonErrorSerializedSize() const override { return 0; }
NonErrorSerializeEmptyKeymasterResponse205     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
NonErrorDeserializeEmptyKeymasterResponse206     bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
207 };
208 
209 // TODO(swillden): Remove when Keymaster1 is deleted
210 struct SupportedAlgorithmsRequest : public KeymasterMessage {
SupportedAlgorithmsRequestSupportedAlgorithmsRequest211     explicit SupportedAlgorithmsRequest(int32_t ver) : KeymasterMessage(ver) {}
212 
SerializedSizeSupportedAlgorithmsRequest213     size_t SerializedSize() const override { return 0; };
SerializeSupportedAlgorithmsRequest214     uint8_t* Serialize(uint8_t* buf, const uint8_t* /* end */) const override { return buf; }
DeserializeSupportedAlgorithmsRequest215     bool Deserialize(const uint8_t** /* buf_ptr */, const uint8_t* /* end */) override {
216         return true;
217     }
218 };
219 
220 // TODO(swillden): Remove when Keymaster1 is deleted
221 struct SupportedByAlgorithmRequest : public KeymasterMessage {
SupportedByAlgorithmRequestSupportedByAlgorithmRequest222     explicit SupportedByAlgorithmRequest(int32_t ver) : KeymasterMessage(ver) {}
223 
SerializedSizeSupportedByAlgorithmRequest224     size_t SerializedSize() const override { return sizeof(uint32_t); };
SerializeSupportedByAlgorithmRequest225     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
226         return append_uint32_to_buf(buf, end, algorithm);
227     }
DeserializeSupportedByAlgorithmRequest228     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
229         return copy_uint32_from_buf(buf_ptr, end, &algorithm);
230     }
231 
232     keymaster_algorithm_t algorithm;
233 };
234 
235 // TODO(swillden): Remove when Keymaster1 is deleted
236 struct SupportedImportFormatsRequest : public SupportedByAlgorithmRequest {
SupportedImportFormatsRequestSupportedImportFormatsRequest237     explicit SupportedImportFormatsRequest(int32_t ver) : SupportedByAlgorithmRequest(ver) {}
238 };
239 
240 // TODO(swillden): Remove when Keymaster1 is deleted
241 struct SupportedExportFormatsRequest : public SupportedByAlgorithmRequest {
SupportedExportFormatsRequestSupportedExportFormatsRequest242     explicit SupportedExportFormatsRequest(int32_t ver) : SupportedByAlgorithmRequest(ver) {}
243 };
244 
245 // TODO(swillden): Remove when Keymaster1 is deleted
246 struct SupportedByAlgorithmAndPurposeRequest : public KeymasterMessage {
SupportedByAlgorithmAndPurposeRequestSupportedByAlgorithmAndPurposeRequest247     explicit SupportedByAlgorithmAndPurposeRequest(int32_t ver) : KeymasterMessage(ver) {}
248 
SerializedSizeSupportedByAlgorithmAndPurposeRequest249     size_t SerializedSize() const override { return sizeof(uint32_t) * 2; };
SerializeSupportedByAlgorithmAndPurposeRequest250     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
251         buf = append_uint32_to_buf(buf, end, algorithm);
252         return append_uint32_to_buf(buf, end, purpose);
253     }
DeserializeSupportedByAlgorithmAndPurposeRequest254     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
255         return copy_uint32_from_buf(buf_ptr, end, &algorithm) &&
256                copy_uint32_from_buf(buf_ptr, end, &purpose);
257     }
258 
259     keymaster_algorithm_t algorithm;
260     keymaster_purpose_t purpose;
261 };
262 
263 // TODO(swillden): Remove when Keymaster1 is deleted
264 struct SupportedBlockModesRequest : public SupportedByAlgorithmAndPurposeRequest {
SupportedBlockModesRequestSupportedBlockModesRequest265     explicit SupportedBlockModesRequest(int32_t ver) : SupportedByAlgorithmAndPurposeRequest(ver) {}
266 };
267 
268 // TODO(swillden): Remove when Keymaster1 is deleted
269 struct SupportedPaddingModesRequest : public SupportedByAlgorithmAndPurposeRequest {
SupportedPaddingModesRequestSupportedPaddingModesRequest270     explicit SupportedPaddingModesRequest(int32_t ver)
271         : SupportedByAlgorithmAndPurposeRequest(ver) {}
272 };
273 
274 // TODO(swillden): Remove when Keymaster1 is deleted
275 struct SupportedDigestsRequest : public SupportedByAlgorithmAndPurposeRequest {
SupportedDigestsRequestSupportedDigestsRequest276     explicit SupportedDigestsRequest(int32_t ver) : SupportedByAlgorithmAndPurposeRequest(ver) {}
277 };
278 
279 // TODO(swillden): Remove when Keymaster1 is deleted
280 template <typename T> struct SupportedResponse : public KeymasterResponse {
SupportedResponseSupportedResponse281     explicit SupportedResponse(int32_t ver)
282         : KeymasterResponse(ver), results(nullptr), results_length(0) {}
~SupportedResponseSupportedResponse283     ~SupportedResponse() { delete[] results; }
284 
SetResultsSupportedResponse285     template <size_t N> void SetResults(const T (&arr)[N]) { SetResults(arr, N); }
286 
SetResultsSupportedResponse287     void SetResults(const T* arr, size_t n) {
288         delete[] results;
289         results_length = 0;
290         results = dup_array(arr, n);
291         if (results == nullptr) {
292             error = KM_ERROR_MEMORY_ALLOCATION_FAILED;
293         } else {
294             results_length = n;
295             error = KM_ERROR_OK;
296         }
297     }
298 
NonErrorSerializedSizeSupportedResponse299     size_t NonErrorSerializedSize() const override {
300         return sizeof(uint32_t) + results_length * sizeof(uint32_t);
301     }
NonErrorSerializeSupportedResponse302     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
303         return append_uint32_array_to_buf(buf, end, results, results_length);
304     }
NonErrorDeserializeSupportedResponse305     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
306         delete[] results;
307         results = nullptr;
308         UniquePtr<T[]> tmp;
309         if (!copy_uint32_array_from_buf(buf_ptr, end, &tmp, &results_length)) return false;
310         results = tmp.release();
311         return true;
312     }
313 
314     T* results;
315     size_t results_length;
316 };
317 
318 // TODO(swillden): Remove when Keymaster1 is deleted
319 struct SupportedAlgorithmsResponse : public SupportedResponse<keymaster_algorithm_t> {
SupportedAlgorithmsResponseSupportedAlgorithmsResponse320     explicit SupportedAlgorithmsResponse(int32_t ver)
321         : SupportedResponse<keymaster_algorithm_t>(ver) {}
322 };
323 
324 // TODO(swillden): Remove when Keymaster1 is deleted
325 struct SupportedBlockModesResponse : public SupportedResponse<keymaster_block_mode_t> {
SupportedBlockModesResponseSupportedBlockModesResponse326     explicit SupportedBlockModesResponse(int32_t ver)
327         : SupportedResponse<keymaster_block_mode_t>(ver) {}
328 };
329 
330 // TODO(swillden): Remove when Keymaster1 is deleted
331 struct SupportedPaddingModesResponse : public SupportedResponse<keymaster_padding_t> {
SupportedPaddingModesResponseSupportedPaddingModesResponse332     explicit SupportedPaddingModesResponse(int32_t ver)
333         : SupportedResponse<keymaster_padding_t>(ver) {}
334 };
335 
336 // TODO(swillden): Remove when Keymaster1 is deleted
337 struct SupportedDigestsResponse : public SupportedResponse<keymaster_digest_t> {
SupportedDigestsResponseSupportedDigestsResponse338     explicit SupportedDigestsResponse(int32_t ver) : SupportedResponse<keymaster_digest_t>(ver) {}
339 };
340 
341 // TODO(swillden): Remove when Keymaster1 is deleted
342 struct SupportedImportFormatsResponse : public SupportedResponse<keymaster_key_format_t> {
SupportedImportFormatsResponseSupportedImportFormatsResponse343     explicit SupportedImportFormatsResponse(int32_t ver)
344         : SupportedResponse<keymaster_key_format_t>(ver) {}
345 };
346 
347 // TODO(swillden): Remove when Keymaster1 is deleted
348 struct SupportedExportFormatsResponse : public SupportedResponse<keymaster_key_format_t> {
SupportedExportFormatsResponseSupportedExportFormatsResponse349     explicit SupportedExportFormatsResponse(int32_t ver)
350         : SupportedResponse<keymaster_key_format_t>(ver) {}
351 };
352 
353 struct GenerateKeyRequest : public KeymasterMessage {
GenerateKeyRequestGenerateKeyRequest354     explicit GenerateKeyRequest(int32_t ver) : KeymasterMessage(ver) {}
355 
356     size_t SerializedSize() const override;
357     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
358     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
359 
360     AuthorizationSet key_description;
361     KeymasterKeyBlob attestation_signing_key_blob;
362     AuthorizationSet attest_key_params;
363     KeymasterBlob issuer_subject;
364 };
365 
366 struct GenerateKeyResponse : public KeymasterResponse {
GenerateKeyResponseGenerateKeyResponse367     explicit GenerateKeyResponse(int32_t ver)
368         : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}
369 
370     size_t NonErrorSerializedSize() const override;
371     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
372     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
373 
374     KeymasterKeyBlob key_blob;
375     AuthorizationSet enforced;
376     AuthorizationSet unenforced;
377     CertificateChain certificate_chain;
378 };
379 
380 struct GenerateRkpKeyRequest : KeymasterMessage {
GenerateRkpKeyRequestGenerateRkpKeyRequest381     explicit GenerateRkpKeyRequest(int32_t ver) : KeymasterMessage(ver) {}
382 
SerializedSizeGenerateRkpKeyRequest383     size_t SerializedSize() const override { return sizeof(uint8_t); }
SerializeGenerateRkpKeyRequest384     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
385         return append_to_buf(buf, end, &test_mode, sizeof(uint8_t));
386     }
DeserializeGenerateRkpKeyRequest387     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
388         return copy_from_buf(buf_ptr, end, &test_mode, sizeof(uint8_t));
389     }
390 
391     bool test_mode = false;
392 };
393 
394 struct GenerateRkpKeyResponse : public KeymasterResponse {
GenerateRkpKeyResponseGenerateRkpKeyResponse395     explicit GenerateRkpKeyResponse(int32_t ver) : KeymasterResponse(ver) {}
396 
397     size_t NonErrorSerializedSize() const override;
398     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
399     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
400 
401     KeymasterKeyBlob key_blob;
402     KeymasterBlob maced_public_key;
403 };
404 
405 struct GenerateCsrRequest : public KeymasterMessage {
GenerateCsrRequestGenerateCsrRequest406     explicit GenerateCsrRequest(int32_t ver) : KeymasterMessage(ver) {}
407 
~GenerateCsrRequestGenerateCsrRequest408     ~GenerateCsrRequest() override { delete[] keys_to_sign_array; }
409 
410     size_t SerializedSize() const override;
411     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
412     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
413     void SetKeyToSign(uint32_t index, const void* data, size_t length);
414     void SetEndpointEncCertChain(const void* data, size_t length);
415     void SetChallenge(const void* data, size_t length);
416 
417     bool test_mode = false;
418     size_t num_keys = 0;
419     KeymasterBlob* keys_to_sign_array = nullptr;
420     KeymasterBlob endpoint_enc_cert_chain;
421     KeymasterBlob challenge;
422 };
423 
424 struct GenerateCsrResponse : public KeymasterResponse {
GenerateCsrResponseGenerateCsrResponse425     explicit GenerateCsrResponse(int32_t ver) : KeymasterResponse(ver) {}
426 
427     size_t NonErrorSerializedSize() const override;
428     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
429     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
430 
431     KeymasterBlob keys_to_sign_mac;
432     KeymasterBlob device_info_blob;
433     KeymasterBlob protected_data_blob;
434 };
435 
436 struct GenerateCsrV2Request : public KeymasterMessage {
GenerateCsrV2RequestGenerateCsrV2Request437     explicit GenerateCsrV2Request(int32_t ver) : KeymasterMessage(ver) {}
438 
~GenerateCsrV2RequestGenerateCsrV2Request439     ~GenerateCsrV2Request() override { delete[] keys_to_sign_array; }
440 
441     size_t SerializedSize() const override;
442     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
443     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
444     bool InitKeysToSign(uint32_t count);
445     void SetKeyToSign(uint32_t index, const void* data, size_t length);
446     void SetChallenge(const void* data, size_t length);
447 
448     uint32_t num_keys = 0;
449     KeymasterBlob* keys_to_sign_array = nullptr;
450     KeymasterBlob challenge;
451 };
452 
453 struct GenerateCsrV2Response : public KeymasterResponse {
GenerateCsrV2ResponseGenerateCsrV2Response454     explicit GenerateCsrV2Response(int32_t ver) : KeymasterResponse(ver) {}
455 
456     size_t NonErrorSerializedSize() const override;
457     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
458     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
459 
460     KeymasterBlob csr;
461 };
462 
463 struct GetKeyCharacteristicsRequest : public KeymasterMessage {
GetKeyCharacteristicsRequestGetKeyCharacteristicsRequest464     explicit GetKeyCharacteristicsRequest(int32_t ver) : KeymasterMessage(ver) {
465         key_blob.key_material = nullptr;
466         key_blob.key_material_size = 0;
467     }
468     ~GetKeyCharacteristicsRequest();
469 
470     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialGetKeyCharacteristicsRequest471     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
472         SetKeyMaterial(blob.key_material, blob.key_material_size);
473     }
474 
475     size_t SerializedSize() const override;
476     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
477     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
478 
479     keymaster_key_blob_t key_blob;
480     AuthorizationSet additional_params;
481 };
482 
483 struct GetKeyCharacteristicsResponse : public KeymasterResponse {
GetKeyCharacteristicsResponseGetKeyCharacteristicsResponse484     explicit GetKeyCharacteristicsResponse(int32_t ver) : KeymasterResponse(ver) {}
485 
486     size_t NonErrorSerializedSize() const override;
487     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
488     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
489 
490     AuthorizationSet enforced;
491     AuthorizationSet unenforced;
492 };
493 
494 struct BeginOperationRequest : public KeymasterMessage {
BeginOperationRequestBeginOperationRequest495     explicit BeginOperationRequest(int32_t ver) : KeymasterMessage(ver) {
496         key_blob.key_material = nullptr;
497         key_blob.key_material_size = 0;
498     }
~BeginOperationRequestBeginOperationRequest499     ~BeginOperationRequest() { delete[] key_blob.key_material; }
500 
501     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialBeginOperationRequest502     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
503         SetKeyMaterial(blob.key_material, blob.key_material_size);
504     }
505 
506     size_t SerializedSize() const override;
507     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
508     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
509 
510     keymaster_purpose_t purpose;
511     keymaster_key_blob_t key_blob;
512     AuthorizationSet additional_params;
513 };
514 
515 struct BeginOperationResponse : public KeymasterResponse {
BeginOperationResponseBeginOperationResponse516     explicit BeginOperationResponse(int32_t ver) : KeymasterResponse(ver) {}
517 
518     size_t NonErrorSerializedSize() const override;
519     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
520     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
521 
522     keymaster_operation_handle_t op_handle;
523     AuthorizationSet output_params;
524 };
525 
526 struct UpdateOperationRequest : public KeymasterMessage {
UpdateOperationRequestUpdateOperationRequest527     explicit UpdateOperationRequest(int32_t ver) : KeymasterMessage(ver) {}
528 
529     size_t SerializedSize() const override;
530     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
531     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
532 
533     keymaster_operation_handle_t op_handle;
534     Buffer input;
535     AuthorizationSet additional_params;
536 };
537 
538 struct UpdateOperationResponse : public KeymasterResponse {
UpdateOperationResponseUpdateOperationResponse539     explicit UpdateOperationResponse(int32_t ver) : KeymasterResponse(ver), input_consumed(0) {}
540 
541     size_t NonErrorSerializedSize() const override;
542     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
543     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
544 
545     Buffer output;
546     size_t input_consumed;
547     AuthorizationSet output_params;
548 };
549 
550 struct FinishOperationRequest : public KeymasterMessage {
FinishOperationRequestFinishOperationRequest551     explicit FinishOperationRequest(int32_t ver) : KeymasterMessage(ver) {}
552 
553     size_t SerializedSize() const override;
554     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
555     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
556 
557     keymaster_operation_handle_t op_handle;
558     Buffer input;
559     Buffer signature;
560     AuthorizationSet additional_params;
561 };
562 
563 struct FinishOperationResponse : public KeymasterResponse {
FinishOperationResponseFinishOperationResponse564     explicit FinishOperationResponse(int32_t ver) : KeymasterResponse(ver) {}
565 
566     size_t NonErrorSerializedSize() const override;
567     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
568     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
569 
570     Buffer output;
571     AuthorizationSet output_params;
572 };
573 
574 struct AbortOperationRequest : public KeymasterMessage {
AbortOperationRequestAbortOperationRequest575     explicit AbortOperationRequest(int32_t ver) : KeymasterMessage(ver) {}
576 
SerializedSizeAbortOperationRequest577     size_t SerializedSize() const override { return sizeof(uint64_t); }
SerializeAbortOperationRequest578     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
579         return append_uint64_to_buf(buf, end, op_handle);
580     }
DeserializeAbortOperationRequest581     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
582         return copy_uint64_from_buf(buf_ptr, end, &op_handle);
583     }
584 
585     keymaster_operation_handle_t op_handle;
586 };
587 
588 using AbortOperationResponse = EmptyKeymasterResponse;
589 
590 struct AddEntropyRequest : public KeymasterMessage {
AddEntropyRequestAddEntropyRequest591     explicit AddEntropyRequest(int32_t ver) : KeymasterMessage(ver) {}
592 
593     size_t SerializedSize() const override;
594     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
595     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
596 
597     Buffer random_data;
598 };
599 
600 using AddEntropyResponse = EmptyKeymasterResponse;
601 
602 struct ImportKeyRequest : public KeymasterMessage {
ImportKeyRequestImportKeyRequest603     explicit ImportKeyRequest(int32_t ver) : KeymasterMessage(ver) {}
604 
605     size_t SerializedSize() const override;
606     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
607     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
608 
609     AuthorizationSet key_description;
610     keymaster_key_format_t key_format;
611     KeymasterKeyBlob key_data;
612     KeymasterKeyBlob attestation_signing_key_blob;
613     AuthorizationSet attest_key_params;
614     KeymasterBlob issuer_subject;
615 };
616 
617 struct ImportKeyResponse : public KeymasterResponse {
ImportKeyResponseImportKeyResponse618     explicit ImportKeyResponse(int32_t ver)
619         : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}
620     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialImportKeyResponse621     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
622         SetKeyMaterial(blob.key_material, blob.key_material_size);
623     }
624 
625     size_t NonErrorSerializedSize() const override;
626     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
627     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
628 
629     KeymasterKeyBlob key_blob;
630     AuthorizationSet enforced;
631     AuthorizationSet unenforced;
632     CertificateChain certificate_chain;
633 };
634 
635 struct ExportKeyRequest : public KeymasterMessage {
ExportKeyRequestExportKeyRequest636     explicit ExportKeyRequest(int32_t ver) : KeymasterMessage(ver) {
637         key_blob.key_material = nullptr;
638         key_blob.key_material_size = 0;
639     }
~ExportKeyRequestExportKeyRequest640     ~ExportKeyRequest() { delete[] key_blob.key_material; }
641 
642     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialExportKeyRequest643     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
644         SetKeyMaterial(blob.key_material, blob.key_material_size);
645     }
646 
647     size_t SerializedSize() const override;
648     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
649     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
650 
651     AuthorizationSet additional_params;
652     keymaster_key_format_t key_format;
653     keymaster_key_blob_t key_blob;
654 };
655 
656 struct ExportKeyResponse : public KeymasterResponse {
ExportKeyResponseExportKeyResponse657     explicit ExportKeyResponse(int32_t ver) : KeymasterResponse(ver), key_data(nullptr) {}
~ExportKeyResponseExportKeyResponse658     ~ExportKeyResponse() { delete[] key_data; }
659 
660     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialExportKeyResponse661     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
662         SetKeyMaterial(blob.key_material, blob.key_material_size);
663     }
664 
665     size_t NonErrorSerializedSize() const override;
666     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
667     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
668 
669     uint8_t* key_data;
670     size_t key_data_length;
671 };
672 
673 struct DeleteKeyRequest : public KeymasterMessage {
DeleteKeyRequestDeleteKeyRequest674     explicit DeleteKeyRequest(int32_t ver) : KeymasterMessage(ver) {
675         key_blob.key_material = nullptr;
676         key_blob.key_material_size = 0;
677     }
~DeleteKeyRequestDeleteKeyRequest678     ~DeleteKeyRequest() { delete[] key_blob.key_material; }
679 
680     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialDeleteKeyRequest681     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
682         SetKeyMaterial(blob.key_material, blob.key_material_size);
683     }
684 
685     size_t SerializedSize() const override;
686     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
687     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
688 
689     keymaster_key_blob_t key_blob;
690 };
691 
692 using DeleteKeyResponse = EmptyKeymasterResponse;
693 
694 struct DeleteAllKeysRequest : public EmptyKeymasterRequest {
DeleteAllKeysRequestDeleteAllKeysRequest695     explicit DeleteAllKeysRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
696 };
697 
698 using DeleteAllKeysResponse = EmptyKeymasterResponse;
699 
700 struct DestroyAttestationIdsRequest : public EmptyKeymasterRequest {
DestroyAttestationIdsRequestDestroyAttestationIdsRequest701     explicit DestroyAttestationIdsRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
702 };
703 
704 using DestroyAttestationIdsResponse = EmptyKeymasterResponse;
705 
706 struct GetVersionRequest : public EmptyKeymasterRequest {
707     // GetVersionRequest ctor takes a version arg so it has the same signature as others, but the
708     // value is ignored because it is not not versionable.
709     explicit GetVersionRequest(uint32_t /* ver */ = 0)
710         : EmptyKeymasterRequest(0 /* not versionable */) {}
711 };
712 
713 struct GetVersionResponse : public KeymasterResponse {
714     // GetVersionResponse ctor takes a version arg so it has the same signature as others, but the
715     // value is ignored because it is not not versionable.
716     explicit GetVersionResponse(uint32_t /* ver */ = 0)
717         : KeymasterResponse(0 /* not versionable */), major_ver(0), minor_ver(0), subminor_ver(0) {}
718 
719     size_t NonErrorSerializedSize() const override;
720     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
721     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
722 
723     uint8_t major_ver;
724     uint8_t minor_ver;
725     uint8_t subminor_ver;
726 };
727 
728 struct AttestKeyRequest : public KeymasterMessage {
AttestKeyRequestAttestKeyRequest729     explicit AttestKeyRequest(int32_t ver) : KeymasterMessage(ver) {
730         key_blob.key_material = nullptr;
731         key_blob.key_material_size = 0;
732     }
733     ~AttestKeyRequest();
734 
735     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialAttestKeyRequest736     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
737         SetKeyMaterial(blob.key_material, blob.key_material_size);
738     }
739 
740     size_t SerializedSize() const override;
741     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
742     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
743 
744     keymaster_key_blob_t key_blob;
745     AuthorizationSet attest_params;
746 };
747 
748 struct AttestKeyResponse : public KeymasterResponse {
AttestKeyResponseAttestKeyResponse749     explicit AttestKeyResponse(int32_t ver) : KeymasterResponse(ver) {}
750 
751     size_t NonErrorSerializedSize() const override;
752     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
753     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
754 
755     CertificateChain certificate_chain;
756 };
757 
758 struct UpgradeKeyRequest : public KeymasterMessage {
UpgradeKeyRequestUpgradeKeyRequest759     explicit UpgradeKeyRequest(int32_t ver) : KeymasterMessage(ver) { key_blob = {nullptr, 0}; }
760     ~UpgradeKeyRequest();
761 
762     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialUpgradeKeyRequest763     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
764         SetKeyMaterial(blob.key_material, blob.key_material_size);
765     }
766 
767     size_t SerializedSize() const override;
768     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
769     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
770 
771     keymaster_key_blob_t key_blob;
772     AuthorizationSet upgrade_params;
773 };
774 
775 struct UpgradeKeyResponse : public KeymasterResponse {
UpgradeKeyResponseUpgradeKeyResponse776     explicit UpgradeKeyResponse(int32_t ver) : KeymasterResponse(ver) {
777         upgraded_key = {nullptr, 0};
778     }
779     ~UpgradeKeyResponse();
780 
781     size_t NonErrorSerializedSize() const override;
782     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
783     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
784 
785     keymaster_key_blob_t upgraded_key;
786 };
787 
788 struct ConfigureRequest : public KeymasterMessage {
ConfigureRequestConfigureRequest789     explicit ConfigureRequest(int32_t ver) : KeymasterMessage(ver) {}
790 
SerializedSizeConfigureRequest791     size_t SerializedSize() const override { return sizeof(os_version) + sizeof(os_patchlevel); }
SerializeConfigureRequest792     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
793         buf = append_uint32_to_buf(buf, end, os_version);
794         return append_uint32_to_buf(buf, end, os_patchlevel);
795     }
DeserializeConfigureRequest796     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
797         return copy_uint32_from_buf(buf_ptr, end, &os_version) &&
798                copy_uint32_from_buf(buf_ptr, end, &os_patchlevel);
799     }
800 
801     uint32_t os_version;
802     uint32_t os_patchlevel;  // YYYYMM
803 };
804 
805 using ConfigureResponse = EmptyKeymasterResponse;
806 
807 struct HmacSharingParameters : public Serializable {
HmacSharingParametersHmacSharingParameters808     HmacSharingParameters() : seed({}) { memset(nonce, 0, sizeof(nonce)); }
HmacSharingParametersHmacSharingParameters809     HmacSharingParameters(HmacSharingParameters&& other) {
810         seed = std::move(other.seed);
811         memcpy(nonce, other.nonce, sizeof(nonce));
812     }
813 
SetSeedHmacSharingParameters814     void SetSeed(KeymasterBlob&& value) { seed = std::move(value); }
815 
816     size_t SerializedSize() const override;
817     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
818     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
819 
820     KeymasterBlob seed{};
821     uint8_t nonce[32];
822 };
823 
824 struct HmacSharingParametersArray : public Serializable {
HmacSharingParametersArrayHmacSharingParametersArray825     HmacSharingParametersArray() : params_array(nullptr), num_params(0) {}
HmacSharingParametersArrayHmacSharingParametersArray826     HmacSharingParametersArray(HmacSharingParametersArray&& other) {
827         delete[] params_array;
828         params_array = other.params_array;
829         num_params = other.num_params;
830         other.params_array = nullptr;
831         other.num_params = 0;
832     }
~HmacSharingParametersArrayHmacSharingParametersArray833     ~HmacSharingParametersArray() override { delete[] params_array; }
834 
835     size_t SerializedSize() const override;
836     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
837     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
838 
839     HmacSharingParameters* params_array;
840     size_t num_params;
841 };
842 
843 struct GetHmacSharingParametersRequest : public EmptyKeymasterRequest {
GetHmacSharingParametersRequestGetHmacSharingParametersRequest844     explicit GetHmacSharingParametersRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
845 };
846 
847 struct GetHmacSharingParametersResponse : public KeymasterResponse {
GetHmacSharingParametersResponseGetHmacSharingParametersResponse848     explicit GetHmacSharingParametersResponse(int32_t ver) : KeymasterResponse(ver) {}
GetHmacSharingParametersResponseGetHmacSharingParametersResponse849     GetHmacSharingParametersResponse(GetHmacSharingParametersResponse&& other)
850         : KeymasterResponse(other.message_version), params(std::move(other.params)) {}
851 
SetSeedGetHmacSharingParametersResponse852     void SetSeed(KeymasterBlob&& seed_data) { params.SetSeed(std::move(seed_data)); }
853 
NonErrorSerializedSizeGetHmacSharingParametersResponse854     size_t NonErrorSerializedSize() const override { return params.SerializedSize(); }
NonErrorSerializeGetHmacSharingParametersResponse855     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
856         return params.Serialize(buf, end);
857     }
NonErrorDeserializeGetHmacSharingParametersResponse858     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
859         return params.Deserialize(buf_ptr, end);
860     }
861 
862     HmacSharingParameters params;
863 };
864 
865 struct ComputeSharedHmacRequest : public KeymasterMessage {
ComputeSharedHmacRequestComputeSharedHmacRequest866     explicit ComputeSharedHmacRequest(int32_t ver) : KeymasterMessage(ver) {}
867 
SerializedSizeComputeSharedHmacRequest868     size_t SerializedSize() const override { return params_array.SerializedSize(); }
SerializeComputeSharedHmacRequest869     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
870         return params_array.Serialize(buf, end);
871     }
DeserializeComputeSharedHmacRequest872     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
873         return params_array.Deserialize(buf_ptr, end);
874     }
875 
876     HmacSharingParametersArray params_array;
877 };
878 
879 struct ComputeSharedHmacResponse : public KeymasterResponse {
ComputeSharedHmacResponseComputeSharedHmacResponse880     explicit ComputeSharedHmacResponse(int32_t ver) : KeymasterResponse(ver) {}
ComputeSharedHmacResponseComputeSharedHmacResponse881     ComputeSharedHmacResponse(ComputeSharedHmacResponse&& other)
882         : KeymasterResponse(other.message_version) {
883         sharing_check = std::move(other.sharing_check);
884     }
885 
886     size_t NonErrorSerializedSize() const override;
887     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
888     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
889 
890     KeymasterBlob sharing_check;
891 };
892 
893 struct ImportWrappedKeyRequest : public KeymasterMessage {
ImportWrappedKeyRequestImportWrappedKeyRequest894     explicit ImportWrappedKeyRequest(int32_t ver) : KeymasterMessage(ver) {}
895 
896     void SetWrappedMaterial(const void* key_material, size_t length);
897     void SetWrappingMaterial(const void* key_material, size_t length);
898     void SetMaskingKeyMaterial(const void* key_material, size_t length);
899 
SetKeyMaterialImportWrappedKeyRequest900     void SetKeyMaterial(const keymaster_key_blob_t& wrapped, const keymaster_key_blob_t& wrapping) {
901         SetWrappedMaterial(wrapped.key_material, wrapped.key_material_size);
902         SetWrappingMaterial(wrapping.key_material, wrapping.key_material_size);
903     }
904 
905     size_t SerializedSize() const override;
906     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
907     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
908 
909     KeymasterKeyBlob wrapped_key;
910     KeymasterKeyBlob wrapping_key;
911     KeymasterKeyBlob masking_key;
912     AuthorizationSet additional_params;
913     uint64_t password_sid;
914     uint64_t biometric_sid;
915 };
916 
917 struct ImportWrappedKeyResponse : public KeymasterResponse {
918     explicit ImportWrappedKeyResponse(int32_t ver = kDefaultMessageVersion)
KeymasterResponseImportWrappedKeyResponse919         : KeymasterResponse(ver), key_blob{}, certificate_chain{} {}
920     void SetKeyMaterial(const void* key_material, size_t length);
SetKeyMaterialImportWrappedKeyResponse921     void SetKeyMaterial(const keymaster_key_blob_t& blob) {
922         SetKeyMaterial(blob.key_material, blob.key_material_size);
923     }
924 
925     size_t NonErrorSerializedSize() const override;
926     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override;
927     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
928 
929     KeymasterKeyBlob key_blob;
930     AuthorizationSet enforced;
931     AuthorizationSet unenforced;
932     CertificateChain certificate_chain;
933 };
934 
935 struct HardwareAuthToken : public Serializable {
936     HardwareAuthToken() = default;
HardwareAuthTokenHardwareAuthToken937     HardwareAuthToken(HardwareAuthToken&& other) {
938         challenge = other.challenge;
939         user_id = other.user_id;
940         authenticator_id = other.authenticator_id;
941         authenticator_type = other.authenticator_type;
942         timestamp = other.timestamp;
943         mac = std::move(other.mac);
944     }
945 
946     size_t SerializedSize() const override;
947     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
948     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
949 
950     uint64_t challenge{};
951     uint64_t user_id{};
952     uint64_t authenticator_id{};
953     hw_authenticator_type_t authenticator_type{};
954     uint64_t timestamp{};
955     KeymasterBlob mac;
956 };
957 
958 struct VerificationToken : public Serializable {
959     VerificationToken() = default;
VerificationTokenVerificationToken960     VerificationToken(VerificationToken&& other) {
961         challenge = other.challenge;
962         timestamp = other.timestamp;
963         parameters_verified = std::move(other.parameters_verified);
964         security_level = other.security_level;
965         mac = std::move(other.mac);
966     }
967 
968     size_t SerializedSize() const override;
969     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
970     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
971 
972     uint64_t challenge{};
973     uint64_t timestamp{};
974     AuthorizationSet parameters_verified{};
975     keymaster_security_level_t security_level{};
976     KeymasterBlob mac{};
977 };
978 
979 struct VerifyAuthorizationRequest : public KeymasterMessage {
VerifyAuthorizationRequestVerifyAuthorizationRequest980     explicit VerifyAuthorizationRequest(int32_t ver) : KeymasterMessage(ver) {}
981     VerifyAuthorizationRequest(VerifyAuthorizationRequest&& other) = default;
982 
SerializedSizeVerifyAuthorizationRequest983     size_t SerializedSize() const override {
984         return sizeof(challenge) + parameters_to_verify.SerializedSize() +
985                auth_token.SerializedSize();
986     }
987 
SerializeVerifyAuthorizationRequest988     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
989         buf = append_uint64_to_buf(buf, end, challenge);
990         buf = parameters_to_verify.Serialize(buf, end);
991         return auth_token.Serialize(buf, end);
992     }
993 
DeserializeVerifyAuthorizationRequest994     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
995         return (copy_uint64_from_buf(buf_ptr, end, &challenge) &&
996                 parameters_to_verify.Deserialize(buf_ptr, end) &&
997                 auth_token.Deserialize(buf_ptr, end));
998     }
999 
1000     uint64_t challenge{};
1001     AuthorizationSet parameters_to_verify;
1002     HardwareAuthToken auth_token;
1003 };
1004 
1005 struct VerifyAuthorizationResponse : public KeymasterResponse {
VerifyAuthorizationResponseVerifyAuthorizationResponse1006     explicit VerifyAuthorizationResponse(int32_t ver) : KeymasterResponse(ver) {}
1007     VerifyAuthorizationResponse(VerifyAuthorizationResponse&& other) = default;
1008 
NonErrorSerializedSizeVerifyAuthorizationResponse1009     size_t NonErrorSerializedSize() const override {
1010         return sizeof(error) + token.SerializedSize();
1011     }
NonErrorSerializeVerifyAuthorizationResponse1012     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
1013         buf = append_uint32_to_buf(buf, end, error);
1014         return token.Serialize(buf, end);
1015     }
NonErrorDeserializeVerifyAuthorizationResponse1016     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1017         return copy_uint32_from_buf(buf_ptr, end, &error) && token.Deserialize(buf_ptr, end);
1018     }
1019 
1020     VerificationToken token;
1021 };
1022 
1023 struct EarlyBootEndedRequest : public EmptyKeymasterRequest {
EarlyBootEndedRequestEarlyBootEndedRequest1024     explicit EarlyBootEndedRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
1025 };
1026 
1027 struct EarlyBootEndedResponse : public KeymasterResponse {
EarlyBootEndedResponseEarlyBootEndedResponse1028     explicit EarlyBootEndedResponse(int32_t ver) : KeymasterResponse(ver) {}
1029 
NonErrorSerializedSizeEarlyBootEndedResponse1030     size_t NonErrorSerializedSize() const override { return 0; }
NonErrorSerializeEarlyBootEndedResponse1031     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
NonErrorDeserializeEarlyBootEndedResponse1032     bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
1033 };
1034 
1035 struct DeviceLockedRequest : public KeymasterMessage {
DeviceLockedRequestDeviceLockedRequest1036     explicit DeviceLockedRequest(int32_t ver) : KeymasterMessage(ver) {}
DeviceLockedRequestDeviceLockedRequest1037     explicit DeviceLockedRequest(int32_t ver, bool passwordOnly_, VerificationToken&& token_)
1038         : KeymasterMessage(ver), passwordOnly(passwordOnly_), token(std::move(token_)) {}
1039 
SerializedSizeDeviceLockedRequest1040     size_t SerializedSize() const override { return 1; }
SerializeDeviceLockedRequest1041     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1042         if (buf < end) *buf++ = passwordOnly ? 1 : 0;
1043         return token.Serialize(buf, end);
1044     }
DeserializeDeviceLockedRequest1045     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1046         if (*buf_ptr >= end) return false;
1047         passwordOnly = !!*(*buf_ptr)++;
1048         return token.Deserialize(buf_ptr, end);
1049     }
1050 
1051     bool passwordOnly;
1052     VerificationToken token;
1053 };
1054 
1055 struct DeviceLockedResponse : public KeymasterResponse {
DeviceLockedResponseDeviceLockedResponse1056     explicit DeviceLockedResponse(int32_t ver) : KeymasterResponse(ver) {}
1057 
NonErrorSerializedSizeDeviceLockedResponse1058     size_t NonErrorSerializedSize() const override { return 0; }
NonErrorSerializeDeviceLockedResponse1059     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override { return buf; }
NonErrorDeserializeDeviceLockedResponse1060     bool NonErrorDeserialize(const uint8_t**, const uint8_t*) override { return true; }
1061 };
1062 
1063 struct GetVersion2Request : public KeymasterMessage {
1064     // GetVersion2Request ctor takes a version arg so it has the same signature as others, but the
1065     // value is ignored because it's not versionable.
1066     explicit GetVersion2Request(uint32_t /* ver */ = 0)
1067         : KeymasterMessage(0 /* not versionable */) {}
1068 
SerializedSizeGetVersion2Request1069     size_t SerializedSize() const override { return sizeof(uint32_t); /* max message version */ }
SerializeGetVersion2Request1070     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1071         return append_uint32_to_buf(buf, end, max_message_version);
1072     }
DeserializeGetVersion2Request1073     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1074         return copy_uint32_from_buf(buf_ptr, end, &max_message_version);
1075     }
1076 
1077     uint32_t max_message_version = kDefaultMessageVersion;
1078 };
1079 
1080 struct GetVersion2Response : public KeymasterResponse {
1081     // GetVersion2Request ctor takes a version arg so it has the same signature as others, but the
1082     // value is ignored because it's not versionable.
1083     explicit GetVersion2Response(uint32_t /* ver */ = 0)
1084         : KeymasterResponse(0 /* not versionable */) {}
1085 
1086     size_t NonErrorSerializedSize() const override;
1087     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t*) const override;
1088     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
1089 
1090     uint32_t max_message_version;
1091     KmVersion km_version;
1092     uint32_t km_date;
1093 };
1094 
1095 struct TimestampToken : public Serializable {
1096     explicit TimestampToken() = default;
TimestampTokenTimestampToken1097     TimestampToken(TimestampToken&& other) {
1098         challenge = other.challenge;
1099         timestamp = other.timestamp;
1100         security_level = other.security_level;
1101         mac = std::move(other.mac);
1102     }
SerializedSizeTimestampToken1103     size_t SerializedSize() const override {
1104         return sizeof(challenge) + sizeof(timestamp) + sizeof(security_level) +
1105                mac.SerializedSize();
1106     }
SerializeTimestampToken1107     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1108         buf = append_uint64_to_buf(buf, end, challenge);
1109         buf = append_uint64_to_buf(buf, end, timestamp);
1110         buf = append_uint32_to_buf(buf, end, security_level);
1111         return mac.Serialize(buf, end);
1112     }
DeserializeTimestampToken1113     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1114         return copy_uint64_from_buf(buf_ptr, end, &challenge) &&
1115                copy_uint64_from_buf(buf_ptr, end, &timestamp) &&
1116                copy_uint32_from_buf(buf_ptr, end, &security_level) && mac.Deserialize(buf_ptr, end);
1117     }
1118     uint64_t challenge{};
1119     uint64_t timestamp{};
1120     keymaster_security_level_t security_level{};
1121     KeymasterBlob mac{};
1122 };
1123 
1124 struct GenerateTimestampTokenRequest : public KeymasterMessage {
GenerateTimestampTokenRequestGenerateTimestampTokenRequest1125     explicit GenerateTimestampTokenRequest(int32_t ver) : KeymasterMessage(ver), challenge{} {}
SerializedSizeGenerateTimestampTokenRequest1126     size_t SerializedSize() const override { return sizeof(challenge); }
SerializeGenerateTimestampTokenRequest1127     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1128         return append_uint64_to_buf(buf, end, challenge);
1129     }
DeserializeGenerateTimestampTokenRequest1130     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1131         return copy_uint64_from_buf(buf_ptr, end, &challenge);
1132     }
1133     uint64_t challenge;
1134 };
1135 
1136 struct GenerateTimestampTokenResponse : public KeymasterResponse {
GenerateTimestampTokenResponseGenerateTimestampTokenResponse1137     explicit GenerateTimestampTokenResponse(int32_t ver) : KeymasterResponse(ver), token{} {}
NonErrorSerializedSizeGenerateTimestampTokenResponse1138     size_t NonErrorSerializedSize() const override { return token.SerializedSize(); }
NonErrorSerializeGenerateTimestampTokenResponse1139     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
1140         return token.Serialize(buf, end);
1141     }
NonErrorDeserializeGenerateTimestampTokenResponse1142     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1143         return token.Deserialize(buf_ptr, end);
1144     }
1145     TimestampToken token;
1146 };
1147 
1148 struct SetAttestationIdsRequest : public KeymasterMessage {
SetAttestationIdsRequestSetAttestationIdsRequest1149     explicit SetAttestationIdsRequest(int32_t ver) : KeymasterMessage(ver) {}
SerializedSizeSetAttestationIdsRequest1150     size_t SerializedSize() const override {
1151         return brand.SerializedSize()           //
1152                + device.SerializedSize()        //
1153                + product.SerializedSize()       //
1154                + serial.SerializedSize()        //
1155                + imei.SerializedSize()          //
1156                + meid.SerializedSize()          //
1157                + manufacturer.SerializedSize()  //
1158                + model.SerializedSize();
1159     }
1160 
SerializeSetAttestationIdsRequest1161     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1162         buf = brand.Serialize(buf, end);
1163         buf = device.Serialize(buf, end);
1164         buf = product.Serialize(buf, end);
1165         buf = serial.Serialize(buf, end);
1166         buf = imei.Serialize(buf, end);
1167         buf = meid.Serialize(buf, end);
1168         buf = manufacturer.Serialize(buf, end);
1169         return model.Serialize(buf, end);
1170     }
1171 
DeserializeSetAttestationIdsRequest1172     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1173         return brand.Deserialize(buf_ptr, end)            //
1174                && device.Deserialize(buf_ptr, end)        //
1175                && product.Deserialize(buf_ptr, end)       //
1176                && serial.Deserialize(buf_ptr, end)        //
1177                && imei.Deserialize(buf_ptr, end)          //
1178                && meid.Deserialize(buf_ptr, end)          //
1179                && manufacturer.Deserialize(buf_ptr, end)  //
1180                && model.Deserialize(buf_ptr, end);        //
1181     }
1182 
1183     Buffer brand;
1184     Buffer device;
1185     Buffer product;
1186     Buffer serial;
1187     Buffer imei;
1188     Buffer meid;
1189     Buffer manufacturer;
1190     Buffer model;
1191 };
1192 
1193 using SetAttestationIdsResponse = EmptyKeymasterResponse;
1194 
1195 struct SetAttestationIdsKM3Request : public KeymasterMessage {
SetAttestationIdsKM3RequestSetAttestationIdsKM3Request1196     explicit SetAttestationIdsKM3Request(int32_t ver) : KeymasterMessage(ver), base(ver) {}
SerializedSizeSetAttestationIdsKM3Request1197     size_t SerializedSize() const override {
1198         return base.SerializedSize()  //
1199                + second_imei.SerializedSize();
1200     }
1201 
SerializeSetAttestationIdsKM3Request1202     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1203         buf = base.Serialize(buf, end);
1204         return second_imei.Serialize(buf, end);
1205     }
1206 
DeserializeSetAttestationIdsKM3Request1207     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1208         return base.Deserialize(buf_ptr, end)             //
1209                && second_imei.Deserialize(buf_ptr, end);  //
1210     }
1211 
1212     SetAttestationIdsRequest base;
1213     Buffer second_imei;
1214 };
1215 
1216 using SetAttestationIdsKM3Response = EmptyKeymasterResponse;
1217 
1218 struct ConfigureVendorPatchlevelRequest : public KeymasterMessage {
ConfigureVendorPatchlevelRequestConfigureVendorPatchlevelRequest1219     explicit ConfigureVendorPatchlevelRequest(int32_t ver) : KeymasterMessage(ver) {}
1220 
SerializedSizeConfigureVendorPatchlevelRequest1221     size_t SerializedSize() const override { return sizeof(vendor_patchlevel); }
SerializeConfigureVendorPatchlevelRequest1222     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1223         return append_uint32_to_buf(buf, end, vendor_patchlevel);
1224     }
DeserializeConfigureVendorPatchlevelRequest1225     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1226         return copy_uint32_from_buf(buf_ptr, end, &vendor_patchlevel);
1227     }
1228 
1229     uint32_t vendor_patchlevel{};  // YYYYMMDD
1230 };
1231 
1232 using ConfigureVendorPatchlevelResponse = EmptyKeymasterResponse;
1233 
1234 struct ConfigureBootPatchlevelRequest : public KeymasterMessage {
ConfigureBootPatchlevelRequestConfigureBootPatchlevelRequest1235     explicit ConfigureBootPatchlevelRequest(int32_t ver) : KeymasterMessage(ver) {}
1236 
SerializedSizeConfigureBootPatchlevelRequest1237     size_t SerializedSize() const override { return sizeof(boot_patchlevel); }
SerializeConfigureBootPatchlevelRequest1238     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1239         return append_uint32_to_buf(buf, end, boot_patchlevel);
1240     }
DeserializeConfigureBootPatchlevelRequest1241     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1242         return copy_uint32_from_buf(buf_ptr, end, &boot_patchlevel);
1243     }
1244 
1245     uint32_t boot_patchlevel{};  // YYYYMMDD
1246 };
1247 
1248 using ConfigureBootPatchlevelResponse = EmptyKeymasterResponse;
1249 
1250 struct ConfigureVerifiedBootInfoRequest : public KeymasterMessage {
ConfigureVerifiedBootInfoRequestConfigureVerifiedBootInfoRequest1251     explicit ConfigureVerifiedBootInfoRequest(int32_t ver)
1252         : ConfigureVerifiedBootInfoRequest(ver, {}, {}, {}) {}
1253 
ConfigureVerifiedBootInfoRequestConfigureVerifiedBootInfoRequest1254     ConfigureVerifiedBootInfoRequest(int32_t ver, std::string_view boot_state_param,
1255                                      std::string_view bootloader_state_param,
1256                                      std::vector<uint8_t> vbmeta_digest_param)
1257         : KeymasterMessage(ver), boot_state(boot_state_param),
1258           bootloader_state(bootloader_state_param), vbmeta_digest(std::move(vbmeta_digest_param)) {}
1259 
SerializedSizeConfigureVerifiedBootInfoRequest1260     size_t SerializedSize() const override {
1261         return sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint32_t)  // buffer sizes
1262                + boot_state.size() + bootloader_state.size() + vbmeta_digest.size();
1263     }
SerializeConfigureVerifiedBootInfoRequest1264     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1265         buf = append_collection_to_buf(buf, end, boot_state);
1266         buf = append_collection_to_buf(buf, end, bootloader_state);
1267         return append_collection_to_buf(buf, end, vbmeta_digest);
1268     }
DeserializeConfigureVerifiedBootInfoRequest1269     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1270         return copy_collection_from_buf(buf_ptr, end, &boot_state) &&
1271                copy_collection_from_buf(buf_ptr, end, &bootloader_state) &&
1272                copy_collection_from_buf(buf_ptr, end, &vbmeta_digest);
1273     }
1274 
1275     std::string boot_state;
1276     std::string bootloader_state;
1277     std::vector<uint8_t> vbmeta_digest;
1278 };
1279 
1280 using ConfigureVerifiedBootInfoResponse = EmptyKeymasterResponse;
1281 
1282 struct GetRootOfTrustRequest : public KeymasterMessage {
GetRootOfTrustRequestGetRootOfTrustRequest1283     explicit GetRootOfTrustRequest(int32_t ver) : GetRootOfTrustRequest(ver, {}) {}
GetRootOfTrustRequestGetRootOfTrustRequest1284     GetRootOfTrustRequest(int32_t ver, std::vector<uint8_t> challenge_param)
1285         : KeymasterMessage(ver), challenge(std::move(challenge_param)){};
1286 
SerializedSizeGetRootOfTrustRequest1287     size_t SerializedSize() const override { return sizeof(uint32_t) + challenge.size(); }
SerializeGetRootOfTrustRequest1288     uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override {
1289         return append_collection_to_buf(buf, end, challenge);
1290     }
DeserializeGetRootOfTrustRequest1291     bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1292         return copy_collection_from_buf(buf_ptr, end, &challenge);
1293     }
1294 
1295     std::vector<uint8_t> challenge;
1296 };
1297 
1298 struct GetRootOfTrustResponse : public KeymasterResponse {
GetRootOfTrustResponseGetRootOfTrustResponse1299     explicit GetRootOfTrustResponse(uint32_t ver) : GetRootOfTrustResponse(ver, {}) {}
GetRootOfTrustResponseGetRootOfTrustResponse1300     GetRootOfTrustResponse(uint32_t ver, std::vector<uint8_t> rootOfTrust_param)
1301         : KeymasterResponse(ver), rootOfTrust(std::move(rootOfTrust_param)){};
1302 
NonErrorSerializedSizeGetRootOfTrustResponse1303     size_t NonErrorSerializedSize() const override { return sizeof(uint32_t) + rootOfTrust.size(); }
NonErrorSerializeGetRootOfTrustResponse1304     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
1305         return append_collection_to_buf(buf, end, rootOfTrust);
1306     }
NonErrorDeserializeGetRootOfTrustResponse1307     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1308         return copy_collection_from_buf(buf_ptr, end, &rootOfTrust);
1309     }
1310 
1311     std::vector<uint8_t> rootOfTrust;
1312 };
1313 
1314 struct GetHwInfoRequest : public EmptyKeymasterRequest {
GetHwInfoRequestGetHwInfoRequest1315     explicit GetHwInfoRequest(int32_t ver) : EmptyKeymasterRequest(ver) {}
1316 };
1317 
1318 struct GetHwInfoResponse : public KeymasterResponse {
GetHwInfoResponseGetHwInfoResponse1319     explicit GetHwInfoResponse(int32_t ver) : KeymasterResponse(ver) {}
1320 
NonErrorSerializedSizeGetHwInfoResponse1321     size_t NonErrorSerializedSize() const override {
1322         return sizeof(version) + sizeof(uint32_t) + rpcAuthorName.size() +
1323                sizeof(supportedEekCurve) + sizeof(uint32_t) + uniqueId.size() +
1324                sizeof(supportedNumKeysInCsr);
1325     }
NonErrorSerializeGetHwInfoResponse1326     uint8_t* NonErrorSerialize(uint8_t* buf, const uint8_t* end) const override {
1327         buf = append_uint32_to_buf(buf, end, version);
1328         buf = append_collection_to_buf(buf, end, rpcAuthorName);
1329         buf = append_uint32_to_buf(buf, end, supportedEekCurve);
1330         buf = append_collection_to_buf(buf, end, uniqueId);
1331         return append_uint32_to_buf(buf, end, supportedNumKeysInCsr);
1332     }
NonErrorDeserializeGetHwInfoResponse1333     bool NonErrorDeserialize(const uint8_t** buf_ptr, const uint8_t* end) override {
1334         return copy_uint32_from_buf(buf_ptr, end, &version) &&
1335                copy_collection_from_buf(buf_ptr, end, &rpcAuthorName) &&
1336                copy_uint32_from_buf(buf_ptr, end, &supportedEekCurve) &&
1337                copy_collection_from_buf(buf_ptr, end, &uniqueId) &&
1338                copy_uint32_from_buf(buf_ptr, end, &supportedNumKeysInCsr);
1339     }
1340 
1341     uint32_t version;
1342     std::string rpcAuthorName;
1343     uint32_t supportedEekCurve;
1344     std::string uniqueId;
1345     uint32_t supportedNumKeysInCsr;
1346 };
1347 
1348 }  // namespace keymaster
1349