blob: 71ba8f6eb3d7a24eac8ba63605b883c40d785ba1 [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
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010091static Result<std::vector<uint8_t>> signDigest(const SigningKey& key,
Martijn Coenen95194842020-09-24 16:56:46 +020092 const std::vector<uint8_t>& digest) {
George Burgess IVcad5b122021-02-20 22:42:27 -080093 fsverity_signed_digest* d;
Martijn Coenen95194842020-09-24 16:56:46 +020094 size_t signed_digest_size = sizeof(*d) + digest.size();
George Burgess IVcad5b122021-02-20 22:42:27 -080095 std::unique_ptr<uint8_t[]> digest_buffer{new uint8_t[signed_digest_size]};
96 d = (fsverity_signed_digest*)digest_buffer.get();
Martijn Coenen95194842020-09-24 16:56:46 +020097
98 memcpy(d->magic, "FSVerity", 8);
99 d->digest_algorithm = cpu_to_le16(FS_VERITY_HASH_ALG_SHA256);
100 d->digest_size = cpu_to_le16(digest.size());
101 memcpy(d->digest, digest.data(), digest.size());
102
103 auto signed_digest = key.sign(std::string((char*)d, signed_digest_size));
104 if (!signed_digest.ok()) {
105 return signed_digest.error();
106 }
107
108 return std::vector<uint8_t>(signed_digest->begin(), signed_digest->end());
109}
110
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100111Result<std::string> enableFsVerity(const std::string& path, const SigningKey& key) {
Martijn Coenen95194842020-09-24 16:56:46 +0200112 auto digest = createDigest(path);
113 if (!digest.ok()) {
114 return digest.error();
115 }
116
117 auto signed_digest = signDigest(key, digest.value());
118 if (!signed_digest.ok()) {
119 return signed_digest.error();
120 }
121
122 auto pkcs7_data = createPkcs7(signed_digest.value());
123
124 struct fsverity_enable_arg arg = {.version = 1};
125
126 arg.sig_ptr = (uint64_t)pkcs7_data->data();
127 arg.sig_size = pkcs7_data->size();
128 arg.hash_algorithm = FS_VERITY_HASH_ALG_SHA256;
129 arg.block_size = 4096;
130
131 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
132 int ret = ioctl(fd, FS_IOC_ENABLE_VERITY, &arg);
133
134 if (ret != 0) {
135 return ErrnoError() << "Failed to call FS_IOC_ENABLE_VERITY on " << path;
136 }
137
Martijn Coenen5588e492021-02-25 14:33:44 +0100138 // Return the root hash as a hex string
139 return toHex(digest.value());
Martijn Coenen95194842020-09-24 16:56:46 +0200140}
141
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100142Result<std::map<std::string, std::string>> addFilesToVerityRecursive(const std::string& path,
143 const SigningKey& key) {
Martijn Coenen5588e492021-02-25 14:33:44 +0100144 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200145 std::error_code ec;
146
147 auto it = std::filesystem::recursive_directory_iterator(path, ec);
148 auto end = std::filesystem::recursive_directory_iterator();
149
150 while (!ec && it != end) {
151 if (it->is_regular_file()) {
152 LOG(INFO) << "Adding " << it->path() << " to fs-verity...";
153 auto result = enableFsVerity(it->path(), key);
154 if (!result.ok()) {
155 return result.error();
156 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100157 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200158 }
159 ++it;
160 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100161 if (ec) {
162 return Error() << "Failed to iterate " << path << ": " << ec;
163 }
Martijn Coenen95194842020-09-24 16:56:46 +0200164
Martijn Coenen5588e492021-02-25 14:33:44 +0100165 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200166}
167
Martijn Coenen5588e492021-02-25 14:33:44 +0100168Result<std::string> isFileInVerity(const std::string& path) {
Martijn Coenen95194842020-09-24 16:56:46 +0200169 unsigned int flags;
170
171 unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_CLOEXEC)));
172 if (fd < 0) {
173 return ErrnoError() << "Failed to open " << path;
174 }
175
176 int ret = ioctl(fd, FS_IOC_GETFLAGS, &flags);
177 if (ret < 0) {
178 return ErrnoError() << "Failed to FS_IOC_GETFLAGS for " << path;
179 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100180 if (!(flags & FS_VERITY_FL)) {
181 return Error() << "File is not in fs-verity: " << path;
182 }
Martijn Coenen95194842020-09-24 16:56:46 +0200183
Martijn Coenen5588e492021-02-25 14:33:44 +0100184 struct fsverity_digest* d;
185 d = (struct fsverity_digest*)malloc(sizeof(*d) + FS_VERITY_MAX_DIGEST_SIZE);
186 d->digest_size = FS_VERITY_MAX_DIGEST_SIZE;
187 ret = ioctl(fd, FS_IOC_MEASURE_VERITY, d);
188 if (ret < 0) {
189 return ErrnoError() << "Failed to FS_IOC_MEASURE_VERITY for " << path;
190 }
191 std::vector<uint8_t> digest_vector(&d->digest[0], &d->digest[d->digest_size]);
192
193 return toHex(digest_vector);
Martijn Coenen95194842020-09-24 16:56:46 +0200194}
195
Martijn Coenen5588e492021-02-25 14:33:44 +0100196Result<std::map<std::string, std::string>> verifyAllFilesInVerity(const std::string& path) {
197 std::map<std::string, std::string> digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200198 std::error_code ec;
199
200 auto it = std::filesystem::recursive_directory_iterator(path, ec);
201 auto end = std::filesystem::recursive_directory_iterator();
202
203 while (!ec && it != end) {
204 if (it->is_regular_file()) {
205 // Verify
206 auto result = isFileInVerity(it->path());
207 if (!result.ok()) {
208 return result.error();
209 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100210 digests[it->path()] = *result;
Martijn Coenen95194842020-09-24 16:56:46 +0200211 } // TODO reject other types besides dirs?
212 ++it;
213 }
Martijn Coenen5588e492021-02-25 14:33:44 +0100214 if (ec) {
215 return Error() << "Failed to iterate " << path << ": " << ec;
216 }
Martijn Coenen95194842020-09-24 16:56:46 +0200217
Martijn Coenen5588e492021-02-25 14:33:44 +0100218 return digests;
Martijn Coenen95194842020-09-24 16:56:46 +0200219}
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100220
221Result<void> addCertToFsVerityKeyring(const std::string& path) {
222 const char* const argv[] = {kFsVerityInitPath, "--load-extra-key", "fsv_ods"};
223
224 int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC);
225 pid_t pid = fork();
226 if (pid == 0) {
227 dup2(fd, STDIN_FILENO);
228 close(fd);
229 int argc = arraysize(argv);
230 char* argv_child[argc + 1];
231 memcpy(argv_child, argv, argc * sizeof(char*));
232 argv_child[argc] = nullptr;
233 execvp(argv_child[0], const_cast<char**>(argv_child));
234 PLOG(ERROR) << "exec in ForkExecvp";
235 _exit(EXIT_FAILURE);
236 } else {
237 close(fd);
238 }
239 if (pid == -1) {
240 return ErrnoError() << "Failed to fork.";
241 }
242 int status;
243 if (waitpid(pid, &status, 0) == -1) {
244 return ErrnoError() << "waitpid() failed.";
245 }
246 if (!WIFEXITED(status)) {
247 return Error() << kFsVerityInitPath << ": abnormal process exit";
248 }
249 if (WEXITSTATUS(status)) {
250 if (status != 0) {
251 return Error() << kFsVerityInitPath << " exited with " << status;
252 }
253 }
254
255 return {};
256}