1 /*
2 * Copyright (C) 2021 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 <sys/stat.h>
18 #include <sys/types.h>
19 #include <unistd.h>
20
21 #include <fstream>
22 #include <iostream>
23 #include <optional>
24 #include <string>
25 #include <vector>
26
27 #include <android-base/file.h>
28 #include <android-base/result.h>
29 #include <com_android_apex.h>
30 #include <image_aggregator.h>
31 #include <json/json.h>
32
33 #include "microdroid/signature.h"
34
35 using android::base::Dirname;
36 using android::base::ErrnoError;
37 using android::base::Error;
38 using android::base::Result;
39 using android::base::unique_fd;
40 using android::microdroid::ApexSignature;
41 using android::microdroid::ApkSignature;
42 using android::microdroid::MicrodroidSignature;
43 using android::microdroid::WriteMicrodroidSignature;
44
45 using com::android::apex::ApexInfoList;
46 using com::android::apex::readApexInfoList;
47
48 using cuttlefish::AlignToPartitionSize;
49 using cuttlefish::CreateCompositeDisk;
50 using cuttlefish::kLinuxFilesystem;
51 using cuttlefish::MultipleImagePartition;
52
GetFileSize(const std::string & path)53 Result<uint32_t> GetFileSize(const std::string& path) {
54 struct stat st;
55 if (lstat(path.c_str(), &st) == -1) {
56 return ErrnoError() << "Can't lstat " << path;
57 }
58 return static_cast<uint32_t>(st.st_size);
59 }
60
ToAbsolute(const std::string & path,const std::string & dirname)61 std::string ToAbsolute(const std::string& path, const std::string& dirname) {
62 bool is_absolute = !path.empty() && path[0] == '/';
63 if (is_absolute) {
64 return path;
65 } else {
66 return dirname + "/" + path;
67 }
68 }
69
70 // Returns `append` is appended to the end of filename preserving the extension.
AppendFileName(const std::string & filename,const std::string & append)71 std::string AppendFileName(const std::string& filename, const std::string& append) {
72 size_t pos = filename.find_last_of('.');
73 if (pos == std::string::npos) {
74 return filename + append;
75 } else {
76 return filename.substr(0, pos) + append + filename.substr(pos);
77 }
78 }
79
80 struct ApexConfig {
81 std::string name; // the apex name
82 std::string path; // the path to the apex file
83 // absolute or relative to the config file
84 std::optional<std::string> public_key;
85 std::optional<std::string> root_digest;
86 };
87
88 struct ApkConfig {
89 std::string name;
90 // TODO(jooyung): find path/idsig with name
91 std::string path;
92 };
93
94 struct Config {
95 std::string dirname; // config file's direname to resolve relative paths in the config
96
97 std::vector<std::string> system_apexes;
98 std::vector<ApexConfig> apexes;
99 std::optional<ApkConfig> apk;
100 };
101
102 #define DO(expr) \
103 if (auto res = (expr); !res.ok()) return res.error()
104
ParseJson(const Json::Value & value,std::string & s)105 Result<void> ParseJson(const Json::Value& value, std::string& s) {
106 if (!value.isString()) {
107 return Error() << "should be a string: " << value;
108 }
109 s = value.asString();
110 return {};
111 }
112
113 template <typename T>
ParseJson(const Json::Value & value,std::optional<T> & s)114 Result<void> ParseJson(const Json::Value& value, std::optional<T>& s) {
115 if (value.isNull()) {
116 s.reset();
117 return {};
118 }
119 s.emplace();
120 return ParseJson(value, *s);
121 }
122
ParseJson(const Json::Value & value,ApexConfig & apex_config)123 Result<void> ParseJson(const Json::Value& value, ApexConfig& apex_config) {
124 DO(ParseJson(value["name"], apex_config.name));
125 DO(ParseJson(value["path"], apex_config.path));
126 DO(ParseJson(value["publicKey"], apex_config.public_key));
127 DO(ParseJson(value["rootDigest"], apex_config.root_digest));
128 return {};
129 }
130
ParseJson(const Json::Value & value,ApkConfig & apk_config)131 Result<void> ParseJson(const Json::Value& value, ApkConfig& apk_config) {
132 DO(ParseJson(value["name"], apk_config.name));
133 DO(ParseJson(value["path"], apk_config.path));
134 return {};
135 }
136
137 template <typename T>
ParseJson(const Json::Value & values,std::vector<T> & parsed)138 Result<void> ParseJson(const Json::Value& values, std::vector<T>& parsed) {
139 for (const Json::Value& value : values) {
140 T t;
141 DO(ParseJson(value, t));
142 parsed.push_back(std::move(t));
143 }
144 return {};
145 }
146
ParseJson(const Json::Value & value,Config & config)147 Result<void> ParseJson(const Json::Value& value, Config& config) {
148 DO(ParseJson(value["system_apexes"], config.system_apexes));
149 DO(ParseJson(value["apexes"], config.apexes));
150 DO(ParseJson(value["apk"], config.apk));
151 return {};
152 }
153
LoadConfig(const std::string & config_file)154 Result<Config> LoadConfig(const std::string& config_file) {
155 std::ifstream in(config_file);
156 Json::CharReaderBuilder builder;
157 Json::Value root;
158 Json::String errs;
159 if (!parseFromStream(builder, in, &root, &errs)) {
160 return Error() << "bad config: " << errs;
161 }
162
163 Config config;
164 config.dirname = Dirname(config_file);
165 DO(ParseJson(root, config));
166 return config;
167 }
168
169 #undef DO
170
LoadSystemApexes(Config & config)171 Result<void> LoadSystemApexes(Config& config) {
172 static const char* kApexInfoListFile = "/apex/apex-info-list.xml";
173 std::optional<ApexInfoList> apex_info_list = readApexInfoList(kApexInfoListFile);
174 if (!apex_info_list.has_value()) {
175 return Error() << "Failed to read " << kApexInfoListFile;
176 }
177 auto get_apex_path = [&](const std::string& apex_name) -> std::optional<std::string> {
178 for (const auto& apex_info : apex_info_list->getApexInfo()) {
179 if (apex_info.getIsActive() && apex_info.getModuleName() == apex_name) {
180 return apex_info.getModulePath();
181 }
182 }
183 return std::nullopt;
184 };
185 for (const auto& apex_name : config.system_apexes) {
186 const auto& apex_path = get_apex_path(apex_name);
187 if (!apex_path.has_value()) {
188 return Error() << "Can't find the system apex: " << apex_name;
189 }
190 config.apexes.push_back(ApexConfig{
191 .name = apex_name,
192 .path = *apex_path,
193 .public_key = std::nullopt,
194 .root_digest = std::nullopt,
195 });
196 }
197 return {};
198 }
199
MakeSignature(const Config & config,const std::string & filename)200 Result<void> MakeSignature(const Config& config, const std::string& filename) {
201 MicrodroidSignature signature;
202 signature.set_version(1);
203
204 for (const auto& apex_config : config.apexes) {
205 ApexSignature* apex_signature = signature.add_apexes();
206
207 // name
208 apex_signature->set_name(apex_config.name);
209
210 // size
211 auto file_size = GetFileSize(ToAbsolute(apex_config.path, config.dirname));
212 if (!file_size.ok()) {
213 return Error() << "I/O error: " << file_size.error();
214 }
215 apex_signature->set_size(file_size.value());
216
217 // publicKey
218 if (apex_config.public_key.has_value()) {
219 apex_signature->set_publickey(apex_config.public_key.value());
220 }
221
222 // rootDigest
223 if (apex_config.root_digest.has_value()) {
224 apex_signature->set_rootdigest(apex_config.root_digest.value());
225 }
226 }
227
228 if (config.apk.has_value()) {
229 ApkSignature* apk_signature = signature.mutable_apk();
230 apk_signature->set_name(config.apk->name);
231 apk_signature->set_payload_partition_name("microdroid-apk");
232 // TODO(jooyung): set idsig partition as well
233 }
234
235 std::ofstream out(filename);
236 return WriteMicrodroidSignature(signature, out);
237 }
238
GenerateFiller(const std::string & file_path,const std::string & filler_path)239 Result<void> GenerateFiller(const std::string& file_path, const std::string& filler_path) {
240 auto file_size = GetFileSize(file_path);
241 if (!file_size.ok()) {
242 return file_size.error();
243 }
244 auto disk_size = AlignToPartitionSize(*file_size + sizeof(uint32_t));
245
246 unique_fd fd(TEMP_FAILURE_RETRY(open(filler_path.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0600)));
247 if (fd.get() == -1) {
248 return ErrnoError() << "open(" << filler_path << ") failed.";
249 }
250 uint32_t size = htobe32(static_cast<uint32_t>(*file_size));
251 if (ftruncate(fd.get(), disk_size - *file_size) == -1) {
252 return ErrnoError() << "ftruncate(" << filler_path << ") failed.";
253 }
254 if (lseek(fd.get(), -sizeof(size), SEEK_END) == -1) {
255 return ErrnoError() << "lseek(" << filler_path << ") failed.";
256 }
257 if (write(fd.get(), &size, sizeof(size)) <= 0) {
258 return ErrnoError() << "write(" << filler_path << ") failed.";
259 }
260 return {};
261 }
262
MakePayload(const Config & config,const std::string & signature_file,const std::string & output_file)263 Result<void> MakePayload(const Config& config, const std::string& signature_file,
264 const std::string& output_file) {
265 std::vector<MultipleImagePartition> partitions;
266
267 // put signature at the first partition
268 partitions.push_back(MultipleImagePartition{
269 .label = "signature",
270 .image_file_paths = {signature_file},
271 .type = kLinuxFilesystem,
272 .read_only = true,
273 });
274
275 int filler_count = 0;
276 auto add_partition = [&](auto partition_name, auto file_path) -> Result<void> {
277 std::string filler_path = output_file + "." + std::to_string(filler_count++);
278 if (auto ret = GenerateFiller(file_path, filler_path); !ret.ok()) {
279 return ret.error();
280 }
281 partitions.push_back(MultipleImagePartition{
282 .label = partition_name,
283 .image_file_paths = {file_path, filler_path},
284 .type = kLinuxFilesystem,
285 .read_only = true,
286 });
287 return {};
288 };
289
290 // put apexes at the subsequent partitions with "size" filler
291 for (size_t i = 0; i < config.apexes.size(); i++) {
292 const auto& apex_config = config.apexes[i];
293 std::string apex_path = ToAbsolute(apex_config.path, config.dirname);
294 if (auto ret = add_partition("microdroid-apex-" + std::to_string(i), apex_path);
295 !ret.ok()) {
296 return ret.error();
297 }
298 }
299 // put apk with "size" filler if necessary.
300 // TODO(jooyung): partition name("microdroid-apk") is TBD
301 if (config.apk.has_value()) {
302 std::string apk_path = ToAbsolute(config.apk->path, config.dirname);
303 if (auto ret = add_partition("microdroid-apk", apk_path); !ret.ok()) {
304 return ret.error();
305 }
306 }
307
308 const std::string gpt_header = AppendFileName(output_file, "-header");
309 const std::string gpt_footer = AppendFileName(output_file, "-footer");
310 CreateCompositeDisk(partitions, gpt_header, gpt_footer, output_file);
311 return {};
312 }
313
main(int argc,char ** argv)314 int main(int argc, char** argv) {
315 if (argc != 3) {
316 std::cerr << "Usage: " << argv[0] << " <config> <output>\n";
317 return 1;
318 }
319
320 auto config = LoadConfig(argv[1]);
321 if (!config.ok()) {
322 std::cerr << config.error() << '\n';
323 return 1;
324 }
325
326 if (const auto res = LoadSystemApexes(*config); !res.ok()) {
327 std::cerr << res.error() << '\n';
328 return 1;
329 }
330
331 const std::string output_file(argv[2]);
332 const std::string signature_file = AppendFileName(output_file, "-signature");
333
334 if (const auto res = MakeSignature(*config, signature_file); !res.ok()) {
335 std::cerr << res.error() << '\n';
336 return 1;
337 }
338 if (const auto res = MakePayload(*config, signature_file, output_file); !res.ok()) {
339 std::cerr << res.error() << '\n';
340 return 1;
341 }
342
343 return 0;
344 }