blob: 243e7df8c4220e7393749ff1a26e02417611717b [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"
Martijn Coenen95194842020-09-24 16:56:46 +020035
Martijn Coenen5588e492021-02-25 14:33:44 +010036#define FS_VERITY_MAX_DIGEST_SIZE 64
37
Martijn Coenen95194842020-09-24 16:56:46 +020038using android::base::ErrnoError;
39using android::base::Error;
40using android::base::Result;
41using android::base::unique_fd;
42
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010043static const char* kFsVerityInitPath = "/system/bin/fsverity_init";
44
Martijn Coenen95194842020-09-24 16:56:46 +020045#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
46#define cpu_to_le16(v) ((__force __le16)(uint16_t)(v))
47#define le16_to_cpu(v) ((__force uint16_t)(__le16)(v))
48#else
49#define cpu_to_le16(v) ((__force __le16)__builtin_bswap16(v))
50#define le16_to_cpu(v) (__builtin_bswap16((__force uint16_t)(v)))
51#endif
52
George Burgess IVfb0b40f2021-03-10 13:31:33 -080053static std::string toHex(std::span<uint8_t> data) {
Martijn Coenen5588e492021-02-25 14:33:44 +010054 std::stringstream ss;
55 for (auto it = data.begin(); it != data.end(); ++it) {
56 ss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(*it);
57 }
58 return ss.str();
59}
60
Martijn Coenen95194842020-09-24 16:56:46 +020061static int read_callback(void* file, void* buf, size_t count) {
62 int* fd = (int*)file;
63 if (TEMP_FAILURE_RETRY(read(*fd, buf, count)) < 0) return errno ? -errno : -EIO;
64 return 0;
65}
66
Martijn Coenen5588e492021-02-25 14:33:44 +010067Result<std::vector<uint8_t>> createDigest(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +020068 struct stat filestat;
69 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
Martijn Coenen309a2202021-03-15 23:45:07 +010070 if (fd < 0) {
71 return ErrnoError() << "Failed to open " << path;
72 }
Martijn Coenen95194842020-09-24 16:56:46 +020073
Martijn Coenen309a2202021-03-15 23:45:07 +010074 int ret = stat(path.c_str(), &filestat);
75 if (ret < 0) {
76 return ErrnoError() << "Failed to stat " << path;
77 }
Martijn Coenen95194842020-09-24 16:56:46 +020078 struct libfsverity_merkle_tree_params params = {
79 .version = 1,
80 .hash_algorithm = FS_VERITY_HASH_ALG_SHA256,
81 .file_size = static_cast<uint64_t>(filestat.st_size),
82 .block_size = 4096,
83 };
84
85 struct libfsverity_digest* digest;
Martijn Coenen309a2202021-03-15 23:45:07 +010086 ret = libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
87 if (ret < 0) {
88 return ErrnoError() << "Failed to compute fs-verity digest for " << path;
89 }
90 std::vector<uint8_t> digestVector(&digest->digest[0], &digest->digest[32]);
91 free(digest);
92 return digestVector;
Martijn Coenen95194842020-09-24 16:56:46 +020093}
94
George Burgess IV69e41102021-03-10 10:35:38 -080095namespace {
96template <typename T> struct DeleteAsPODArray {
97 void operator()(T* x) {
98 if (x) {
99 x->~T();
100 delete[](uint8_t*) x;
101 }
102 }
103};
104} // namespace
105
106template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
107
108template <typename T>
109static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
110 uint8_t* memory = new uint8_t[sizeof(T*) + trailing_data_size];
111 T* ptr = new (memory) T;
112 return trailing_unique_ptr<T>{ptr};
113}
114
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100115static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200116 const std::vector<uint8_t>& digest) {
Eric Biggers37708582021-06-09 16:32:35 -0700117 auto d = makeUniqueWithTrailingData<fsverity_formatted_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200118
119 memcpy(d->magic, "FSVerity", 8);
120 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
121 d->digest_size = cpu_to_le16(digest.size());
122 memcpy(d->digest, digest.data(), digest.size());
123
George Burgess IV69e41102021-03-10 10:35:38 -0800124 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200125 if (!signed_digest.ok()) {
126 return signed_digest.error();
127 }
128
129 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
130}
131
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100132Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Martijn Coenen95194842020-09-24 16:56:46 +0200133 auto digest = createDigest(path);
134 if (!digest.ok()) {
135 return digest.error();
136 }
137
138 auto signed_digest = signDigest(key, digest.value());
139 if (!signed_digest.ok()) {
140 return signed_digest.error();
141 }
142
143 auto pkcs7_data = createPkcs7(signed_digest.value());
144
145 struct fsverity_enable_arg arg = {.version = 1};
146
147 arg.sig_ptr = (uint64_t)pkcs7_data->data();
148 arg.sig_size = pkcs7_data->size();
149 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
150 arg.block_size = 4096;
151
152 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
153 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
154
155 if (ret != 0) {
156 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY on " << path;
157 }
158
Martijn Coenen5588e492021-02-25 14:33:44 +0100159 // Return the root hash as a hex string
160 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200161}
162
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100163Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
164 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100165 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200166 std::error_code ec;
167
168 auto it = std::filesystem::recursive_directory_iterator(path, ec);
169 auto end = std::filesystem::recursive_directory_iterator();
170
171 while (!ec && it != end) {
172 if (it->is_regular_file()) {
173 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
174 auto result = enableFsVerity(it->path(), key);
175 if (!result.ok()) {
176 return result.error();
177 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100178 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200179 }
180 ++it;
181 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100182 if (ec) {
183 return Error() << "Failed to iterate " << path << ": " << ec;
184 }
Martijn Coenen95194842020-09-24 16:56:46 +0200185
Martijn Coenen5588e492021-02-25 14:33:44 +0100186 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200187}
188
Martijn Coenen5588e492021-02-25 14:33:44 +0100189Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200190 unsigned int flags;
191
192 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
193 if (fd < 0) {
194 return ErrnoError() << "Failed to open " << path;
195 }
196
197 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
198 if (ret < 0) {
199 return ErrnoError() << "Failed to FS_IOC_GETFLAGS for " << path;
200 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100201 if (!(flags & FS_VERITY_FL)) {
202 return Error() << "File is not in fs-verity: " << path;
203 }
Martijn Coenen95194842020-09-24 16:56:46 +0200204
George Burgess IV69e41102021-03-10 10:35:38 -0800205 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
Martijn Coenen5588e492021-02-25 14:33:44 +0100206 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
George Burgess IV69e41102021-03-10 10:35:38 -0800207 ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
Martijn Coenen5588e492021-02-25 14:33:44 +0100208 if (ret < 0) {
209 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY for " << path;
210 }
George Burgess IVfb0b40f2021-03-10 13:31:33 -0800211 return toHex({&d->digest[0], &d->digest[d->digest_size]});
Martijn Coenen95194842020-09-24 16:56:46 +0200212}
213
Martijn Coenen5588e492021-02-25 14:33:44 +0100214Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
215 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200216 std::error_code ec;
217
218 auto it = std::filesystem::recursive_directory_iterator(path, ec);
219 auto end = std::filesystem::recursive_directory_iterator();
220
221 while (!ec && it != end) {
222 if (it->is_regular_file()) {
Martijn Coenen0f760d72021-06-29 10:31:01 +0200223 // Verify the file is in fs-verity
Martijn Coenen95194842020-09-24 16:56:46 +0200224 auto result = isFileInVerity(it->path());
225 if (!result.ok()) {
226 return result.error();
227 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100228 digests[it->path()] = *result;
Martijn Coenen0f760d72021-06-29 10:31:01 +0200229 } else if (it->is_directory()) {
230 // These are fine to ignore
231 } else if (it->is_symlink()) {
232 return Error() << "Rejecting artifacts, symlink at " << it->path();
233 } else {
234 return Error() << "Rejecting artifacts, unexpected file type for " << it->path();
235 }
Martijn Coenen95194842020-09-24 16:56:46 +0200236 ++it;
237 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100238 if (ec) {
239 return Error() << "Failed to iterate " << path << ": " << ec;
240 }
Martijn Coenen95194842020-09-24 16:56:46 +0200241
Martijn Coenen5588e492021-02-25 14:33:44 +0100242 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200243}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100244
Alan Stokesb1821782021-06-07 14:57:15 +0100245Result<void> addCertToFsVerityKeyring(const std::string& path, const char* keyName) {
246 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", keyName};
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100247
248 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
Alan Stokes246a7f12021-06-10 14:30:53 +0100249 if (fd == -1) {
250 return ErrnoError() << "Failed to open " << path;
251 }
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100252 pid_t pid = fork();
253 if (pid == 0) {
254 dup2(fd, STDIN_FILENO);
255 close(fd);
256 int argc = arraysize(argv);
257 char* argv_child[argc + 1];
258 memcpy(argv_child, argv, argc * sizeof(char*));
259 argv_child[argc] = nullptr;
Alan Stokes3b885982021-06-07 11:34:26 +0100260 execvp(argv_child[0], argv_child);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100261 PLOG(ERROR) << "exec in ForkExecvp";
262 _exit(EXIT_FAILURE);
263 } else {
264 close(fd);
265 }
266 if (pid == -1) {
267 return ErrnoError() << "Failed to fork.";
268 }
269 int status;
270 if (waitpid(pid, &status, 0) == -1) {
271 return ErrnoError() << "waitpid() failed.";
272 }
273 if (!WIFEXITED(status)) {
274 return Error() << kFsVerityInitPath << ": abnormal process exit";
275 }
Alan Stokes246a7f12021-06-10 14:30:53 +0100276 if (WEXITSTATUS(status) != 0) {
277 return Error() << kFsVerityInitPath << " exited with " << WEXITSTATUS(status);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100278 }
279
280 return {};
281}