blob: 543e5a49f26b8f4f7045363815d018c339bd1a24 [file] [log] [blame]
Martijn Coenen95194842020-09-24 16:56:46 +02001/*
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
17#include <filesystem>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010018#include <map>
George Burgess IVfb0b40f2021-03-10 13:31:33 -080019#include <span>
Martijn Coenen95194842020-09-24 16:56:46 +020020#include <string>
21
22#include <fcntl.h>
23#include <linux/fs.h>
24#include <sys/stat.h>
25#include <sys/types.h>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010026#include <sys/wait.h>
Martijn Coenen95194842020-09-24 16:56:46 +020027
28#include <android-base/logging.h>
29#include <android-base/unique_fd.h>
30#include <libfsverity.h>
31#include <linux/fsverity.h>
32
33#include "CertUtils.h"
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010034#include "SigningKey.h"
Alan Stokes35049b62021-06-25 12:16:13 +010035#include "compos_signature.pb.h"
Martijn Coenen95194842020-09-24 16:56:46 +020036
Martijn Coenen5588e492021-02-25 14:33:44 +010037#define FS_VERITY_MAX_DIGEST_SIZE 64
38
Martijn Coenen95194842020-09-24 16:56:46 +020039using android::base::ErrnoError;
40using android::base::Error;
41using android::base::Result;
42using android::base::unique_fd;
43
Alan Stokes35049b62021-06-25 12:16:13 +010044using compos::proto::Signature;
45
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010046static const char* kFsVerityInitPath = "/system/bin/fsverity_init";
Alan Stokes35049b62021-06-25 12:16:13 +010047static const char* kSignatureExtension = ".signature";
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010048
Martijn Coenen95194842020-09-24 16:56:46 +020049#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
50#define cpu_to_le16(v) ((__force __le16)(uint16_t)(v))
51#define le16_to_cpu(v) ((__force uint16_t)(__le16)(v))
52#else
53#define cpu_to_le16(v) ((__force __le16)__builtin_bswap16(v))
54#define le16_to_cpu(v) (__builtin_bswap16((__force uint16_t)(v)))
55#endif
56
Alan Stokes35049b62021-06-25 12:16:13 +010057static bool isSignatureFile(const std::filesystem::path& path) {
58 return path.extension().native() == kSignatureExtension;
59}
60
61static std::string toHex(std::span<const uint8_t> data) {
Martijn Coenen5588e492021-02-25 14:33:44 +010062 std::stringstream ss;
63 for (auto it = data.begin(); it != data.end(); ++it) {
64 ss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(*it);
65 }
66 return ss.str();
67}
68
Martijn Coenen95194842020-09-24 16:56:46 +020069static int read_callback(void* file, void* buf, size_t count) {
70 int* fd = (int*)file;
71 if (TEMP_FAILURE_RETRY(read(*fd, buf, count)) < 0) return errno ? -errno : -EIO;
72 return 0;
73}
74
Alan Stokes35049b62021-06-25 12:16:13 +010075Result<std::vector<uint8_t>> createDigest(int fd) {
Martijn Coenen95194842020-09-24 16:56:46 +020076 struct stat filestat;
Alan Stokes35049b62021-06-25 12:16:13 +010077 int ret = fstat(fd, &filestat);
Martijn Coenen309a2202021-03-15 23:45:07 +010078 if (ret < 0) {
Alan Stokes35049b62021-06-25 12:16:13 +010079 return ErrnoError() << "Failed to fstat";
Martijn Coenen309a2202021-03-15 23:45:07 +010080 }
Martijn Coenen95194842020-09-24 16:56:46 +020081 struct libfsverity_merkle_tree_params params = {
82 .version = 1,
83 .hash_algorithm = FS_VERITY_HASH_ALG_SHA256,
84 .file_size = static_cast<uint64_t>(filestat.st_size),
85 .block_size = 4096,
86 };
87
88 struct libfsverity_digest* digest;
Martijn Coenen309a2202021-03-15 23:45:07 +010089 ret = libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
90 if (ret < 0) {
Alan Stokes35049b62021-06-25 12:16:13 +010091 return ErrnoError() << "Failed to compute fs-verity digest";
Martijn Coenen309a2202021-03-15 23:45:07 +010092 }
93 std::vector<uint8_t> digestVector(&digest->digest[0], &digest->digest[32]);
94 free(digest);
95 return digestVector;
Martijn Coenen95194842020-09-24 16:56:46 +020096}
97
Alan Stokes35049b62021-06-25 12:16:13 +010098Result<std::vector<uint8_t>> createDigest(const std::string& path) {
99 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
100 if (!fd.ok()) {
101 return ErrnoError() << "Unable to open";
102 }
103 return createDigest(fd.get());
104}
105
George Burgess IV69e41102021-03-10 10:35:38 -0800106namespace {
107template <typename T> struct DeleteAsPODArray {
108 void operator()(T* x) {
109 if (x) {
110 x->~T();
111 delete[](uint8_t*) x;
112 }
113 }
114};
115} // namespace
116
117template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
118
119template <typename T>
120static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
121 uint8_t* memory = new uint8_t[sizeof(T*) + trailing_data_size];
122 T* ptr = new (memory) T;
123 return trailing_unique_ptr<T>{ptr};
124}
125
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100126static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200127 const std::vector<uint8_t>& digest) {
Eric Biggers37708582021-06-09 16:32:35 -0700128 auto d = makeUniqueWithTrailingData<fsverity_formatted_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200129
130 memcpy(d->magic, "FSVerity", 8);
131 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
132 d->digest_size = cpu_to_le16(digest.size());
133 memcpy(d->digest, digest.data(), digest.size());
134
George Burgess IV69e41102021-03-10 10:35:38 -0800135 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200136 if (!signed_digest.ok()) {
137 return signed_digest.error();
138 }
139
140 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
141}
142
Alan Stokes35049b62021-06-25 12:16:13 +0100143Result<void> enableFsVerity(int fd, std::span<uint8_t> pkcs7) {
144 struct fsverity_enable_arg arg = {.version = 1};
145
146 arg.sig_ptr = reinterpret_cast<uint64_t>(pkcs7.data());
147 arg.sig_size = pkcs7.size();
148 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
149 arg.block_size = 4096;
150
151 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
152
153 if (ret != 0) {
154 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY";
155 }
156
157 return {};
158}
159
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100160Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Alan Stokes35049b62021-06-25 12:16:13 +0100161 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
162 if (!fd.ok()) {
163 return ErrnoError() << "Failed to open " << path;
164 }
165
166 auto digest = createDigest(fd.get());
Martijn Coenen95194842020-09-24 16:56:46 +0200167 if (!digest.ok()) {
Alan Stokes35049b62021-06-25 12:16:13 +0100168 return Error() << digest.error() << ": " << path;
Martijn Coenen95194842020-09-24 16:56:46 +0200169 }
170
171 auto signed_digest = signDigest(key, digest.value());
172 if (!signed_digest.ok()) {
173 return signed_digest.error();
174 }
175
Alan Stokes35049b62021-06-25 12:16:13 +0100176 auto pkcs7_data = createPkcs7(signed_digest.value(), kRootSubject);
177 if (!pkcs7_data.ok()) {
178 return pkcs7_data.error();
179 }
Martijn Coenen95194842020-09-24 16:56:46 +0200180
Alan Stokes35049b62021-06-25 12:16:13 +0100181 auto enabled = enableFsVerity(fd.get(), pkcs7_data.value());
182 if (!enabled.ok()) {
183 return Error() << enabled.error() << ": " << path;
Martijn Coenen95194842020-09-24 16:56:46 +0200184 }
185
Martijn Coenen5588e492021-02-25 14:33:44 +0100186 // Return the root hash as a hex string
187 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200188}
189
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100190Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
191 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100192 std::map<std::string, std::string> digests;
Alan Stokes35049b62021-06-25 12:16:13 +0100193
Martijn Coenen95194842020-09-24 16:56:46 +0200194 std::error_code ec;
Martijn Coenen95194842020-09-24 16:56:46 +0200195 auto it = std::filesystem::recursive_directory_iterator(path, ec);
Alan Stokes35049b62021-06-25 12:16:13 +0100196 for (auto end = std::filesystem::recursive_directory_iterator(); it != end; it.increment(ec)) {
Martijn Coenen95194842020-09-24 16:56:46 +0200197 if (it->is_regular_file()) {
198 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
199 auto result = enableFsVerity(it->path(), key);
200 if (!result.ok()) {
201 return result.error();
202 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100203 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200204 }
Martijn Coenen95194842020-09-24 16:56:46 +0200205 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100206 if (ec) {
Alan Stokes35049b62021-06-25 12:16:13 +0100207 return Error() << "Failed to iterate " << path << ": " << ec.message();
Martijn Coenen5588e492021-02-25 14:33:44 +0100208 }
Martijn Coenen95194842020-09-24 16:56:46 +0200209
Martijn Coenen5588e492021-02-25 14:33:44 +0100210 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200211}
212
Alan Stokes2553b562021-07-06 10:14:29 +0100213Result<std::string> isFileInVerity(int fd) {
Alan Stokes35049b62021-06-25 12:16:13 +0100214 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
215 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
216 auto ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
217 if (ret < 0) {
Alan Stokes2553b562021-07-06 10:14:29 +0100218 if (errno == ENODATA) {
219 return Error() << "File is not in fs-verity";
220 } else {
221 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY";
222 }
Alan Stokes35049b62021-06-25 12:16:13 +0100223 }
224 return toHex({&d->digest[0], &d->digest[d->digest_size]});
225}
Martijn Coenen95194842020-09-24 16:56:46 +0200226
Alan Stokes35049b62021-06-25 12:16:13 +0100227Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200228 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
Alan Stokes35049b62021-06-25 12:16:13 +0100229 if (!fd.ok()) {
Martijn Coenen95194842020-09-24 16:56:46 +0200230 return ErrnoError() << "Failed to open " << path;
231 }
232
Alan Stokes35049b62021-06-25 12:16:13 +0100233 auto digest = isFileInVerity(fd);
234 if (!digest.ok()) {
235 return Error() << digest.error() << ": " << path;
Martijn Coenen5588e492021-02-25 14:33:44 +0100236 }
Martijn Coenen95194842020-09-24 16:56:46 +0200237
Alan Stokes35049b62021-06-25 12:16:13 +0100238 return digest;
Martijn Coenen95194842020-09-24 16:56:46 +0200239}
240
Martijn Coenen5588e492021-02-25 14:33:44 +0100241Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
242 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200243 std::error_code ec;
244
245 auto it = std::filesystem::recursive_directory_iterator(path, ec);
246 auto end = std::filesystem::recursive_directory_iterator();
247
248 while (!ec && it != end) {
249 if (it->is_regular_file()) {
Martijn Coenen0f760d72021-06-29 10:31:01 +0200250 // Verify the file is in fs-verity
Martijn Coenen95194842020-09-24 16:56:46 +0200251 auto result = isFileInVerity(it->path());
252 if (!result.ok()) {
253 return result.error();
254 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100255 digests[it->path()] = *result;
Martijn Coenen0f760d72021-06-29 10:31:01 +0200256 } else if (it->is_directory()) {
257 // These are fine to ignore
258 } else if (it->is_symlink()) {
259 return Error() << "Rejecting artifacts, symlink at " << it->path();
260 } else {
261 return Error() << "Rejecting artifacts, unexpected file type for " << it->path();
262 }
Martijn Coenen95194842020-09-24 16:56:46 +0200263 ++it;
264 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100265 if (ec) {
266 return Error() << "Failed to iterate " << path << ": " << ec;
267 }
Martijn Coenen95194842020-09-24 16:56:46 +0200268
Martijn Coenen5588e492021-02-25 14:33:44 +0100269 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200270}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100271
Alan Stokes35049b62021-06-25 12:16:13 +0100272Result<Signature> readSignature(const std::filesystem::path& signature_path) {
273 unique_fd fd(TEMP_FAILURE_RETRY(open(signature_path.c_str(), O_RDONLY | O_CLOEXEC)));
274 if (fd == -1) {
275 return ErrnoError();
276 }
277 Signature signature;
278 if (!signature.ParseFromFileDescriptor(fd.get())) {
279 return Error() << "Failed to parse";
280 }
281 return signature;
282}
283
284Result<std::map<std::string, std::string>>
285verifyAllFilesUsingCompOs(const std::string& directory_path,
286 const std::vector<uint8_t>& compos_key) {
287 std::map<std::string, std::string> new_digests;
288 std::vector<std::filesystem::path> signature_files;
289
290 std::error_code ec;
291 auto it = std::filesystem::recursive_directory_iterator(directory_path, ec);
292 for (auto end = std::filesystem::recursive_directory_iterator(); it != end; it.increment(ec)) {
293 auto& path = it->path();
294 if (it->is_regular_file()) {
295 if (isSignatureFile(path)) {
296 continue;
297 }
298
299 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
300 if (!fd.ok()) {
301 return ErrnoError() << "Can't open " << path;
302 }
303
304 auto signature_path = path;
305 signature_path += kSignatureExtension;
306 auto signature = readSignature(signature_path);
307 if (!signature.ok()) {
308 return Error() << "Invalid signature " << signature_path << ": "
309 << signature.error();
310 }
311 signature_files.push_back(signature_path);
312
313 // Note that these values are not yet trusted.
314 auto& raw_digest = signature->digest();
315 auto& raw_signature = signature->signature();
316
317 // Make sure the signature matches the CompOs public key, and not some other
318 // fs-verity trusted key.
319 auto verified = verifySignature(raw_digest, raw_signature, compos_key);
320 if (!verified.ok()) {
321 return Error() << verified.error() << ": " << path;
322 }
323
324 std::span<const uint8_t> digest_bytes(
325 reinterpret_cast<const uint8_t*>(raw_digest.data()), raw_digest.size());
326 std::string compos_digest = toHex(digest_bytes);
327
328 auto verity_digest = isFileInVerity(fd);
329 if (verity_digest.ok()) {
330 // The file is already in fs-verity. We need to make sure it was signed
331 // by CompOs, so we just check that it has the digest we expect.
332 if (verity_digest.value() != compos_digest) {
333 return Error() << "fs-verity digest does not match signature file: " << path;
334 }
335 } else {
336 // Not in fs-verity yet. But we have a valid signature of some
337 // digest. If it's not the correct digest for the file then
338 // enabling fs-verity will fail, so we don't need to check it
339 // explicitly ourselves. Otherwise we should be good.
340 std::vector<uint8_t> signature_bytes(raw_signature.begin(), raw_signature.end());
341 auto pkcs7 = createPkcs7(signature_bytes, kCompOsSubject);
342 if (!pkcs7.ok()) {
343 return Error() << pkcs7.error() << ": " << path;
344 }
345
346 LOG(INFO) << "Adding " << path << " to fs-verity...";
347 auto enabled = enableFsVerity(fd, pkcs7.value());
348 if (!enabled.ok()) {
349 return Error() << enabled.error() << ": " << path;
350 }
351 }
352
353 new_digests[path] = compos_digest;
354 } else if (it->is_directory()) {
355 // These are fine to ignore
356 } else if (it->is_symlink()) {
357 return Error() << "Rejecting artifacts, symlink at " << path;
358 } else {
359 return Error() << "Rejecting artifacts, unexpected file type for " << path;
360 }
361 }
362 if (ec) {
363 return Error() << "Failed to iterate " << directory_path << ": " << ec.message();
364 }
365
366 // Delete the signature files now that they have served their purpose. (ART
367 // has no use for them, and their presence could cause verification to fail
368 // on subsequent boots.)
369 for (auto& signature_path : signature_files) {
370 std::filesystem::remove(signature_path, ec);
371 if (ec) {
372 return Error() << "Failed to delete " << signature_path << ": " << ec.message();
373 }
374 }
375
376 return new_digests;
377}
378
Alan Stokesb1821782021-06-07 14:57:15 +0100379Result<void> addCertToFsVerityKeyring(const std::string& path, const char* keyName) {
380 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", keyName};
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100381
382 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
Alan Stokes246a7f12021-06-10 14:30:53 +0100383 if (fd == -1) {
384 return ErrnoError() << "Failed to open " << path;
385 }
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100386 pid_t pid = fork();
387 if (pid == 0) {
388 dup2(fd, STDIN_FILENO);
389 close(fd);
390 int argc = arraysize(argv);
391 char* argv_child[argc + 1];
392 memcpy(argv_child, argv, argc * sizeof(char*));
393 argv_child[argc] = nullptr;
Alan Stokes3b885982021-06-07 11:34:26 +0100394 execvp(argv_child[0], argv_child);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100395 PLOG(ERROR) << "exec in ForkExecvp";
396 _exit(EXIT_FAILURE);
397 } else {
398 close(fd);
399 }
400 if (pid == -1) {
401 return ErrnoError() << "Failed to fork.";
402 }
403 int status;
404 if (waitpid(pid, &status, 0) == -1) {
405 return ErrnoError() << "waitpid() failed.";
406 }
407 if (!WIFEXITED(status)) {
408 return Error() << kFsVerityInitPath << ": abnormal process exit";
409 }
Alan Stokes246a7f12021-06-10 14:30:53 +0100410 if (WEXITSTATUS(status) != 0) {
411 return Error() << kFsVerityInitPath << " exited with " << WEXITSTATUS(status);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100412 }
413
414 return {};
415}