fs_mgr_avb.cpp revision 87d0836cda90b33ee97d63ef61a10dd23d82581a
1/*
2 * Copyright (C) 2016 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 <errno.h>
18#include <fcntl.h>
19#include <inttypes.h>
20#include <libgen.h>
21#include <stdio.h>
22#include <string.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
26#include <vector>
27
28#include <android-base/file.h>
29#include <android-base/parseint.h>
30#include <android-base/properties.h>
31#include <android-base/strings.h>
32#include <android-base/unique_fd.h>
33#include <cutils/properties.h>
34#include <libavb/libavb.h>
35#include <openssl/sha.h>
36#include <sys/ioctl.h>
37#include <utils/Compat.h>
38
39#include "fs_mgr.h"
40#include "fs_mgr_avb_ops.h"
41#include "fs_mgr_priv.h"
42#include "fs_mgr_priv_avb.h"
43#include "fs_mgr_priv_dm_ioctl.h"
44#include "fs_mgr_priv_sha.h"
45
46/* The format of dm-verity construction parameters:
47 *     <version> <dev> <hash_dev> <data_block_size> <hash_block_size>
48 *     <num_data_blocks> <hash_start_block> <algorithm> <digest> <salt>
49 */
50#define VERITY_TABLE_FORMAT \
51    "%u %s %s %u %u "       \
52    "%" PRIu64 " %" PRIu64 " %s %s %s "
53
54#define VERITY_TABLE_PARAMS(hashtree_desc, blk_device, digest, salt)                        \
55    hashtree_desc.dm_verity_version, blk_device, blk_device, hashtree_desc.data_block_size, \
56        hashtree_desc.hash_block_size,                                                      \
57        hashtree_desc.image_size / hashtree_desc.data_block_size,  /* num_data_blocks. */   \
58        hashtree_desc.tree_offset / hashtree_desc.hash_block_size, /* hash_start_block. */  \
59        (char*)hashtree_desc.hash_algorithm, digest, salt
60
61#define VERITY_TABLE_OPT_RESTART "restart_on_corruption"
62#define VERITY_TABLE_OPT_IGNZERO "ignore_zero_blocks"
63
64/* The default format of dm-verity optional parameters:
65 *     <#opt_params> ignore_zero_blocks restart_on_corruption
66 */
67#define VERITY_TABLE_OPT_DEFAULT_FORMAT "2 %s %s"
68#define VERITY_TABLE_OPT_DEFAULT_PARAMS VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART
69
70/* The FEC (forward error correction) format of dm-verity optional parameters:
71 *     <#opt_params> use_fec_from_device <fec_dev>
72 *     fec_roots <num> fec_blocks <num> fec_start <offset>
73 *     ignore_zero_blocks restart_on_corruption
74 */
75#define VERITY_TABLE_OPT_FEC_FORMAT \
76    "10 use_fec_from_device %s fec_roots %u fec_blocks %" PRIu64 " fec_start %" PRIu64 " %s %s"
77
78/* Note that fec_blocks is the size that FEC covers, *not* the
79 * size of the FEC data. Since we use FEC for everything up until
80 * the FEC data, it's the same as the offset (fec_start).
81 */
82#define VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device)                     \
83    blk_device, hashtree_desc.fec_num_roots,                                       \
84        hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_blocks */ \
85        hashtree_desc.fec_offset / hashtree_desc.data_block_size, /* fec_start */  \
86        VERITY_TABLE_OPT_IGNZERO, VERITY_TABLE_OPT_RESTART
87
88AvbSlotVerifyData* fs_mgr_avb_verify_data = nullptr;
89AvbOps* fs_mgr_avb_ops = nullptr;
90
91enum HashAlgorithm {
92    kInvalid = 0,
93    kSHA256 = 1,
94    kSHA512 = 2,
95};
96
97struct androidboot_vbmeta {
98    HashAlgorithm hash_alg;
99    uint8_t digest[SHA512_DIGEST_LENGTH];
100    size_t vbmeta_size;
101    bool allow_verification_error;
102};
103
104androidboot_vbmeta fs_mgr_vbmeta_prop;
105
106static inline bool nibble_value(const char& c, uint8_t* value) {
107    FS_MGR_CHECK(value != nullptr);
108
109    switch (c) {
110        case '0' ... '9':
111            *value = c - '0';
112            break;
113        case 'a' ... 'f':
114            *value = c - 'a' + 10;
115            break;
116        case 'A' ... 'F':
117            *value = c - 'A' + 10;
118            break;
119        default:
120            return false;
121    }
122
123    return true;
124}
125
126static bool hex_to_bytes(uint8_t* bytes, size_t bytes_len, const std::string& hex) {
127    FS_MGR_CHECK(bytes != nullptr);
128
129    if (hex.size() % 2 != 0) {
130        return false;
131    }
132    if (hex.size() / 2 > bytes_len) {
133        return false;
134    }
135    for (size_t i = 0, j = 0, n = hex.size(); i < n; i += 2, ++j) {
136        uint8_t high;
137        if (!nibble_value(hex[i], &high)) {
138            return false;
139        }
140        uint8_t low;
141        if (!nibble_value(hex[i + 1], &low)) {
142            return false;
143        }
144        bytes[j] = (high << 4) | low;
145    }
146    return true;
147}
148
149static std::string bytes_to_hex(const uint8_t* bytes, size_t bytes_len) {
150    FS_MGR_CHECK(bytes != nullptr);
151
152    static const char* hex_digits = "0123456789abcdef";
153    std::string hex;
154
155    for (size_t i = 0; i < bytes_len; i++) {
156        hex.push_back(hex_digits[(bytes[i] & 0xF0) >> 4]);
157        hex.push_back(hex_digits[bytes[i] & 0x0F]);
158    }
159    return hex;
160}
161
162static bool load_vbmeta_prop(androidboot_vbmeta* vbmeta_prop) {
163    FS_MGR_CHECK(vbmeta_prop != nullptr);
164
165    std::string cmdline;
166    android::base::ReadFileToString("/proc/cmdline", &cmdline);
167
168    std::string hash_alg;
169    std::string digest;
170
171    for (const auto& entry : android::base::Split(android::base::Trim(cmdline), " ")) {
172        std::vector<std::string> pieces = android::base::Split(entry, "=");
173        const std::string& key = pieces[0];
174        const std::string& value = pieces[1];
175
176        if (key == "androidboot.vbmeta.device_state") {
177            vbmeta_prop->allow_verification_error = (value == "unlocked");
178        } else if (key == "androidboot.vbmeta.hash_alg") {
179            hash_alg = value;
180        } else if (key == "androidboot.vbmeta.size") {
181            if (!android::base::ParseUint(value.c_str(), &vbmeta_prop->vbmeta_size)) {
182                return false;
183            }
184        } else if (key == "androidboot.vbmeta.digest") {
185            digest = value;
186        }
187    }
188
189    // Reads hash algorithm.
190    size_t expected_digest_size = 0;
191    if (hash_alg == "sha256") {
192        expected_digest_size = SHA256_DIGEST_LENGTH * 2;
193        vbmeta_prop->hash_alg = kSHA256;
194    } else if (hash_alg == "sha512") {
195        expected_digest_size = SHA512_DIGEST_LENGTH * 2;
196        vbmeta_prop->hash_alg = kSHA512;
197    } else {
198        LERROR << "Unknown hash algorithm: " << hash_alg.c_str();
199        return false;
200    }
201
202    // Reads digest.
203    if (digest.size() != expected_digest_size) {
204        LERROR << "Unexpected digest size: " << digest.size()
205               << " (expected: " << expected_digest_size << ")";
206        return false;
207    }
208
209    if (!hex_to_bytes(vbmeta_prop->digest, sizeof(vbmeta_prop->digest), digest)) {
210        LERROR << "Hash digest contains non-hexidecimal character: " << digest.c_str();
211        return false;
212    }
213
214    return true;
215}
216
217template <typename Hasher>
218static std::pair<size_t, bool> verify_vbmeta_digest(const AvbSlotVerifyData& verify_data,
219                                                    const androidboot_vbmeta& vbmeta_prop) {
220    size_t total_size = 0;
221    Hasher hasher;
222    for (size_t n = 0; n < verify_data.num_vbmeta_images; n++) {
223        hasher.update(verify_data.vbmeta_images[n].vbmeta_data,
224                      verify_data.vbmeta_images[n].vbmeta_size);
225        total_size += verify_data.vbmeta_images[n].vbmeta_size;
226    }
227
228    bool matched = (memcmp(hasher.finalize(), vbmeta_prop.digest, Hasher::DIGEST_SIZE) == 0);
229
230    return std::make_pair(total_size, matched);
231}
232
233static bool verify_vbmeta_images(const AvbSlotVerifyData& verify_data,
234                                 const androidboot_vbmeta& vbmeta_prop) {
235    if (verify_data.num_vbmeta_images == 0) {
236        LERROR << "No vbmeta images";
237        return false;
238    }
239
240    size_t total_size = 0;
241    bool digest_matched = false;
242
243    if (vbmeta_prop.hash_alg == kSHA256) {
244        std::tie(total_size, digest_matched) =
245            verify_vbmeta_digest<SHA256Hasher>(verify_data, vbmeta_prop);
246    } else if (vbmeta_prop.hash_alg == kSHA512) {
247        std::tie(total_size, digest_matched) =
248            verify_vbmeta_digest<SHA512Hasher>(verify_data, vbmeta_prop);
249    }
250
251    if (total_size != vbmeta_prop.vbmeta_size) {
252        LERROR << "total vbmeta size mismatch: " << total_size
253               << " (expected: " << vbmeta_prop.vbmeta_size << ")";
254        return false;
255    }
256
257    if (!digest_matched) {
258        LERROR << "vbmeta digest mismatch";
259        return false;
260    }
261
262    return true;
263}
264
265static bool hashtree_load_verity_table(struct dm_ioctl* io, const std::string& dm_device_name,
266                                       int fd, const std::string& blk_device,
267                                       const AvbHashtreeDescriptor& hashtree_desc,
268                                       const std::string& salt, const std::string& root_digest) {
269    fs_mgr_verity_ioctl_init(io, dm_device_name, DM_STATUS_TABLE_FLAG);
270
271    // The buffer consists of [dm_ioctl][dm_target_spec][verity_params].
272    char* buffer = (char*)io;
273
274    // Builds the dm_target_spec arguments.
275    struct dm_target_spec* dm_target = (struct dm_target_spec*)&buffer[sizeof(struct dm_ioctl)];
276    io->target_count = 1;
277    dm_target->status = 0;
278    dm_target->sector_start = 0;
279    dm_target->length = hashtree_desc.image_size / 512;
280    strcpy(dm_target->target_type, "verity");
281
282    // Builds the verity params.
283    char* verity_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
284    size_t bufsize = DM_BUF_SIZE - (verity_params - buffer);
285
286    int res = 0;
287    if (hashtree_desc.fec_size > 0) {
288        res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_FEC_FORMAT,
289                       VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(),
290                                           salt.c_str()),
291                       VERITY_TABLE_OPT_FEC_PARAMS(hashtree_desc, blk_device.c_str()));
292    } else {
293        res = snprintf(verity_params, bufsize, VERITY_TABLE_FORMAT VERITY_TABLE_OPT_DEFAULT_FORMAT,
294                       VERITY_TABLE_PARAMS(hashtree_desc, blk_device.c_str(), root_digest.c_str(),
295                                           salt.c_str()),
296                       VERITY_TABLE_OPT_DEFAULT_PARAMS);
297    }
298
299    if (res < 0 || (size_t)res >= bufsize) {
300        LERROR << "Error building verity table; insufficient buffer size?";
301        return false;
302    }
303
304    LINFO << "Loading verity table: '" << verity_params << "'";
305
306    // Sets ext target boundary.
307    verity_params += strlen(verity_params) + 1;
308    verity_params = (char*)(((unsigned long)verity_params + 7) & ~7);
309    dm_target->next = verity_params - buffer;
310
311    // Sends the ioctl to load the verity table.
312    if (ioctl(fd, DM_TABLE_LOAD, io)) {
313        PERROR << "Error loading verity table";
314        return false;
315    }
316
317    return true;
318}
319
320static bool hashtree_dm_verity_setup(struct fstab_rec* fstab_entry,
321                                     const AvbHashtreeDescriptor& hashtree_desc,
322                                     const std::string& salt, const std::string& root_digest) {
323    // Gets the device mapper fd.
324    android::base::unique_fd fd(open("/dev/device-mapper", O_RDWR));
325    if (fd < 0) {
326        PERROR << "Error opening device mapper";
327        return false;
328    }
329
330    // Creates the device.
331    alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
332    struct dm_ioctl* io = (struct dm_ioctl*)buffer;
333    const std::string mount_point(basename(fstab_entry->mount_point));
334    if (!fs_mgr_create_verity_device(io, mount_point, fd)) {
335        LERROR << "Couldn't create verity device!";
336        return false;
337    }
338
339    // Gets the name of the device file.
340    std::string verity_blk_name;
341    if (!fs_mgr_get_verity_device_name(io, mount_point, fd, &verity_blk_name)) {
342        LERROR << "Couldn't get verity device number!";
343        return false;
344    }
345
346    // Loads the verity mapping table.
347    if (!hashtree_load_verity_table(io, mount_point, fd, std::string(fstab_entry->blk_device),
348                                    hashtree_desc, salt, root_digest)) {
349        LERROR << "Couldn't load verity table!";
350        return false;
351    }
352
353    // Activates the device.
354    if (!fs_mgr_resume_verity_table(io, mount_point, fd)) {
355        return false;
356    }
357
358    // Marks the underlying block device as read-only.
359    fs_mgr_set_blk_ro(fstab_entry->blk_device);
360
361    // TODO(bowgotsai): support verified all partition at boot.
362    // Updates fstab_rec->blk_device to verity device name.
363    free(fstab_entry->blk_device);
364    fstab_entry->blk_device = strdup(verity_blk_name.c_str());
365
366    // Makes sure we've set everything up properly.
367    if (fs_mgr_test_access(verity_blk_name.c_str()) < 0) {
368        return false;
369    }
370
371    return true;
372}
373
374static bool get_hashtree_descriptor(const std::string& partition_name,
375                                    const AvbSlotVerifyData& verify_data,
376                                    AvbHashtreeDescriptor* out_hashtree_desc, std::string* out_salt,
377                                    std::string* out_digest) {
378    bool found = false;
379    const uint8_t* desc_partition_name;
380
381    for (size_t i = 0; i < verify_data.num_vbmeta_images && !found; i++) {
382        // Get descriptors from vbmeta_images[i].
383        size_t num_descriptors;
384        std::unique_ptr<const AvbDescriptor* [], decltype(&avb_free)> descriptors(
385            avb_descriptor_get_all(verify_data.vbmeta_images[i].vbmeta_data,
386                                   verify_data.vbmeta_images[i].vbmeta_size, &num_descriptors),
387            avb_free);
388
389        if (!descriptors || num_descriptors < 1) {
390            continue;
391        }
392
393        // Ensures that hashtree descriptor is in /vbmeta or /boot or in
394        // the same partition for verity setup.
395        std::string vbmeta_partition_name(verify_data.vbmeta_images[i].partition_name);
396        if (vbmeta_partition_name != "vbmeta" &&
397            vbmeta_partition_name != "boot" &&  // for legacy device to append top-level vbmeta
398            vbmeta_partition_name != partition_name) {
399            LWARNING << "Skip vbmeta image at " << verify_data.vbmeta_images[i].partition_name
400                     << " for partition: " << partition_name.c_str();
401            continue;
402        }
403
404        for (size_t j = 0; j < num_descriptors && !found; j++) {
405            AvbDescriptor desc;
406            if (!avb_descriptor_validate_and_byteswap(descriptors[j], &desc)) {
407                LWARNING << "Descriptor[" << j << "] is invalid";
408                continue;
409            }
410            if (desc.tag == AVB_DESCRIPTOR_TAG_HASHTREE) {
411                desc_partition_name =
412                    (const uint8_t*)descriptors[j] + sizeof(AvbHashtreeDescriptor);
413                if (!avb_hashtree_descriptor_validate_and_byteswap(
414                        (AvbHashtreeDescriptor*)descriptors[j], out_hashtree_desc)) {
415                    continue;
416                }
417                if (out_hashtree_desc->partition_name_len != partition_name.length()) {
418                    continue;
419                }
420                // Notes that desc_partition_name is not NUL-terminated.
421                std::string hashtree_partition_name((const char*)desc_partition_name,
422                                                    out_hashtree_desc->partition_name_len);
423                if (hashtree_partition_name == partition_name) {
424                    found = true;
425                }
426            }
427        }
428    }
429
430    if (!found) {
431        LERROR << "Partition descriptor not found: " << partition_name.c_str();
432        return false;
433    }
434
435    const uint8_t* desc_salt = desc_partition_name + out_hashtree_desc->partition_name_len;
436    *out_salt = bytes_to_hex(desc_salt, out_hashtree_desc->salt_len);
437
438    const uint8_t* desc_digest = desc_salt + out_hashtree_desc->salt_len;
439    *out_digest = bytes_to_hex(desc_digest, out_hashtree_desc->root_digest_len);
440
441    return true;
442}
443
444static bool init_is_avb_used() {
445    // When AVB is used, boot loader should set androidboot.vbmeta.{hash_alg,
446    // size, digest} in kernel cmdline or in device tree. They will then be
447    // imported by init process to system properties: ro.boot.vbmeta.{hash_alg, size, digest}.
448    //
449    // In case of early mount, init properties are not initialized, so we also
450    // ensure we look into kernel command line and device tree if the property is
451    // not found
452    //
453    // Checks hash_alg as an indicator for whether AVB is used.
454    // We don't have to parse and check all of them here. The check will
455    // be done in fs_mgr_load_vbmeta_images() and FS_MGR_SETUP_AVB_FAIL will
456    // be returned when there is an error.
457
458    std::string hash_alg;
459    if (!fs_mgr_get_boot_config("vbmeta.hash_alg", &hash_alg)) {
460        return false;
461    }
462    if (hash_alg == "sha256" || hash_alg == "sha512") {
463        return true;
464    }
465    return false;
466}
467
468bool fs_mgr_is_avb_used() {
469    static bool result = init_is_avb_used();
470    return result;
471}
472
473int fs_mgr_load_vbmeta_images(struct fstab* fstab) {
474    FS_MGR_CHECK(fstab != nullptr);
475
476    // Gets the expected hash value of vbmeta images from
477    // kernel cmdline.
478    if (!load_vbmeta_prop(&fs_mgr_vbmeta_prop)) {
479        return FS_MGR_SETUP_AVB_FAIL;
480    }
481
482    fs_mgr_avb_ops = fs_mgr_dummy_avb_ops_new(fstab);
483    if (fs_mgr_avb_ops == nullptr) {
484        LERROR << "Failed to allocate dummy avb_ops";
485        return FS_MGR_SETUP_AVB_FAIL;
486    }
487
488    // Invokes avb_slot_verify() to load and verify all vbmeta images.
489    // Sets requested_partitions to nullptr as it's to copy the contents
490    // of HASH partitions into fs_mgr_avb_verify_data, which is not required as
491    // fs_mgr only deals with HASHTREE partitions.
492    const char* requested_partitions[] = {nullptr};
493    std::string ab_suffix = fs_mgr_get_slot_suffix();
494
495    AvbSlotVerifyResult verify_result =
496        avb_slot_verify(fs_mgr_avb_ops, requested_partitions, ab_suffix.c_str(),
497                        fs_mgr_vbmeta_prop.allow_verification_error, &fs_mgr_avb_verify_data);
498
499    // Only allow two verify results:
500    //   - AVB_SLOT_VERIFY_RESULT_OK.
501    //   - AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION (for UNLOCKED state).
502    if (verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION) {
503        if (!fs_mgr_vbmeta_prop.allow_verification_error) {
504            LERROR << "ERROR_VERIFICATION isn't allowed";
505            goto fail;
506        }
507    } else if (verify_result != AVB_SLOT_VERIFY_RESULT_OK) {
508        LERROR << "avb_slot_verify failed, result: " << verify_result;
509        goto fail;
510    }
511
512    // Verifies vbmeta images against the digest passed from bootloader.
513    if (!verify_vbmeta_images(*fs_mgr_avb_verify_data, fs_mgr_vbmeta_prop)) {
514        LERROR << "verify_vbmeta_images failed";
515        goto fail;
516    } else {
517        // Checks whether FLAGS_HASHTREE_DISABLED is set.
518        AvbVBMetaImageHeader vbmeta_header;
519        avb_vbmeta_image_header_to_host_byte_order(
520            (AvbVBMetaImageHeader*)fs_mgr_avb_verify_data->vbmeta_images[0].vbmeta_data,
521            &vbmeta_header);
522
523        bool hashtree_disabled =
524            ((AvbVBMetaImageFlags)vbmeta_header.flags & AVB_VBMETA_IMAGE_FLAGS_HASHTREE_DISABLED);
525        if (hashtree_disabled) {
526            return FS_MGR_SETUP_AVB_HASHTREE_DISABLED;
527        }
528    }
529
530    if (verify_result == AVB_SLOT_VERIFY_RESULT_OK) {
531        return FS_MGR_SETUP_AVB_SUCCESS;
532    }
533
534fail:
535    fs_mgr_unload_vbmeta_images();
536    return FS_MGR_SETUP_AVB_FAIL;
537}
538
539void fs_mgr_unload_vbmeta_images() {
540    if (fs_mgr_avb_verify_data != nullptr) {
541        avb_slot_verify_data_free(fs_mgr_avb_verify_data);
542    }
543
544    if (fs_mgr_avb_ops != nullptr) {
545        fs_mgr_dummy_avb_ops_free(fs_mgr_avb_ops);
546    }
547}
548
549int fs_mgr_setup_avb(struct fstab_rec* fstab_entry) {
550    if (!fstab_entry || !fs_mgr_avb_verify_data || fs_mgr_avb_verify_data->num_vbmeta_images < 1) {
551        return FS_MGR_SETUP_AVB_FAIL;
552    }
553
554    std::string partition_name(basename(fstab_entry->mount_point));
555    if (!avb_validate_utf8((const uint8_t*)partition_name.c_str(), partition_name.length())) {
556        LERROR << "Partition name: " << partition_name.c_str() << " is not valid UTF-8.";
557        return FS_MGR_SETUP_AVB_FAIL;
558    }
559
560    AvbHashtreeDescriptor hashtree_descriptor;
561    std::string salt;
562    std::string root_digest;
563    if (!get_hashtree_descriptor(partition_name, *fs_mgr_avb_verify_data, &hashtree_descriptor,
564                                 &salt, &root_digest)) {
565        return FS_MGR_SETUP_AVB_FAIL;
566    }
567
568    // Converts HASHTREE descriptor to verity_table_params.
569    if (!hashtree_dm_verity_setup(fstab_entry, hashtree_descriptor, salt, root_digest)) {
570        return FS_MGR_SETUP_AVB_FAIL;
571    }
572
573    return FS_MGR_SETUP_AVB_SUCCESS;
574}
575