1 //
2 // Copyright (C) 2020-2023 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 "host/commands/secure_env/storage/storage.h"
19 
20 #include <memory>
21 #include <optional>
22 #include <string>
23 #include <vector>
24 
25 #include <tss2/tss2_esys.h>
26 #include <tss2/tss2_tpm2_types.h>
27 #include <json/json.h>
28 
29 #include "common/libs/utils/result.h"
30 #include "host/commands/secure_env/tpm_resource_manager.h"
31 
32 namespace cuttlefish {
33 namespace secure_env {
34 
35 /**
36  * Manager for data stored inside the TPM with an index outside of the TPM. The
37  * contents of the data cannot be corrupted or decrypted by accessing the index,
38  * but the index can be corrupted by an attacker.
39  *
40  * As the actual data is stored inside the TPM, a replay attack can be used to
41  * restore deleted index entries or hide revert to before an index entry was
42  * added, but not change the contents that an index points to if it still
43  * exists.
44  *
45  * This class is not thread-safe, and should be synchronized externally if it
46  * is going to be used from multiple threads.
47  */
48 class TpmStorage : public secure_env::Storage {
49  public:
50   TpmStorage(TpmResourceManager& resource_manager, const std::string& index_file);
51 
52   Result<bool> HasKey(const std::string& key) const override;
53   Result<ManagedStorageData> Read(const std::string& key) const override;
54   Result<void> Write(const std::string& key, const StorageData& data) override;
55   bool Exists() const override;
56 
57  private:
58   Result<std::optional<TPM2_HANDLE>> GetHandle(const std::string& key) const;
59   TPM2_HANDLE GenerateRandomHandle();
60   Result<void> Allocate(const std::string& key, uint16_t size);
61 
62   TpmResourceManager& resource_manager_;
63   std::string index_file_;
64   Json::Value index_;
65 
66   std::string path_;
67 };
68 
69 }  // namespace secure_env
70 }  // namespace cuttlefish
71