blob: 2beb7ebb060c0abb2f32e9a3577a7ed4d6dbcd07 [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>
Alan Stokes8b4cb962021-07-06 17:45:39 +010030#include <asm/byteorder.h>
Martijn Coenen95194842020-09-24 16:56:46 +020031#include <libfsverity.h>
32#include <linux/fsverity.h>
33
34#include "CertUtils.h"
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010035#include "SigningKey.h"
Alan Stokes35049b62021-06-25 12:16:13 +010036#include "compos_signature.pb.h"
Martijn Coenen95194842020-09-24 16:56:46 +020037
Martijn Coenen5588e492021-02-25 14:33:44 +010038#define FS_VERITY_MAX_DIGEST_SIZE 64
39
Martijn Coenen95194842020-09-24 16:56:46 +020040using android::base::ErrnoError;
41using android::base::Error;
42using android::base::Result;
43using android::base::unique_fd;
44
Alan Stokes35049b62021-06-25 12:16:13 +010045using compos::proto::Signature;
46
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010047static const char* kFsVerityInitPath = "/system/bin/fsverity_init";
Alan Stokes35049b62021-06-25 12:16:13 +010048static const char* kSignatureExtension = ".signature";
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010049
Alan Stokes35049b62021-06-25 12:16:13 +010050static bool isSignatureFile(const std::filesystem::path& path) {
51 return path.extension().native() == kSignatureExtension;
52}
53
54static std::string toHex(std::span<const uint8_t> data) {
Martijn Coenen5588e492021-02-25 14:33:44 +010055 std::stringstream ss;
56 for (auto it = data.begin(); it != data.end(); ++it) {
57 ss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(*it);
58 }
59 return ss.str();
60}
61
Martijn Coenen95194842020-09-24 16:56:46 +020062static int read_callback(void* file, void* buf, size_t count) {
63 int* fd = (int*)file;
64 if (TEMP_FAILURE_RETRY(read(*fd, buf, count)) < 0) return errno ? -errno : -EIO;
65 return 0;
66}
67
Alan Stokes35049b62021-06-25 12:16:13 +010068Result<std::vector<uint8_t>> createDigest(int fd) {
Martijn Coenen95194842020-09-24 16:56:46 +020069 struct stat filestat;
Alan Stokes35049b62021-06-25 12:16:13 +010070 int ret = fstat(fd, &filestat);
Martijn Coenen309a2202021-03-15 23:45:07 +010071 if (ret < 0) {
Alan Stokes35049b62021-06-25 12:16:13 +010072 return ErrnoError() << "Failed to fstat";
Martijn Coenen309a2202021-03-15 23:45:07 +010073 }
Martijn Coenen95194842020-09-24 16:56:46 +020074 struct libfsverity_merkle_tree_params params = {
75 .version = 1,
76 .hash_algorithm = FS_VERITY_HASH_ALG_SHA256,
77 .file_size = static_cast<uint64_t>(filestat.st_size),
78 .block_size = 4096,
79 };
80
81 struct libfsverity_digest* digest;
Martijn Coenen309a2202021-03-15 23:45:07 +010082 ret = libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
83 if (ret < 0) {
Alan Stokes35049b62021-06-25 12:16:13 +010084 return ErrnoError() << "Failed to compute fs-verity digest";
Martijn Coenen309a2202021-03-15 23:45:07 +010085 }
Martijn Coenend7b63d22021-07-22 03:24:28 +020086 int expected_digest_size = libfsverity_get_digest_size(FS_VERITY_HASH_ALG_SHA256);
87 if (digest->digest_size != expected_digest_size) {
88 return Error() << "Digest does not have expected size: " << expected_digest_size
89 << " actual: " << digest->digest_size;
90 }
91 std::vector<uint8_t> digestVector(&digest->digest[0], &digest->digest[expected_digest_size]);
Martijn Coenen309a2202021-03-15 23:45:07 +010092 free(digest);
93 return digestVector;
Martijn Coenen95194842020-09-24 16:56:46 +020094}
95
Alan Stokes35049b62021-06-25 12:16:13 +010096Result<std::vector<uint8_t>> createDigest(const std::string& path) {
97 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
98 if (!fd.ok()) {
99 return ErrnoError() << "Unable to open";
100 }
101 return createDigest(fd.get());
102}
103
George Burgess IV69e41102021-03-10 10:35:38 -0800104namespace {
105template <typename T> struct DeleteAsPODArray {
106 void operator()(T* x) {
107 if (x) {
108 x->~T();
109 delete[](uint8_t*) x;
110 }
111 }
112};
113} // namespace
114
115template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
116
117template <typename T>
118static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
Martijn Coenend7b63d22021-07-22 03:24:28 +0200119 uint8_t* memory = new uint8_t[sizeof(T) + trailing_data_size];
George Burgess IV69e41102021-03-10 10:35:38 -0800120 T* ptr = new (memory) T;
121 return trailing_unique_ptr<T>{ptr};
122}
123
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100124static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200125 const std::vector<uint8_t>& digest) {
Eric Biggers37708582021-06-09 16:32:35 -0700126 auto d = makeUniqueWithTrailingData<fsverity_formatted_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200127
128 memcpy(d->magic, "FSVerity", 8);
Alan Stokes8b4cb962021-07-06 17:45:39 +0100129 d->digest_algorithm = __cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
130 d->digest_size = __cpu_to_le16(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200131 memcpy(d->digest, digest.data(), digest.size());
132
George Burgess IV69e41102021-03-10 10:35:38 -0800133 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200134 if (!signed_digest.ok()) {
135 return signed_digest.error();
136 }
137
138 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
139}
140
Alan Stokes35049b62021-06-25 12:16:13 +0100141Result<void> enableFsVerity(int fd, std::span<uint8_t> pkcs7) {
142 struct fsverity_enable_arg arg = {.version = 1};
143
144 arg.sig_ptr = reinterpret_cast<uint64_t>(pkcs7.data());
145 arg.sig_size = pkcs7.size();
146 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
147 arg.block_size = 4096;
148
149 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
150
151 if (ret != 0) {
152 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY";
153 }
154
155 return {};
156}
157
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100158Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Alan Stokes35049b62021-06-25 12:16:13 +0100159 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
160 if (!fd.ok()) {
161 return ErrnoError() << "Failed to open " << path;
162 }
163
164 auto digest = createDigest(fd.get());
Martijn Coenen95194842020-09-24 16:56:46 +0200165 if (!digest.ok()) {
Alan Stokes35049b62021-06-25 12:16:13 +0100166 return Error() << digest.error() << ": " << path;
Martijn Coenen95194842020-09-24 16:56:46 +0200167 }
168
169 auto signed_digest = signDigest(key, digest.value());
170 if (!signed_digest.ok()) {
171 return signed_digest.error();
172 }
173
Alan Stokes35049b62021-06-25 12:16:13 +0100174 auto pkcs7_data = createPkcs7(signed_digest.value(), kRootSubject);
175 if (!pkcs7_data.ok()) {
176 return pkcs7_data.error();
177 }
Martijn Coenen95194842020-09-24 16:56:46 +0200178
Alan Stokes35049b62021-06-25 12:16:13 +0100179 auto enabled = enableFsVerity(fd.get(), pkcs7_data.value());
180 if (!enabled.ok()) {
181 return Error() << enabled.error() << ": " << path;
Martijn Coenen95194842020-09-24 16:56:46 +0200182 }
183
Martijn Coenen5588e492021-02-25 14:33:44 +0100184 // Return the root hash as a hex string
185 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200186}
187
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100188Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
189 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100190 std::map<std::string, std::string> digests;
Alan Stokes35049b62021-06-25 12:16:13 +0100191
Martijn Coenen95194842020-09-24 16:56:46 +0200192 std::error_code ec;
Martijn Coenen95194842020-09-24 16:56:46 +0200193 auto it = std::filesystem::recursive_directory_iterator(path, ec);
Alan Stokes35049b62021-06-25 12:16:13 +0100194 for (auto end = std::filesystem::recursive_directory_iterator(); it != end; it.increment(ec)) {
Martijn Coenen95194842020-09-24 16:56:46 +0200195 if (it->is_regular_file()) {
196 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
197 auto result = enableFsVerity(it->path(), key);
198 if (!result.ok()) {
199 return result.error();
200 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100201 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200202 }
Martijn Coenen95194842020-09-24 16:56:46 +0200203 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100204 if (ec) {
Alan Stokes35049b62021-06-25 12:16:13 +0100205 return Error() << "Failed to iterate " << path << ": " << ec.message();
Martijn Coenen5588e492021-02-25 14:33:44 +0100206 }
Martijn Coenen95194842020-09-24 16:56:46 +0200207
Martijn Coenen5588e492021-02-25 14:33:44 +0100208 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200209}
210
Alan Stokes2553b562021-07-06 10:14:29 +0100211Result<std::string> isFileInVerity(int fd) {
Alan Stokes35049b62021-06-25 12:16:13 +0100212 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
213 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
214 auto ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
215 if (ret < 0) {
Alan Stokes2553b562021-07-06 10:14:29 +0100216 if (errno == ENODATA) {
217 return Error() << "File is not in fs-verity";
218 } else {
219 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY";
220 }
Alan Stokes35049b62021-06-25 12:16:13 +0100221 }
222 return toHex({&d->digest[0], &d->digest[d->digest_size]});
223}
Martijn Coenen95194842020-09-24 16:56:46 +0200224
Alan Stokes35049b62021-06-25 12:16:13 +0100225Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200226 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
Alan Stokes35049b62021-06-25 12:16:13 +0100227 if (!fd.ok()) {
Martijn Coenen95194842020-09-24 16:56:46 +0200228 return ErrnoError() << "Failed to open " << path;
229 }
230
Alan Stokes35049b62021-06-25 12:16:13 +0100231 auto digest = isFileInVerity(fd);
232 if (!digest.ok()) {
233 return Error() << digest.error() << ": " << path;
Martijn Coenen5588e492021-02-25 14:33:44 +0100234 }
Martijn Coenen95194842020-09-24 16:56:46 +0200235
Alan Stokes35049b62021-06-25 12:16:13 +0100236 return digest;
Martijn Coenen95194842020-09-24 16:56:46 +0200237}
238
Martijn Coenen5588e492021-02-25 14:33:44 +0100239Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
240 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200241 std::error_code ec;
242
243 auto it = std::filesystem::recursive_directory_iterator(path, ec);
244 auto end = std::filesystem::recursive_directory_iterator();
245
246 while (!ec && it != end) {
247 if (it->is_regular_file()) {
Martijn Coenen0f760d72021-06-29 10:31:01 +0200248 // Verify the file is in fs-verity
Martijn Coenen95194842020-09-24 16:56:46 +0200249 auto result = isFileInVerity(it->path());
250 if (!result.ok()) {
251 return result.error();
252 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100253 digests[it->path()] = *result;
Martijn Coenen0f760d72021-06-29 10:31:01 +0200254 } else if (it->is_directory()) {
255 // These are fine to ignore
256 } else if (it->is_symlink()) {
257 return Error() << "Rejecting artifacts, symlink at " << it->path();
258 } else {
259 return Error() << "Rejecting artifacts, unexpected file type for " << it->path();
260 }
Martijn Coenen95194842020-09-24 16:56:46 +0200261 ++it;
262 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100263 if (ec) {
264 return Error() << "Failed to iterate " << path << ": " << ec;
265 }
Martijn Coenen95194842020-09-24 16:56:46 +0200266
Martijn Coenen5588e492021-02-25 14:33:44 +0100267 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200268}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100269
Alan Stokes35049b62021-06-25 12:16:13 +0100270Result<Signature> readSignature(const std::filesystem::path& signature_path) {
271 unique_fd fd(TEMP_FAILURE_RETRY(open(signature_path.c_str(), O_RDONLY | O_CLOEXEC)));
272 if (fd == -1) {
273 return ErrnoError();
274 }
275 Signature signature;
276 if (!signature.ParseFromFileDescriptor(fd.get())) {
277 return Error() << "Failed to parse";
278 }
279 return signature;
280}
281
282Result<std::map<std::string, std::string>>
283verifyAllFilesUsingCompOs(const std::string& directory_path,
284 const std::vector<uint8_t>& compos_key) {
285 std::map<std::string, std::string> new_digests;
286 std::vector<std::filesystem::path> signature_files;
287
288 std::error_code ec;
289 auto it = std::filesystem::recursive_directory_iterator(directory_path, ec);
290 for (auto end = std::filesystem::recursive_directory_iterator(); it != end; it.increment(ec)) {
291 auto& path = it->path();
292 if (it->is_regular_file()) {
293 if (isSignatureFile(path)) {
294 continue;
295 }
296
297 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
298 if (!fd.ok()) {
299 return ErrnoError() << "Can't open " << path;
300 }
301
302 auto signature_path = path;
303 signature_path += kSignatureExtension;
304 auto signature = readSignature(signature_path);
305 if (!signature.ok()) {
306 return Error() << "Invalid signature " << signature_path << ": "
307 << signature.error();
308 }
309 signature_files.push_back(signature_path);
310
311 // Note that these values are not yet trusted.
312 auto& raw_digest = signature->digest();
313 auto& raw_signature = signature->signature();
314
Alan Stokes8b4cb962021-07-06 17:45:39 +0100315 // Re-construct the fsverity_formatted_digest that was signed, so we
316 // can verify the signature.
317 std::vector<uint8_t> buffer(sizeof(fsverity_formatted_digest) + raw_digest.size());
318 auto signed_data = new (buffer.data()) fsverity_formatted_digest;
319 memcpy(signed_data->magic, "FSVerity", sizeof signed_data->magic);
320 signed_data->digest_algorithm = __cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
321 signed_data->digest_size = __cpu_to_le16(raw_digest.size());
322 memcpy(signed_data->digest, raw_digest.data(), raw_digest.size());
323
Alan Stokes35049b62021-06-25 12:16:13 +0100324 // Make sure the signature matches the CompOs public key, and not some other
325 // fs-verity trusted key.
Alan Stokes8b4cb962021-07-06 17:45:39 +0100326 std::string to_verify(reinterpret_cast<char*>(buffer.data()), buffer.size());
327
328 auto verified = verifyRsaPublicKeySignature(to_verify, raw_signature, compos_key);
Alan Stokes35049b62021-06-25 12:16:13 +0100329 if (!verified.ok()) {
330 return Error() << verified.error() << ": " << path;
331 }
332
333 std::span<const uint8_t> digest_bytes(
334 reinterpret_cast<const uint8_t*>(raw_digest.data()), raw_digest.size());
335 std::string compos_digest = toHex(digest_bytes);
336
337 auto verity_digest = isFileInVerity(fd);
338 if (verity_digest.ok()) {
339 // The file is already in fs-verity. We need to make sure it was signed
340 // by CompOs, so we just check that it has the digest we expect.
341 if (verity_digest.value() != compos_digest) {
342 return Error() << "fs-verity digest does not match signature file: " << path;
343 }
344 } else {
345 // Not in fs-verity yet. But we have a valid signature of some
346 // digest. If it's not the correct digest for the file then
347 // enabling fs-verity will fail, so we don't need to check it
348 // explicitly ourselves. Otherwise we should be good.
349 std::vector<uint8_t> signature_bytes(raw_signature.begin(), raw_signature.end());
350 auto pkcs7 = createPkcs7(signature_bytes, kCompOsSubject);
351 if (!pkcs7.ok()) {
352 return Error() << pkcs7.error() << ": " << path;
353 }
354
355 LOG(INFO) << "Adding " << path << " to fs-verity...";
356 auto enabled = enableFsVerity(fd, pkcs7.value());
357 if (!enabled.ok()) {
358 return Error() << enabled.error() << ": " << path;
359 }
360 }
361
362 new_digests[path] = compos_digest;
363 } else if (it->is_directory()) {
364 // These are fine to ignore
365 } else if (it->is_symlink()) {
366 return Error() << "Rejecting artifacts, symlink at " << path;
367 } else {
368 return Error() << "Rejecting artifacts, unexpected file type for " << path;
369 }
370 }
371 if (ec) {
372 return Error() << "Failed to iterate " << directory_path << ": " << ec.message();
373 }
374
375 // Delete the signature files now that they have served their purpose. (ART
376 // has no use for them, and their presence could cause verification to fail
377 // on subsequent boots.)
378 for (auto& signature_path : signature_files) {
379 std::filesystem::remove(signature_path, ec);
380 if (ec) {
381 return Error() << "Failed to delete " << signature_path << ": " << ec.message();
382 }
383 }
384
385 return new_digests;
386}
387
Alan Stokesb1821782021-06-07 14:57:15 +0100388Result<void> addCertToFsVerityKeyring(const std::string& path, const char* keyName) {
389 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", keyName};
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100390
391 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
Alan Stokes246a7f12021-06-10 14:30:53 +0100392 if (fd == -1) {
393 return ErrnoError() << "Failed to open " << path;
394 }
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100395 pid_t pid = fork();
396 if (pid == 0) {
397 dup2(fd, STDIN_FILENO);
398 close(fd);
399 int argc = arraysize(argv);
400 char* argv_child[argc + 1];
401 memcpy(argv_child, argv, argc * sizeof(char*));
402 argv_child[argc] = nullptr;
Alan Stokes3b885982021-06-07 11:34:26 +0100403 execvp(argv_child[0], argv_child);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100404 PLOG(ERROR) << "exec in ForkExecvp";
405 _exit(EXIT_FAILURE);
406 } else {
407 close(fd);
408 }
409 if (pid == -1) {
410 return ErrnoError() << "Failed to fork.";
411 }
412 int status;
413 if (waitpid(pid, &status, 0) == -1) {
414 return ErrnoError() << "waitpid() failed.";
415 }
416 if (!WIFEXITED(status)) {
417 return Error() << kFsVerityInitPath << ": abnormal process exit";
418 }
Alan Stokes246a7f12021-06-10 14:30:53 +0100419 if (WEXITSTATUS(status) != 0) {
420 return Error() << kFsVerityInitPath << " exited with " << WEXITSTATUS(status);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100421 }
422
423 return {};
424}