blob: ff7de7e0547ddaf4958c038eb447674360f83772 [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
53struct fsverity_signed_digest {
54 char magic[8]; /* must be "FSVerity" */
55 __le16 digest_algorithm;
56 __le16 digest_size;
57 __u8 digest[];
58};
59
George Burgess IVfb0b40f2021-03-10 13:31:33 -080060static std::string toHex(std::span<uint8_t> data) {
Martijn Coenen5588e492021-02-25 14:33:44 +010061 std::stringstream ss;
62 for (auto it = data.begin(); it != data.end(); ++it) {
63 ss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(*it);
64 }
65 return ss.str();
66}
67
Martijn Coenen95194842020-09-24 16:56:46 +020068static int read_callback(void* file, void* buf, size_t count) {
69 int* fd = (int*)file;
70 if (TEMP_FAILURE_RETRY(read(*fd, buf, count)) < 0) return errno ? -errno : -EIO;
71 return 0;
72}
73
Martijn Coenen5588e492021-02-25 14:33:44 +010074Result<std::vector<uint8_t>> createDigest(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +020075 struct stat filestat;
76 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
77
78 stat(path.c_str(), &filestat);
79 struct libfsverity_merkle_tree_params params = {
80 .version = 1,
81 .hash_algorithm = FS_VERITY_HASH_ALG_SHA256,
82 .file_size = static_cast<uint64_t>(filestat.st_size),
83 .block_size = 4096,
84 };
85
86 struct libfsverity_digest* digest;
87 libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
88
89 return std::vector<uint8_t>(&digest->digest[0], &digest->digest[32]);
90}
91
George Burgess IV69e41102021-03-10 10:35:38 -080092namespace {
93template <typename T> struct DeleteAsPODArray {
94 void operator()(T* x) {
95 if (x) {
96 x->~T();
97 delete[](uint8_t*) x;
98 }
99 }
100};
101} // namespace
102
103template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
104
105template <typename T>
106static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
107 uint8_t* memory = new uint8_t[sizeof(T*) + trailing_data_size];
108 T* ptr = new (memory) T;
109 return trailing_unique_ptr<T>{ptr};
110}
111
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100112static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200113 const std::vector<uint8_t>& digest) {
George Burgess IV69e41102021-03-10 10:35:38 -0800114 auto d = makeUniqueWithTrailingData<fsverity_signed_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200115
116 memcpy(d->magic, "FSVerity", 8);
117 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
118 d->digest_size = cpu_to_le16(digest.size());
119 memcpy(d->digest, digest.data(), digest.size());
120
George Burgess IV69e41102021-03-10 10:35:38 -0800121 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200122 if (!signed_digest.ok()) {
123 return signed_digest.error();
124 }
125
126 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
127}
128
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100129Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Martijn Coenen95194842020-09-24 16:56:46 +0200130 auto digest = createDigest(path);
131 if (!digest.ok()) {
132 return digest.error();
133 }
134
135 auto signed_digest = signDigest(key, digest.value());
136 if (!signed_digest.ok()) {
137 return signed_digest.error();
138 }
139
140 auto pkcs7_data = createPkcs7(signed_digest.value());
141
142 struct fsverity_enable_arg arg = {.version = 1};
143
144 arg.sig_ptr = (uint64_t)pkcs7_data->data();
145 arg.sig_size = pkcs7_data->size();
146 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
147 arg.block_size = 4096;
148
149 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
150 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
151
152 if (ret != 0) {
153 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY on " << path;
154 }
155
Martijn Coenen5588e492021-02-25 14:33:44 +0100156 // Return the root hash as a hex string
157 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200158}
159
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100160Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
161 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100162 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200163 std::error_code ec;
164
165 auto it = std::filesystem::recursive_directory_iterator(path, ec);
166 auto end = std::filesystem::recursive_directory_iterator();
167
168 while (!ec && it != end) {
169 if (it->is_regular_file()) {
170 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
171 auto result = enableFsVerity(it->path(), key);
172 if (!result.ok()) {
173 return result.error();
174 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100175 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200176 }
177 ++it;
178 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100179 if (ec) {
180 return Error() << "Failed to iterate " << path << ": " << ec;
181 }
Martijn Coenen95194842020-09-24 16:56:46 +0200182
Martijn Coenen5588e492021-02-25 14:33:44 +0100183 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200184}
185
Martijn Coenen5588e492021-02-25 14:33:44 +0100186Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200187 unsigned int flags;
188
189 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
190 if (fd < 0) {
191 return ErrnoError() << "Failed to open " << path;
192 }
193
194 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
195 if (ret < 0) {
196 return ErrnoError() << "Failed to FS_IOC_GETFLAGS for " << path;
197 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100198 if (!(flags & FS_VERITY_FL)) {
199 return Error() << "File is not in fs-verity: " << path;
200 }
Martijn Coenen95194842020-09-24 16:56:46 +0200201
George Burgess IV69e41102021-03-10 10:35:38 -0800202 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
Martijn Coenen5588e492021-02-25 14:33:44 +0100203 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
George Burgess IV69e41102021-03-10 10:35:38 -0800204 ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
Martijn Coenen5588e492021-02-25 14:33:44 +0100205 if (ret < 0) {
206 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY for " << path;
207 }
George Burgess IVfb0b40f2021-03-10 13:31:33 -0800208 return toHex({&d->digest[0], &d->digest[d->digest_size]});
Martijn Coenen95194842020-09-24 16:56:46 +0200209}
210
Martijn Coenen5588e492021-02-25 14:33:44 +0100211Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
212 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200213 std::error_code ec;
214
215 auto it = std::filesystem::recursive_directory_iterator(path, ec);
216 auto end = std::filesystem::recursive_directory_iterator();
217
218 while (!ec && it != end) {
219 if (it->is_regular_file()) {
220 // Verify
221 auto result = isFileInVerity(it->path());
222 if (!result.ok()) {
223 return result.error();
224 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100225 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200226 } // TODO reject other types besides dirs?
227 ++it;
228 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100229 if (ec) {
230 return Error() << "Failed to iterate " << path << ": " << ec;
231 }
Martijn Coenen95194842020-09-24 16:56:46 +0200232
Martijn Coenen5588e492021-02-25 14:33:44 +0100233 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200234}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100235
236Result<void> addCertToFsVerityKeyring(const std::string& path) {
237 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", "fsv_ods"};
238
239 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
240 pid_t pid = fork();
241 if (pid == 0) {
242 dup2(fd, STDIN_FILENO);
243 close(fd);
244 int argc = arraysize(argv);
245 char* argv_child[argc + 1];
246 memcpy(argv_child, argv, argc * sizeof(char*));
247 argv_child[argc] = nullptr;
248 execvp(argv_child[0], const_cast<char**>(argv_child));
249 PLOG(ERROR) << "exec in ForkExecvp";
250 _exit(EXIT_FAILURE);
251 } else {
252 close(fd);
253 }
254 if (pid == -1) {
255 return ErrnoError() << "Failed to fork.";
256 }
257 int status;
258 if (waitpid(pid, &status, 0) == -1) {
259 return ErrnoError() << "waitpid() failed.";
260 }
261 if (!WIFEXITED(status)) {
262 return Error() << kFsVerityInitPath << ": abnormal process exit";
263 }
264 if (WEXITSTATUS(status)) {
265 if (status != 0) {
266 return Error() << kFsVerityInitPath << " exited with " << status;
267 }
268 }
269
270 return {};
271}