1 //
2 // Copyright (C) 2020 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 #pragma once
17 
18 #include <keymaster/serializable.h>
19 
20 #include "host/commands/secure_env/tpm_resource_manager.h"
21 
22 namespace cuttlefish {
23 
24 /**
25  * A keymaster::Serializable that wraps another keymaster::Serializable,
26  * encrypting the data with a TPM to ensure privacy.
27  *
28  * This implementation randomly generates a unique key which only exists inside
29  * the TPM, and uses it to encrypt the data from the other Serializable
30  * instance. The encrypted data, together with information about the unique key
31  * is stored in the output data. The unique key information is something that
32  * can only be decoded using a TPM, which will detect if the key is corrupted.
33  * However, this implementation will not detect if the encrypted data is
34  * corrupted, which could break the other Serializable instance on
35  * deserialization. This class should be used with something else to verify
36  * that the data hasn't been tampered with.
37  *
38  * The serialization format is:
39  * [tpm key public data] [tpm key private data]
40  * [uint32_t: block_size]
41  * [uint32_t: encrypted_length] [encrypted_data]
42  *
43  * The actual length of [encrypted_data] in the serialized format is
44  * [encrypted_length] rounded up to the nearest multiple of [block_size].
45  * [encrypted_length] is the true length of the data before encryption, without
46  * padding.
47  */
48 class EncryptedSerializable : public keymaster::Serializable {
49 public:
50   EncryptedSerializable(TpmResourceManager&,
51                         std::function<TpmObjectSlot(TpmResourceManager&)>,
52                         Serializable&);
53 
54   size_t SerializedSize() const override;
55   uint8_t* Serialize(uint8_t* buf, const uint8_t* end) const override;
56   bool Deserialize(const uint8_t** buf_ptr, const uint8_t* end) override;
57 private:
58   TpmResourceManager& resource_manager_;
59   std::function<TpmObjectSlot(TpmResourceManager&)> parent_key_fn_;
60   keymaster::Serializable& wrapped_;
61 };
62 
63 }  // namespace cuttlefish
64