blob: cab92e243a2ea7304c63a96f1237ef75ac65c5cf [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)));
Martijn Coenen309a2202021-03-15 23:45:07 +010077 if (fd < 0) {
78 return ErrnoError() << "Failed to open " << path;
79 }
Martijn Coenen95194842020-09-24 16:56:46 +020080
Martijn Coenen309a2202021-03-15 23:45:07 +010081 int ret = stat(path.c_str(), &filestat);
82 if (ret < 0) {
83 return ErrnoError() << "Failed to stat " << path;
84 }
Martijn Coenen95194842020-09-24 16:56:46 +020085 struct libfsverity_merkle_tree_params params = {
86 .version = 1,
87 .hash_algorithm = FS_VERITY_HASH_ALG_SHA256,
88 .file_size = static_cast<uint64_t>(filestat.st_size),
89 .block_size = 4096,
90 };
91
92 struct libfsverity_digest* digest;
Martijn Coenen309a2202021-03-15 23:45:07 +010093 ret = libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
94 if (ret < 0) {
95 return ErrnoError() << "Failed to compute fs-verity digest for " << path;
96 }
97 std::vector<uint8_t> digestVector(&digest->digest[0], &digest->digest[32]);
98 free(digest);
99 return digestVector;
Martijn Coenen95194842020-09-24 16:56:46 +0200100}
101
George Burgess IV69e41102021-03-10 10:35:38 -0800102namespace {
103template <typename T> struct DeleteAsPODArray {
104 void operator()(T* x) {
105 if (x) {
106 x->~T();
107 delete[](uint8_t*) x;
108 }
109 }
110};
111} // namespace
112
113template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
114
115template <typename T>
116static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
117 uint8_t* memory = new uint8_t[sizeof(T*) + trailing_data_size];
118 T* ptr = new (memory) T;
119 return trailing_unique_ptr<T>{ptr};
120}
121
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100122static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200123 const std::vector<uint8_t>& digest) {
George Burgess IV69e41102021-03-10 10:35:38 -0800124 auto d = makeUniqueWithTrailingData<fsverity_signed_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200125
126 memcpy(d->magic, "FSVerity", 8);
127 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
128 d->digest_size = cpu_to_le16(digest.size());
129 memcpy(d->digest, digest.data(), digest.size());
130
George Burgess IV69e41102021-03-10 10:35:38 -0800131 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200132 if (!signed_digest.ok()) {
133 return signed_digest.error();
134 }
135
136 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
137}
138
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100139Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Martijn Coenen95194842020-09-24 16:56:46 +0200140 auto digest = createDigest(path);
141 if (!digest.ok()) {
142 return digest.error();
143 }
144
145 auto signed_digest = signDigest(key, digest.value());
146 if (!signed_digest.ok()) {
147 return signed_digest.error();
148 }
149
150 auto pkcs7_data = createPkcs7(signed_digest.value());
151
152 struct fsverity_enable_arg arg = {.version = 1};
153
154 arg.sig_ptr = (uint64_t)pkcs7_data->data();
155 arg.sig_size = pkcs7_data->size();
156 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
157 arg.block_size = 4096;
158
159 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
160 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
161
162 if (ret != 0) {
163 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY on " << path;
164 }
165
Martijn Coenen5588e492021-02-25 14:33:44 +0100166 // Return the root hash as a hex string
167 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200168}
169
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100170Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
171 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100172 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200173 std::error_code ec;
174
175 auto it = std::filesystem::recursive_directory_iterator(path, ec);
176 auto end = std::filesystem::recursive_directory_iterator();
177
178 while (!ec && it != end) {
179 if (it->is_regular_file()) {
180 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
181 auto result = enableFsVerity(it->path(), key);
182 if (!result.ok()) {
183 return result.error();
184 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100185 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200186 }
187 ++it;
188 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100189 if (ec) {
190 return Error() << "Failed to iterate " << path << ": " << ec;
191 }
Martijn Coenen95194842020-09-24 16:56:46 +0200192
Martijn Coenen5588e492021-02-25 14:33:44 +0100193 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200194}
195
Martijn Coenen5588e492021-02-25 14:33:44 +0100196Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200197 unsigned int flags;
198
199 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
200 if (fd < 0) {
201 return ErrnoError() << "Failed to open " << path;
202 }
203
204 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
205 if (ret < 0) {
206 return ErrnoError() << "Failed to FS_IOC_GETFLAGS for " << path;
207 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100208 if (!(flags & FS_VERITY_FL)) {
209 return Error() << "File is not in fs-verity: " << path;
210 }
Martijn Coenen95194842020-09-24 16:56:46 +0200211
George Burgess IV69e41102021-03-10 10:35:38 -0800212 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
Martijn Coenen5588e492021-02-25 14:33:44 +0100213 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
George Burgess IV69e41102021-03-10 10:35:38 -0800214 ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
Martijn Coenen5588e492021-02-25 14:33:44 +0100215 if (ret < 0) {
216 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY for " << path;
217 }
George Burgess IVfb0b40f2021-03-10 13:31:33 -0800218 return toHex({&d->digest[0], &d->digest[d->digest_size]});
Martijn Coenen95194842020-09-24 16:56:46 +0200219}
220
Martijn Coenen5588e492021-02-25 14:33:44 +0100221Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
222 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200223 std::error_code ec;
224
225 auto it = std::filesystem::recursive_directory_iterator(path, ec);
226 auto end = std::filesystem::recursive_directory_iterator();
227
228 while (!ec && it != end) {
229 if (it->is_regular_file()) {
230 // Verify
231 auto result = isFileInVerity(it->path());
232 if (!result.ok()) {
233 return result.error();
234 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100235 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200236 } // TODO reject other types besides dirs?
237 ++it;
238 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100239 if (ec) {
240 return Error() << "Failed to iterate " << path << ": " << ec;
241 }
Martijn Coenen95194842020-09-24 16:56:46 +0200242
Martijn Coenen5588e492021-02-25 14:33:44 +0100243 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200244}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100245
246Result<void> addCertToFsVerityKeyring(const std::string& path) {
247 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", "fsv_ods"};
248
249 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
250 pid_t pid = fork();
251 if (pid == 0) {
252 dup2(fd, STDIN_FILENO);
253 close(fd);
254 int argc = arraysize(argv);
255 char* argv_child[argc + 1];
256 memcpy(argv_child, argv, argc * sizeof(char*));
257 argv_child[argc] = nullptr;
258 execvp(argv_child[0], const_cast<char**>(argv_child));
259 PLOG(ERROR) << "exec in ForkExecvp";
260 _exit(EXIT_FAILURE);
261 } else {
262 close(fd);
263 }
264 if (pid == -1) {
265 return ErrnoError() << "Failed to fork.";
266 }
267 int status;
268 if (waitpid(pid, &status, 0) == -1) {
269 return ErrnoError() << "waitpid() failed.";
270 }
271 if (!WIFEXITED(status)) {
272 return Error() << kFsVerityInitPath << ": abnormal process exit";
273 }
274 if (WEXITSTATUS(status)) {
275 if (status != 0) {
276 return Error() << kFsVerityInitPath << " exited with " << status;
277 }
278 }
279
280 return {};
281}