blob: a8d72fc1f93c19ad08ee6eda2eadf27ef51e6e5a [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>
Martijn Coenen95194842020-09-24 16:56:46 +020019#include <string>
20
21#include <fcntl.h>
22#include <linux/fs.h>
23#include <sys/stat.h>
24#include <sys/types.h>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010025#include <sys/wait.h>
Martijn Coenen95194842020-09-24 16:56:46 +020026
27#include <android-base/logging.h>
28#include <android-base/unique_fd.h>
29#include <libfsverity.h>
30#include <linux/fsverity.h>
31
32#include "CertUtils.h"
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010033#include "SigningKey.h"
Martijn Coenen95194842020-09-24 16:56:46 +020034
Martijn Coenen5588e492021-02-25 14:33:44 +010035#define FS_VERITY_MAX_DIGEST_SIZE 64
36
Martijn Coenen95194842020-09-24 16:56:46 +020037using android::base::ErrnoError;
38using android::base::Error;
39using android::base::Result;
40using android::base::unique_fd;
41
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010042static const char* kFsVerityInitPath = "/system/bin/fsverity_init";
43
Martijn Coenen95194842020-09-24 16:56:46 +020044#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
45#define cpu_to_le16(v) ((__force __le16)(uint16_t)(v))
46#define le16_to_cpu(v) ((__force uint16_t)(__le16)(v))
47#else
48#define cpu_to_le16(v) ((__force __le16)__builtin_bswap16(v))
49#define le16_to_cpu(v) (__builtin_bswap16((__force uint16_t)(v)))
50#endif
51
52struct fsverity_signed_digest {
53 char magic[8]; /* must be "FSVerity" */
54 __le16 digest_algorithm;
55 __le16 digest_size;
56 __u8 digest[];
57};
58
Martijn Coenen5588e492021-02-25 14:33:44 +010059static std::string toHex(const std::vector<uint8_t>& data) {
60 std::stringstream ss;
61 for (auto it = data.begin(); it != data.end(); ++it) {
62 ss << std::setfill('0') << std::setw(2) << std::hex << static_cast<unsigned>(*it);
63 }
64 return ss.str();
65}
66
Martijn Coenen95194842020-09-24 16:56:46 +020067static int read_callback(void* file, void* buf, size_t count) {
68 int* fd = (int*)file;
69 if (TEMP_FAILURE_RETRY(read(*fd, buf, count)) < 0) return errno ? -errno : -EIO;
70 return 0;
71}
72
Martijn Coenen5588e492021-02-25 14:33:44 +010073Result<std::vector<uint8_t>> createDigest(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +020074 struct stat filestat;
75 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
76
77 stat(path.c_str(), &filestat);
78 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;
86 libfsverity_compute_digest(&fd, &read_callback, &params, &digest);
87
88 return std::vector<uint8_t>(&digest->digest[0], &digest->digest[32]);
89}
90
George Burgess IV69e41102021-03-10 10:35:38 -080091namespace {
92template <typename T> struct DeleteAsPODArray {
93 void operator()(T* x) {
94 if (x) {
95 x->~T();
96 delete[](uint8_t*) x;
97 }
98 }
99};
100} // namespace
101
102template <typename T> using trailing_unique_ptr = std::unique_ptr<T, DeleteAsPODArray<T>>;
103
104template <typename T>
105static trailing_unique_ptr<T> makeUniqueWithTrailingData(size_t trailing_data_size) {
106 uint8_t* memory = new uint8_t[sizeof(T*) + trailing_data_size];
107 T* ptr = new (memory) T;
108 return trailing_unique_ptr<T>{ptr};
109}
110
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100111static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +0200112 const std::vector<uint8_t>& digest) {
George Burgess IV69e41102021-03-10 10:35:38 -0800113 auto d = makeUniqueWithTrailingData<fsverity_signed_digest>(digest.size());
Martijn Coenen95194842020-09-24 16:56:46 +0200114
115 memcpy(d->magic, "FSVerity", 8);
116 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
117 d->digest_size = cpu_to_le16(digest.size());
118 memcpy(d->digest, digest.data(), digest.size());
119
George Burgess IV69e41102021-03-10 10:35:38 -0800120 auto signed_digest = key.sign(std::string((char*)d.get(), sizeof(*d) + digest.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200121 if (!signed_digest.ok()) {
122 return signed_digest.error();
123 }
124
125 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
126}
127
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100128Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Martijn Coenen95194842020-09-24 16:56:46 +0200129 auto digest = createDigest(path);
130 if (!digest.ok()) {
131 return digest.error();
132 }
133
134 auto signed_digest = signDigest(key, digest.value());
135 if (!signed_digest.ok()) {
136 return signed_digest.error();
137 }
138
139 auto pkcs7_data = createPkcs7(signed_digest.value());
140
141 struct fsverity_enable_arg arg = {.version = 1};
142
143 arg.sig_ptr = (uint64_t)pkcs7_data->data();
144 arg.sig_size = pkcs7_data->size();
145 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
146 arg.block_size = 4096;
147
148 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
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 on " << path;
153 }
154
Martijn Coenen5588e492021-02-25 14:33:44 +0100155 // Return the root hash as a hex string
156 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200157}
158
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100159Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
160 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100161 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200162 std::error_code ec;
163
164 auto it = std::filesystem::recursive_directory_iterator(path, ec);
165 auto end = std::filesystem::recursive_directory_iterator();
166
167 while (!ec && it != end) {
168 if (it->is_regular_file()) {
169 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
170 auto result = enableFsVerity(it->path(), key);
171 if (!result.ok()) {
172 return result.error();
173 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100174 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200175 }
176 ++it;
177 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100178 if (ec) {
179 return Error() << "Failed to iterate " << path << ": " << ec;
180 }
Martijn Coenen95194842020-09-24 16:56:46 +0200181
Martijn Coenen5588e492021-02-25 14:33:44 +0100182 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200183}
184
Martijn Coenen5588e492021-02-25 14:33:44 +0100185Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200186 unsigned int flags;
187
188 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
189 if (fd < 0) {
190 return ErrnoError() << "Failed to open " << path;
191 }
192
193 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
194 if (ret < 0) {
195 return ErrnoError() << "Failed to FS_IOC_GETFLAGS for " << path;
196 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100197 if (!(flags & FS_VERITY_FL)) {
198 return Error() << "File is not in fs-verity: " << path;
199 }
Martijn Coenen95194842020-09-24 16:56:46 +0200200
George Burgess IV69e41102021-03-10 10:35:38 -0800201 auto d = makeUniqueWithTrailingData<fsverity_digest>(FS_VERITY_MAX_DIGEST_SIZE);
Martijn Coenen5588e492021-02-25 14:33:44 +0100202 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
George Burgess IV69e41102021-03-10 10:35:38 -0800203 ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d.get());
Martijn Coenen5588e492021-02-25 14:33:44 +0100204 if (ret < 0) {
205 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY for " << path;
206 }
207 std::vector<uint8_t> digest_vector(&d->digest[0], &d->digest[d->digest_size]);
208
209 return toHex(digest_vector);
Martijn Coenen95194842020-09-24 16:56:46 +0200210}
211
Martijn Coenen5588e492021-02-25 14:33:44 +0100212Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
213 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200214 std::error_code ec;
215
216 auto it = std::filesystem::recursive_directory_iterator(path, ec);
217 auto end = std::filesystem::recursive_directory_iterator();
218
219 while (!ec && it != end) {
220 if (it->is_regular_file()) {
221 // Verify
222 auto result = isFileInVerity(it->path());
223 if (!result.ok()) {
224 return result.error();
225 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100226 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200227 } // TODO reject other types besides dirs?
228 ++it;
229 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100230 if (ec) {
231 return Error() << "Failed to iterate " << path << ": " << ec;
232 }
Martijn Coenen95194842020-09-24 16:56:46 +0200233
Martijn Coenen5588e492021-02-25 14:33:44 +0100234 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200235}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100236
237Result<void> addCertToFsVerityKeyring(const std::string& path) {
238 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", "fsv_ods"};
239
240 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
241 pid_t pid = fork();
242 if (pid == 0) {
243 dup2(fd, STDIN_FILENO);
244 close(fd);
245 int argc = arraysize(argv);
246 char* argv_child[argc + 1];
247 memcpy(argv_child, argv, argc * sizeof(char*));
248 argv_child[argc] = nullptr;
249 execvp(argv_child[0], const_cast<char**>(argv_child));
250 PLOG(ERROR) << "exec in ForkExecvp";
251 _exit(EXIT_FAILURE);
252 } else {
253 close(fd);
254 }
255 if (pid == -1) {
256 return ErrnoError() << "Failed to fork.";
257 }
258 int status;
259 if (waitpid(pid, &status, 0) == -1) {
260 return ErrnoError() << "waitpid() failed.";
261 }
262 if (!WIFEXITED(status)) {
263 return Error() << kFsVerityInitPath << ": abnormal process exit";
264 }
265 if (WEXITSTATUS(status)) {
266 if (status != 0) {
267 return Error() << kFsVerityInitPath << " exited with " << status;
268 }
269 }
270
271 return {};
272}