1 /*
2  * Copyright (C) 2019 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 #include "fs_avb_test_util.h"
18 
19 #include <stdlib.h>
20 
21 #include <android-base/file.h>
22 #include <base/files/file_util.h>
23 #include <base/strings/string_util.h>
24 
25 namespace fs_avb_host_test {
26 
27 // Need to match the data setting in Android.bp:
28 //     data: ["tests/data/*"]
29 base::FilePath BaseFsAvbTest::data_dir_ = base::FilePath("tests/data");
30 
SetUp()31 void BaseFsAvbTest::SetUp() {
32     // Changes current directory to test executable directory so that relative path
33     // references to test dependencies don't rely on being manually run from
34     // the executable directory. With this, we can just open "./tests/data/testkey_rsa2048.pem"
35     // from the source.
36     base::SetCurrentDirectory(base::FilePath(android::base::GetExecutableDirectory()));
37 
38     // Creates a temporary directory, e.g., /tmp/libfs_avb-tests.XXXXXX to stash images in.
39     base::FilePath tmp_dir;
40     ASSERT_TRUE(GetTempDir(&tmp_dir));
41     base::CreateTemporaryDirInDir(tmp_dir, "libfs_avb-tests.", &test_dir_);
42 }
43 
TearDown()44 void BaseFsAvbTest::TearDown() {
45     // Nukes temporary directory.
46     ASSERT_NE(std::string::npos, test_dir_.value().find("libfs_avb-tests"));
47     ASSERT_TRUE(base::DeleteFile(test_dir_, true /* recursive */));
48 }
49 
CalcVBMetaDigest(const std::string & file_name,const std::string & hash_algorithm)50 std::string BaseFsAvbTest::CalcVBMetaDigest(const std::string& file_name,
51                                             const std::string& hash_algorithm) {
52     auto iter = vbmeta_images_.find(file_name);
53     EXPECT_NE(iter, vbmeta_images_.end());  // ensures file_name is generated before.
54 
55     // Gets the image path from iterator->second.path: VBMetaImage.path.
56     base::FilePath image_path = iter->second.path;
57     base::FilePath vbmeta_digest_path = test_dir_.Append("vbmeta_digest");
58     EXPECT_COMMAND(0,
59                    "avbtool calculate_vbmeta_digest --image %s --hash_algorithm %s"
60                    " --output %s",
61                    image_path.value().c_str(), hash_algorithm.c_str(),
62                    vbmeta_digest_path.value().c_str());
63     // Reads the content of the output digest file.
64     std::string vbmeta_digest_data;
65     EXPECT_TRUE(base::ReadFileToString(vbmeta_digest_path, &vbmeta_digest_data));
66     // Returns the trimmed digest.
67     std::string trimmed_digest_data;
68     base::TrimString(vbmeta_digest_data, " \t\n", &trimmed_digest_data);
69     return trimmed_digest_data;
70 }
71 
GenerateVBMetaImage(const std::string & file_name,const std::string & avb_algorithm,uint64_t rollback_index,const base::FilePath & key_path,const std::vector<base::FilePath> & include_descriptor_image_paths,const std::vector<ChainPartitionConfig> & chain_partitions,const std::string & additional_options)72 base::FilePath BaseFsAvbTest::GenerateVBMetaImage(
73         const std::string& file_name, const std::string& avb_algorithm, uint64_t rollback_index,
74         const base::FilePath& key_path,
75         const std::vector<base::FilePath>& include_descriptor_image_paths,
76         const std::vector<ChainPartitionConfig>& chain_partitions,
77         const std::string& additional_options) {
78     // --algorithm and --key
79     std::string signing_options;
80     if (avb_algorithm == "") {
81         signing_options = " --algorithm NONE ";
82     } else {
83         signing_options =
84                 std::string(" --algorithm ") + avb_algorithm + " --key " + key_path.value() + " ";
85     }
86     // --include_descriptors_from_image
87     std::string include_descriptor_options;
88     for (const auto& path : include_descriptor_image_paths) {
89         include_descriptor_options += " --include_descriptors_from_image " + path.value();
90     }
91     // --chain_partitions
92     std::string chain_partition_options;
93     for (const auto& partition : chain_partitions) {
94         chain_partition_options += base::StringPrintf(
95                 " --chain_partition %s:%u:%s", partition.partition_name.c_str(),
96                 partition.rollback_index_location, partition.key_blob_path.value().c_str());
97     }
98     // Starts to 'make_vbmeta_image'.
99     VBMetaImage vbmeta_image;
100     vbmeta_image.path = test_dir_.Append(file_name);
101     EXPECT_COMMAND(0,
102                    "avbtool make_vbmeta_image"
103                    " --rollback_index %" PRIu64
104                    " %s %s %s %s"
105                    " --output %s",
106                    rollback_index, signing_options.c_str(), include_descriptor_options.c_str(),
107                    chain_partition_options.c_str(), additional_options.c_str(),
108                    vbmeta_image.path.value().c_str());
109     int64_t file_size;
110     EXPECT_TRUE(base::GetFileSize(vbmeta_image.path, &file_size));
111     vbmeta_image.content.resize(file_size);
112     EXPECT_TRUE(base::ReadFile(vbmeta_image.path,
113                                reinterpret_cast<char*>(vbmeta_image.content.data()), file_size));
114     // Stores the generated vbmeta image into vbmeta_images_ member object.
115     vbmeta_images_.emplace(file_name, std::move(vbmeta_image));
116 
117     return vbmeta_images_[file_name].path;  // returns the path.
118 }
119 
ExtractVBMetaImage(const base::FilePath & image_path,const std::string & output_file_name,const size_t padding_size)120 base::FilePath BaseFsAvbTest::ExtractVBMetaImage(const base::FilePath& image_path,
121                                                  const std::string& output_file_name,
122                                                  const size_t padding_size) {
123     VBMetaImage vbmeta_image;
124     vbmeta_image.path = test_dir_.Append(output_file_name);
125     EXPECT_COMMAND(0,
126                    "avbtool extract_vbmeta_image"
127                    " --image %s"
128                    " --output %s"
129                    " --padding_size %zu",
130                    image_path.value().c_str(), vbmeta_image.path.value().c_str(), padding_size);
131     int64_t file_size;
132     EXPECT_TRUE(base::GetFileSize(vbmeta_image.path, &file_size));
133     vbmeta_image.content.resize(file_size);
134     EXPECT_TRUE(base::ReadFile(vbmeta_image.path,
135                                reinterpret_cast<char*>(vbmeta_image.content.data()), file_size));
136     // Stores the extracted vbmeta image into vbmeta_images_ member object.
137     vbmeta_images_.emplace(output_file_name, std::move(vbmeta_image));
138 
139     // Returns the output file path.
140     return vbmeta_images_[output_file_name].path;
141 }
142 
143 // Generates a file with name |file_name| of size |image_size| with
144 // known content (0x00 0x01 0x02 .. 0xff 0x00 0x01 ..).
GenerateImage(const std::string & file_name,size_t image_size,uint8_t start_byte)145 base::FilePath BaseFsAvbTest::GenerateImage(const std::string& file_name, size_t image_size,
146                                             uint8_t start_byte) {
147     std::vector<uint8_t> image;
148     image.resize(image_size);
149     for (size_t n = 0; n < image_size; n++) {
150         image[n] = uint8_t(n + start_byte);
151     }
152     base::FilePath image_path = test_dir_.Append(file_name);
153     EXPECT_EQ(image_size,
154               static_cast<const size_t>(base::WriteFile(
155                       image_path, reinterpret_cast<const char*>(image.data()), image.size())));
156     return image_path;
157 }
158 
AddAvbFooter(const base::FilePath & image_path,const std::string & footer_type,const std::string & partition_name,const uint64_t partition_size,const std::string & avb_algorithm,uint64_t rollback_index,const base::FilePath & key_path,const std::string & salt,const std::string & additional_options)159 void BaseFsAvbTest::AddAvbFooter(const base::FilePath& image_path, const std::string& footer_type,
160                                  const std::string& partition_name, const uint64_t partition_size,
161                                  const std::string& avb_algorithm, uint64_t rollback_index,
162                                  const base::FilePath& key_path, const std::string& salt,
163                                  const std::string& additional_options) {
164     // 'add_hash_footer' or 'add_hashtree_footer'.
165     EXPECT_TRUE(footer_type == "hash" or footer_type == "hashtree");
166     std::string add_footer_option = "add_" + footer_type + "_footer";
167 
168     std::string signing_options;
169     if (avb_algorithm == "") {
170         signing_options = " --algorithm NONE ";
171     } else {
172         signing_options =
173                 std::string(" --algorithm ") + avb_algorithm + " --key " + key_path.value() + " ";
174     }
175     EXPECT_COMMAND(0,
176                    "avbtool %s"
177                    " --image %s"
178                    " --partition_name %s "
179                    " --partition_size %" PRIu64 " --rollback_index %" PRIu64
180                    " --salt %s"
181                    " %s %s",
182                    add_footer_option.c_str(), image_path.value().c_str(), partition_name.c_str(),
183                    partition_size, rollback_index, salt.c_str(), signing_options.c_str(),
184                    additional_options.c_str());
185 }
186 
GenerateImageAndExtractVBMetaData(const std::string & partition_name,const size_t image_size,const size_t partition_size,const std::string & footer_type,const base::FilePath & avb_signing_key,const std::string & avb_algorithm,const uint64_t rollback_index)187 VBMetaData BaseFsAvbTest::GenerateImageAndExtractVBMetaData(
188         const std::string& partition_name, const size_t image_size, const size_t partition_size,
189         const std::string& footer_type, const base::FilePath& avb_signing_key,
190         const std::string& avb_algorithm, const uint64_t rollback_index) {
191     // Generates a raw image first
192     base::FilePath image_path = GenerateImage(partition_name + ".img", image_size);
193 
194     // Appends AVB Hashtree Footer.
195     AddAvbFooter(image_path, footer_type, partition_name, partition_size, avb_algorithm,
196                  rollback_index, avb_signing_key, "d00df00d",
197                  "--internal_release_string \"unit test\"");
198 
199     // Extracts vbmeta from the ram image into another *-vbmeta.img.
200     auto vbmeta_image = ExtractVBMetaImage(image_path, partition_name + "-vbmeta.img");
201 
202     // Loads *-vbmeta.img into a VBMetaData.
203     std::string vbmeta_buffer;
204     EXPECT_TRUE(base::ReadFileToString(vbmeta_image, &vbmeta_buffer));
205 
206     return {(const uint8_t*)vbmeta_buffer.data(), vbmeta_buffer.size(), partition_name};
207 }
208 
LoadVBMetaData(const std::string & file_name)209 VBMetaData BaseFsAvbTest::LoadVBMetaData(const std::string& file_name) {
210     auto iter = vbmeta_images_.find(file_name);
211     EXPECT_NE(iter, vbmeta_images_.end());  // ensures file_name is generated before.
212 
213     // Gets the image path from iterator->second.path: VBMetaImage.path.
214     base::FilePath image_path = iter->second.path;
215 
216     // Loads the vbmeta_image into a VBMetaData.
217     std::string vbmeta_buffer;
218     EXPECT_TRUE(base::ReadFileToString(image_path, &vbmeta_buffer));
219 
220     std::string partition_name = image_path.RemoveExtension().BaseName().value();
221     return {(const uint8_t*)vbmeta_buffer.data(), vbmeta_buffer.size(), partition_name};
222 }
223 
ExtractAndLoadVBMetaData(const base::FilePath & image_path,const std::string & output_file_name)224 VBMetaData BaseFsAvbTest::ExtractAndLoadVBMetaData(const base::FilePath& image_path,
225                                                    const std::string& output_file_name) {
226     ExtractVBMetaImage(image_path, output_file_name);
227     return LoadVBMetaData(output_file_name);
228 }
229 
InfoImage(const base::FilePath & image_path)230 std::string BaseFsAvbTest::InfoImage(const base::FilePath& image_path) {
231     base::FilePath tmp_path = test_dir_.Append("info_output.txt");
232     EXPECT_COMMAND(0, "avbtool info_image --image %s --output %s", image_path.value().c_str(),
233                    tmp_path.value().c_str());
234     std::string info_data;
235     EXPECT_TRUE(base::ReadFileToString(tmp_path, &info_data));
236     return info_data;
237 }
238 
InfoImage(const std::string & file_name)239 std::string BaseFsAvbTest::InfoImage(const std::string& file_name) {
240     auto iter = vbmeta_images_.find(file_name);
241     EXPECT_NE(iter, vbmeta_images_.end());  // ensures file_name is generated before.
242     // Gets the image path from iterator->second.path: VBMetaImage.path.
243     base::FilePath image_path = iter->second.path;
244     return InfoImage(image_path);
245 }
246 
ExtractPublicKeyAvb(const base::FilePath & key_path)247 base::FilePath BaseFsAvbTest::ExtractPublicKeyAvb(const base::FilePath& key_path) {
248     std::string file_name = key_path.RemoveExtension().BaseName().value();
249     base::FilePath tmp_path = test_dir_.Append(file_name + "public_key.bin");
250     EXPECT_COMMAND(0,
251                    "avbtool extract_public_key --key %s"
252                    " --output %s",
253                    key_path.value().c_str(), tmp_path.value().c_str());
254     return tmp_path;
255 }
256 
ExtractPublicKeyAvbBlob(const base::FilePath & key_path)257 std::string BaseFsAvbTest::ExtractPublicKeyAvbBlob(const base::FilePath& key_path) {
258     base::FilePath tmp_path = test_dir_.Append("public_key.bin");
259     EXPECT_COMMAND(0,
260                    "avbtool extract_public_key --key %s"
261                    " --output %s",
262                    key_path.value().c_str(), tmp_path.value().c_str());
263     std::string key_data;
264     EXPECT_TRUE(base::ReadFileToString(tmp_path, &key_data));
265     return key_data;
266 }
267 
268 }  // namespace fs_avb_host_test
269