blob: 36f85b509fa62300402b2fd4c56812a0a3de32cb [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 Stokes35049b62021-06-25 12:16:13 +0100213Result<std::string> readVerityDigest(int fd) {
214 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) {
218 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY";
219 }
220 return toHex({&d->digest[0], &d->digest[d->digest_size]});
221}
Martijn Coenen95194842020-09-24 16:56:46 +0200222
Alan Stokes35049b62021-06-25 12:16:13 +0100223Result<std::string> isFileInVerity(int fd) {
224 unsigned int flags;
225 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
226 if (ret < 0) {
227 return ErrnoError() << "Failed to FS_IOC_GETFLAGS";
228 }
229 if (!(flags & FS_VERITY_FL)) {
230 return Error() << "File is not in fs-verity";
231 }
232
233 return readVerityDigest(fd);
234}
235
236Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200237 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
Alan Stokes35049b62021-06-25 12:16:13 +0100238 if (!fd.ok()) {
Martijn Coenen95194842020-09-24 16:56:46 +0200239 return ErrnoError() << "Failed to open " << path;
240 }
241
Alan Stokes35049b62021-06-25 12:16:13 +0100242 auto digest = isFileInVerity(fd);
243 if (!digest.ok()) {
244 return Error() << digest.error() << ": " << path;
Martijn Coenen5588e492021-02-25 14:33:44 +0100245 }
Martijn Coenen95194842020-09-24 16:56:46 +0200246
Alan Stokes35049b62021-06-25 12:16:13 +0100247 return digest;
Martijn Coenen95194842020-09-24 16:56:46 +0200248}
249
Martijn Coenen5588e492021-02-25 14:33:44 +0100250Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
251 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200252 std::error_code ec;
253
254 auto it = std::filesystem::recursive_directory_iterator(path, ec);
255 auto end = std::filesystem::recursive_directory_iterator();
256
257 while (!ec && it != end) {
258 if (it->is_regular_file()) {
Martijn Coenen0f760d72021-06-29 10:31:01 +0200259 // Verify the file is in fs-verity
Martijn Coenen95194842020-09-24 16:56:46 +0200260 auto result = isFileInVerity(it->path());
261 if (!result.ok()) {
262 return result.error();
263 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100264 digests[it->path()] = *result;
Martijn Coenen0f760d72021-06-29 10:31:01 +0200265 } else if (it->is_directory()) {
266 // These are fine to ignore
267 } else if (it->is_symlink()) {
268 return Error() << "Rejecting artifacts, symlink at " << it->path();
269 } else {
270 return Error() << "Rejecting artifacts, unexpected file type for " << it->path();
271 }
Martijn Coenen95194842020-09-24 16:56:46 +0200272 ++it;
273 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100274 if (ec) {
275 return Error() << "Failed to iterate " << path << ": " << ec;
276 }
Martijn Coenen95194842020-09-24 16:56:46 +0200277
Martijn Coenen5588e492021-02-25 14:33:44 +0100278 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200279}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100280
Alan Stokes35049b62021-06-25 12:16:13 +0100281Result<Signature> readSignature(const std::filesystem::path& signature_path) {
282 unique_fd fd(TEMP_FAILURE_RETRY(open(signature_path.c_str(), O_RDONLY | O_CLOEXEC)));
283 if (fd == -1) {
284 return ErrnoError();
285 }
286 Signature signature;
287 if (!signature.ParseFromFileDescriptor(fd.get())) {
288 return Error() << "Failed to parse";
289 }
290 return signature;
291}
292
293Result<std::map<std::string, std::string>>
294verifyAllFilesUsingCompOs(const std::string& directory_path,
295 const std::vector<uint8_t>& compos_key) {
296 std::map<std::string, std::string> new_digests;
297 std::vector<std::filesystem::path> signature_files;
298
299 std::error_code ec;
300 auto it = std::filesystem::recursive_directory_iterator(directory_path, ec);
301 for (auto end = std::filesystem::recursive_directory_iterator(); it != end; it.increment(ec)) {
302 auto& path = it->path();
303 if (it->is_regular_file()) {
304 if (isSignatureFile(path)) {
305 continue;
306 }
307
308 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
309 if (!fd.ok()) {
310 return ErrnoError() << "Can't open " << path;
311 }
312
313 auto signature_path = path;
314 signature_path += kSignatureExtension;
315 auto signature = readSignature(signature_path);
316 if (!signature.ok()) {
317 return Error() << "Invalid signature " << signature_path << ": "
318 << signature.error();
319 }
320 signature_files.push_back(signature_path);
321
322 // Note that these values are not yet trusted.
323 auto& raw_digest = signature->digest();
324 auto& raw_signature = signature->signature();
325
326 // Make sure the signature matches the CompOs public key, and not some other
327 // fs-verity trusted key.
328 auto verified = verifySignature(raw_digest, raw_signature, compos_key);
329 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}