• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 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 <inttypes.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <ctype.h>
24 #include <sys/mount.h>
25 #include <sys/stat.h>
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/wait.h>
29 #include <libgen.h>
30 #include <time.h>
31 
32 #include <android-base/file.h>
33 #include <private/android_filesystem_config.h>
34 #include <cutils/properties.h>
35 #include <logwrap/logwrap.h>
36 
37 #include "mincrypt/rsa.h"
38 #include "mincrypt/sha.h"
39 #include "mincrypt/sha256.h"
40 
41 #include "fec/io.h"
42 
43 #include "fs_mgr.h"
44 #include "fs_mgr_priv.h"
45 #include "fs_mgr_priv_verity.h"
46 
47 #define FSTAB_PREFIX "/fstab."
48 
49 #define VERITY_TABLE_RSA_KEY "/verity_key"
50 #define VERITY_TABLE_HASH_IDX 8
51 #define VERITY_TABLE_SALT_IDX 9
52 
53 #define VERITY_TABLE_OPT_RESTART "restart_on_corruption"
54 #define VERITY_TABLE_OPT_LOGGING "ignore_corruption"
55 #define VERITY_TABLE_OPT_IGNZERO "ignore_zero_blocks"
56 
57 #define VERITY_TABLE_OPT_FEC_FORMAT \
58     "use_fec_from_device %s fec_start %" PRIu64 " fec_blocks %" PRIu64 \
59     " fec_roots %u " VERITY_TABLE_OPT_IGNZERO
60 #define VERITY_TABLE_OPT_FEC_ARGS 9
61 
62 #define METADATA_MAGIC 0x01564c54
63 #define METADATA_TAG_MAX_LENGTH 63
64 #define METADATA_EOD "eod"
65 
66 #define VERITY_LASTSIG_TAG "verity_lastsig"
67 
68 #define VERITY_STATE_TAG "verity_state"
69 #define VERITY_STATE_HEADER 0x83c0ae9d
70 #define VERITY_STATE_VERSION 1
71 
72 #define VERITY_KMSG_RESTART "dm-verity device corrupted"
73 #define VERITY_KMSG_BUFSIZE 1024
74 
75 #define __STRINGIFY(x) #x
76 #define STRINGIFY(x) __STRINGIFY(x)
77 
78 struct verity_state {
79     uint32_t header;
80     uint32_t version;
81     int32_t mode;
82 };
83 
84 extern struct fs_info info;
85 
load_key(const char * path)86 static RSAPublicKey *load_key(const char *path)
87 {
88     RSAPublicKey* key = static_cast<RSAPublicKey*>(malloc(sizeof(RSAPublicKey)));
89     if (!key) {
90         ERROR("Can't malloc key\n");
91         return NULL;
92     }
93 
94     FILE* f = fopen(path, "r");
95     if (!f) {
96         ERROR("Can't open '%s'\n", path);
97         free(key);
98         return NULL;
99     }
100 
101     if (!fread(key, sizeof(*key), 1, f)) {
102         ERROR("Could not read key!\n");
103         fclose(f);
104         free(key);
105         return NULL;
106     }
107 
108     if (key->len != RSANUMWORDS) {
109         ERROR("Invalid key length %d\n", key->len);
110         fclose(f);
111         free(key);
112         return NULL;
113     }
114 
115     fclose(f);
116     return key;
117 }
118 
verify_table(const uint8_t * signature,const char * table,uint32_t table_length)119 static int verify_table(const uint8_t *signature, const char *table,
120         uint32_t table_length)
121 {
122     RSAPublicKey *key;
123     uint8_t hash_buf[SHA256_DIGEST_SIZE];
124     int retval = -1;
125 
126     // Hash the table
127     SHA256_hash((uint8_t*)table, table_length, hash_buf);
128 
129     // Now get the public key from the keyfile
130     key = load_key(VERITY_TABLE_RSA_KEY);
131     if (!key) {
132         ERROR("Couldn't load verity keys\n");
133         goto out;
134     }
135 
136     // verify the result
137     if (!RSA_verify(key,
138                     signature,
139                     RSANUMBYTES,
140                     (uint8_t*) hash_buf,
141                     SHA256_DIGEST_SIZE)) {
142         ERROR("Couldn't verify table\n");
143         goto out;
144     }
145 
146     retval = 0;
147 
148 out:
149     free(key);
150     return retval;
151 }
152 
verify_verity_signature(const struct fec_verity_metadata & verity)153 static int verify_verity_signature(const struct fec_verity_metadata& verity)
154 {
155     if (verify_table(verity.signature, verity.table,
156             verity.table_length) == 0 ||
157         verify_table(verity.ecc_signature, verity.table,
158             verity.table_length) == 0) {
159         return 0;
160     }
161 
162     return -1;
163 }
164 
invalidate_table(char * table,size_t table_length)165 static int invalidate_table(char *table, size_t table_length)
166 {
167     size_t n = 0;
168     size_t idx = 0;
169     size_t cleared = 0;
170 
171     while (n < table_length) {
172         if (table[n++] == ' ') {
173             ++idx;
174         }
175 
176         if (idx != VERITY_TABLE_HASH_IDX && idx != VERITY_TABLE_SALT_IDX) {
177             continue;
178         }
179 
180         while (n < table_length && table[n] != ' ') {
181             table[n++] = '0';
182         }
183 
184         if (++cleared == 2) {
185             return 0;
186         }
187     }
188 
189     return -1;
190 }
191 
verity_ioctl_init(struct dm_ioctl * io,char * name,unsigned flags)192 static void verity_ioctl_init(struct dm_ioctl *io, char *name, unsigned flags)
193 {
194     memset(io, 0, DM_BUF_SIZE);
195     io->data_size = DM_BUF_SIZE;
196     io->data_start = sizeof(struct dm_ioctl);
197     io->version[0] = 4;
198     io->version[1] = 0;
199     io->version[2] = 0;
200     io->flags = flags | DM_READONLY_FLAG;
201     if (name) {
202         strlcpy(io->name, name, sizeof(io->name));
203     }
204 }
205 
create_verity_device(struct dm_ioctl * io,char * name,int fd)206 static int create_verity_device(struct dm_ioctl *io, char *name, int fd)
207 {
208     verity_ioctl_init(io, name, 1);
209     if (ioctl(fd, DM_DEV_CREATE, io)) {
210         ERROR("Error creating device mapping (%s)", strerror(errno));
211         return -1;
212     }
213     return 0;
214 }
215 
get_verity_device_name(struct dm_ioctl * io,char * name,int fd,char ** dev_name)216 static int get_verity_device_name(struct dm_ioctl *io, char *name, int fd, char **dev_name)
217 {
218     verity_ioctl_init(io, name, 0);
219     if (ioctl(fd, DM_DEV_STATUS, io)) {
220         ERROR("Error fetching verity device number (%s)", strerror(errno));
221         return -1;
222     }
223     int dev_num = (io->dev & 0xff) | ((io->dev >> 12) & 0xfff00);
224     if (asprintf(dev_name, "/dev/block/dm-%u", dev_num) < 0) {
225         ERROR("Error getting verity block device name (%s)", strerror(errno));
226         return -1;
227     }
228     return 0;
229 }
230 
231 struct verity_table_params {
232     const char *table;
233     int mode;
234     struct fec_ecc_metadata ecc;
235     const char *ecc_dev;
236 };
237 
238 typedef bool (*format_verity_table_func)(char *buf, const size_t bufsize,
239         const struct verity_table_params *params);
240 
format_verity_table(char * buf,const size_t bufsize,const struct verity_table_params * params)241 static bool format_verity_table(char *buf, const size_t bufsize,
242         const struct verity_table_params *params)
243 {
244     const char *mode_flag = NULL;
245     int res = -1;
246 
247     if (params->mode == VERITY_MODE_RESTART) {
248         mode_flag = VERITY_TABLE_OPT_RESTART;
249     } else if (params->mode == VERITY_MODE_LOGGING) {
250         mode_flag = VERITY_TABLE_OPT_LOGGING;
251     }
252 
253     if (params->ecc.valid) {
254         if (mode_flag) {
255             res = snprintf(buf, bufsize,
256                     "%s %u %s " VERITY_TABLE_OPT_FEC_FORMAT,
257                     params->table, 1 + VERITY_TABLE_OPT_FEC_ARGS, mode_flag, params->ecc_dev,
258                     params->ecc.start / FEC_BLOCKSIZE, params->ecc.blocks, params->ecc.roots);
259         } else {
260             res = snprintf(buf, bufsize,
261                     "%s %u " VERITY_TABLE_OPT_FEC_FORMAT,
262                     params->table, VERITY_TABLE_OPT_FEC_ARGS, params->ecc_dev,
263                     params->ecc.start / FEC_BLOCKSIZE, params->ecc.blocks, params->ecc.roots);
264         }
265     } else if (mode_flag) {
266         res = snprintf(buf, bufsize, "%s 2 " VERITY_TABLE_OPT_IGNZERO " %s", params->table,
267                     mode_flag);
268     } else {
269         res = snprintf(buf, bufsize, "%s 1 " VERITY_TABLE_OPT_IGNZERO, params->table);
270     }
271 
272     if (res < 0 || (size_t)res >= bufsize) {
273         ERROR("Error building verity table; insufficient buffer size?\n");
274         return false;
275     }
276 
277     return true;
278 }
279 
format_legacy_verity_table(char * buf,const size_t bufsize,const struct verity_table_params * params)280 static bool format_legacy_verity_table(char *buf, const size_t bufsize,
281         const struct verity_table_params *params)
282 {
283     int res;
284 
285     if (params->mode == VERITY_MODE_EIO) {
286         res = strlcpy(buf, params->table, bufsize);
287     } else {
288         res = snprintf(buf, bufsize, "%s %d", params->table, params->mode);
289     }
290 
291     if (res < 0 || (size_t)res >= bufsize) {
292         ERROR("Error building verity table; insufficient buffer size?\n");
293         return false;
294     }
295 
296     return true;
297 }
298 
load_verity_table(struct dm_ioctl * io,char * name,uint64_t device_size,int fd,const struct verity_table_params * params,format_verity_table_func format)299 static int load_verity_table(struct dm_ioctl *io, char *name, uint64_t device_size, int fd,
300         const struct verity_table_params *params, format_verity_table_func format)
301 {
302     char *verity_params;
303     char *buffer = (char*) io;
304     size_t bufsize;
305 
306     verity_ioctl_init(io, name, DM_STATUS_TABLE_FLAG);
307 
308     struct dm_target_spec *tgt = (struct dm_target_spec *) &buffer[sizeof(struct dm_ioctl)];
309 
310     // set tgt arguments
311     io->target_count = 1;
312     tgt->status = 0;
313     tgt->sector_start = 0;
314     tgt->length = device_size / 512;
315     strcpy(tgt->target_type, "verity");
316 
317     // build the verity params
318     verity_params = buffer + sizeof(struct dm_ioctl) + sizeof(struct dm_target_spec);
319     bufsize = DM_BUF_SIZE - (verity_params - buffer);
320 
321     if (!format(verity_params, bufsize, params)) {
322         ERROR("Failed to format verity parameters\n");
323         return -1;
324     }
325 
326     INFO("loading verity table: '%s'", verity_params);
327 
328     // set next target boundary
329     verity_params += strlen(verity_params) + 1;
330     verity_params = (char*)(((unsigned long)verity_params + 7) & ~8);
331     tgt->next = verity_params - buffer;
332 
333     // send the ioctl to load the verity table
334     if (ioctl(fd, DM_TABLE_LOAD, io)) {
335         ERROR("Error loading verity table (%s)\n", strerror(errno));
336         return -1;
337     }
338 
339     return 0;
340 }
341 
resume_verity_table(struct dm_ioctl * io,char * name,int fd)342 static int resume_verity_table(struct dm_ioctl *io, char *name, int fd)
343 {
344     verity_ioctl_init(io, name, 0);
345     if (ioctl(fd, DM_DEV_SUSPEND, io)) {
346         ERROR("Error activating verity device (%s)", strerror(errno));
347         return -1;
348     }
349     return 0;
350 }
351 
test_access(char * device)352 static int test_access(char *device) {
353     int tries = 25;
354     while (tries--) {
355         if (!access(device, F_OK) || errno != ENOENT) {
356             return 0;
357         }
358         usleep(40 * 1000);
359     }
360     return -1;
361 }
362 
check_verity_restart(const char * fname)363 static int check_verity_restart(const char *fname)
364 {
365     char buffer[VERITY_KMSG_BUFSIZE + 1];
366     int fd;
367     int rc = 0;
368     ssize_t size;
369     struct stat s;
370 
371     fd = TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_CLOEXEC));
372 
373     if (fd == -1) {
374         if (errno != ENOENT) {
375             ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
376         }
377         goto out;
378     }
379 
380     if (fstat(fd, &s) == -1) {
381         ERROR("Failed to fstat %s (%s)\n", fname, strerror(errno));
382         goto out;
383     }
384 
385     size = VERITY_KMSG_BUFSIZE;
386 
387     if (size > s.st_size) {
388         size = s.st_size;
389     }
390 
391     if (lseek(fd, s.st_size - size, SEEK_SET) == -1) {
392         ERROR("Failed to lseek %jd %s (%s)\n", (intmax_t)(s.st_size - size), fname,
393             strerror(errno));
394         goto out;
395     }
396 
397     if (!android::base::ReadFully(fd, buffer, size)) {
398         ERROR("Failed to read %zd bytes from %s (%s)\n", size, fname,
399             strerror(errno));
400         goto out;
401     }
402 
403     buffer[size] = '\0';
404 
405     if (strstr(buffer, VERITY_KMSG_RESTART) != NULL) {
406         rc = 1;
407     }
408 
409 out:
410     if (fd != -1) {
411         close(fd);
412     }
413 
414     return rc;
415 }
416 
was_verity_restart()417 static int was_verity_restart()
418 {
419     static const char *files[] = {
420         "/sys/fs/pstore/console-ramoops",
421         "/proc/last_kmsg",
422         NULL
423     };
424     int i;
425 
426     for (i = 0; files[i]; ++i) {
427         if (check_verity_restart(files[i])) {
428             return 1;
429         }
430     }
431 
432     return 0;
433 }
434 
metadata_add(FILE * fp,long start,const char * tag,unsigned int length,off64_t * offset)435 static int metadata_add(FILE *fp, long start, const char *tag,
436         unsigned int length, off64_t *offset)
437 {
438     if (fseek(fp, start, SEEK_SET) < 0 ||
439         fprintf(fp, "%s %u\n", tag, length) < 0) {
440         return -1;
441     }
442 
443     *offset = ftell(fp);
444 
445     if (fseek(fp, length, SEEK_CUR) < 0 ||
446         fprintf(fp, METADATA_EOD " 0\n") < 0) {
447         return -1;
448     }
449 
450     return 0;
451 }
452 
metadata_find(const char * fname,const char * stag,unsigned int slength,off64_t * offset)453 static int metadata_find(const char *fname, const char *stag,
454         unsigned int slength, off64_t *offset)
455 {
456     FILE *fp = NULL;
457     char tag[METADATA_TAG_MAX_LENGTH + 1];
458     int rc = -1;
459     int n;
460     long start = 0x4000; /* skip cryptfs metadata area */
461     uint32_t magic;
462     unsigned int length = 0;
463 
464     if (!fname) {
465         return -1;
466     }
467 
468     fp = fopen(fname, "r+");
469 
470     if (!fp) {
471         ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
472         goto out;
473     }
474 
475     /* check magic */
476     if (fseek(fp, start, SEEK_SET) < 0 ||
477         fread(&magic, sizeof(magic), 1, fp) != 1) {
478         ERROR("Failed to read magic from %s (%s)\n", fname, strerror(errno));
479         goto out;
480     }
481 
482     if (magic != METADATA_MAGIC) {
483         magic = METADATA_MAGIC;
484 
485         if (fseek(fp, start, SEEK_SET) < 0 ||
486             fwrite(&magic, sizeof(magic), 1, fp) != 1) {
487             ERROR("Failed to write magic to %s (%s)\n", fname, strerror(errno));
488             goto out;
489         }
490 
491         rc = metadata_add(fp, start + sizeof(magic), stag, slength, offset);
492         if (rc < 0) {
493             ERROR("Failed to add metadata to %s: %s\n", fname, strerror(errno));
494         }
495 
496         goto out;
497     }
498 
499     start += sizeof(magic);
500 
501     while (1) {
502         n = fscanf(fp, "%" STRINGIFY(METADATA_TAG_MAX_LENGTH) "s %u\n",
503                 tag, &length);
504 
505         if (n == 2 && strcmp(tag, METADATA_EOD)) {
506             /* found a tag */
507             start = ftell(fp);
508 
509             if (!strcmp(tag, stag) && length == slength) {
510                 *offset = start;
511                 rc = 0;
512                 goto out;
513             }
514 
515             start += length;
516 
517             if (fseek(fp, length, SEEK_CUR) < 0) {
518                 ERROR("Failed to seek %s (%s)\n", fname, strerror(errno));
519                 goto out;
520             }
521         } else {
522             rc = metadata_add(fp, start, stag, slength, offset);
523             if (rc < 0) {
524                 ERROR("Failed to write metadata to %s: %s\n", fname,
525                     strerror(errno));
526             }
527             goto out;
528         }
529    }
530 
531 out:
532     if (fp) {
533         fflush(fp);
534         fclose(fp);
535     }
536 
537     return rc;
538 }
539 
write_verity_state(const char * fname,off64_t offset,int32_t mode)540 static int write_verity_state(const char *fname, off64_t offset, int32_t mode)
541 {
542     int fd;
543     int rc = -1;
544     struct verity_state s = { VERITY_STATE_HEADER, VERITY_STATE_VERSION, mode };
545 
546     fd = TEMP_FAILURE_RETRY(open(fname, O_WRONLY | O_SYNC | O_CLOEXEC));
547 
548     if (fd == -1) {
549         ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
550         goto out;
551     }
552 
553     if (TEMP_FAILURE_RETRY(pwrite64(fd, &s, sizeof(s), offset)) != sizeof(s)) {
554         ERROR("Failed to write %zu bytes to %s to offset %" PRIu64 " (%s)\n",
555             sizeof(s), fname, offset, strerror(errno));
556         goto out;
557     }
558 
559     rc = 0;
560 
561 out:
562     if (fd != -1) {
563         close(fd);
564     }
565 
566     return rc;
567 }
568 
read_verity_state(const char * fname,off64_t offset,int * mode)569 static int read_verity_state(const char *fname, off64_t offset, int *mode)
570 {
571     int fd = -1;
572     int rc = -1;
573     struct verity_state s;
574 
575     fd = TEMP_FAILURE_RETRY(open(fname, O_RDONLY | O_CLOEXEC));
576 
577     if (fd == -1) {
578         ERROR("Failed to open %s (%s)\n", fname, strerror(errno));
579         goto out;
580     }
581 
582     if (TEMP_FAILURE_RETRY(pread64(fd, &s, sizeof(s), offset)) != sizeof(s)) {
583         ERROR("Failed to read %zu bytes from %s offset %" PRIu64 " (%s)\n",
584             sizeof(s), fname, offset, strerror(errno));
585         goto out;
586     }
587 
588     if (s.header != VERITY_STATE_HEADER) {
589         /* space allocated, but no state written. write default state */
590         *mode = VERITY_MODE_DEFAULT;
591         rc = write_verity_state(fname, offset, *mode);
592         goto out;
593     }
594 
595     if (s.version != VERITY_STATE_VERSION) {
596         ERROR("Unsupported verity state version (%u)\n", s.version);
597         goto out;
598     }
599 
600     if (s.mode < VERITY_MODE_EIO ||
601         s.mode > VERITY_MODE_LAST) {
602         ERROR("Unsupported verity mode (%u)\n", s.mode);
603         goto out;
604     }
605 
606     *mode = s.mode;
607     rc = 0;
608 
609 out:
610     if (fd != -1) {
611         close(fd);
612     }
613 
614     return rc;
615 }
616 
compare_last_signature(struct fstab_rec * fstab,int * match)617 static int compare_last_signature(struct fstab_rec *fstab, int *match)
618 {
619     char tag[METADATA_TAG_MAX_LENGTH + 1];
620     int fd = -1;
621     int rc = -1;
622     off64_t offset = 0;
623     struct fec_handle *f = NULL;
624     struct fec_verity_metadata verity;
625     uint8_t curr[SHA256_DIGEST_SIZE];
626     uint8_t prev[SHA256_DIGEST_SIZE];
627 
628     *match = 1;
629 
630     if (fec_open(&f, fstab->blk_device, O_RDONLY, FEC_VERITY_DISABLE,
631             FEC_DEFAULT_ROOTS) == -1) {
632         ERROR("Failed to open '%s' (%s)\n", fstab->blk_device,
633             strerror(errno));
634         return rc;
635     }
636 
637     // read verity metadata
638     if (fec_verity_get_metadata(f, &verity) == -1) {
639         ERROR("Failed to get verity metadata '%s' (%s)\n", fstab->blk_device,
640             strerror(errno));
641         goto out;
642     }
643 
644     SHA256_hash(verity.signature, RSANUMBYTES, curr);
645 
646     if (snprintf(tag, sizeof(tag), VERITY_LASTSIG_TAG "_%s",
647             basename(fstab->mount_point)) >= (int)sizeof(tag)) {
648         ERROR("Metadata tag name too long for %s\n", fstab->mount_point);
649         goto out;
650     }
651 
652     if (metadata_find(fstab->verity_loc, tag, SHA256_DIGEST_SIZE,
653             &offset) < 0) {
654         goto out;
655     }
656 
657     fd = TEMP_FAILURE_RETRY(open(fstab->verity_loc, O_RDWR | O_SYNC | O_CLOEXEC));
658 
659     if (fd == -1) {
660         ERROR("Failed to open %s: %s\n", fstab->verity_loc, strerror(errno));
661         goto out;
662     }
663 
664     if (TEMP_FAILURE_RETRY(pread64(fd, prev, sizeof(prev),
665             offset)) != sizeof(prev)) {
666         ERROR("Failed to read %zu bytes from %s offset %" PRIu64 " (%s)\n",
667             sizeof(prev), fstab->verity_loc, offset, strerror(errno));
668         goto out;
669     }
670 
671     *match = !memcmp(curr, prev, SHA256_DIGEST_SIZE);
672 
673     if (!*match) {
674         /* update current signature hash */
675         if (TEMP_FAILURE_RETRY(pwrite64(fd, curr, sizeof(curr),
676                 offset)) != sizeof(curr)) {
677             ERROR("Failed to write %zu bytes to %s offset %" PRIu64 " (%s)\n",
678                 sizeof(curr), fstab->verity_loc, offset, strerror(errno));
679             goto out;
680         }
681     }
682 
683     rc = 0;
684 
685 out:
686     fec_close(f);
687     return rc;
688 }
689 
get_verity_state_offset(struct fstab_rec * fstab,off64_t * offset)690 static int get_verity_state_offset(struct fstab_rec *fstab, off64_t *offset)
691 {
692     char tag[METADATA_TAG_MAX_LENGTH + 1];
693 
694     if (snprintf(tag, sizeof(tag), VERITY_STATE_TAG "_%s",
695             basename(fstab->mount_point)) >= (int)sizeof(tag)) {
696         ERROR("Metadata tag name too long for %s\n", fstab->mount_point);
697         return -1;
698     }
699 
700     return metadata_find(fstab->verity_loc, tag, sizeof(struct verity_state),
701                 offset);
702 }
703 
load_verity_state(struct fstab_rec * fstab,int * mode)704 static int load_verity_state(struct fstab_rec *fstab, int *mode)
705 {
706     char propbuf[PROPERTY_VALUE_MAX];
707     int match = 0;
708     off64_t offset = 0;
709 
710     /* unless otherwise specified, use EIO mode */
711     *mode = VERITY_MODE_EIO;
712 
713     /* use the kernel parameter if set */
714     property_get("ro.boot.veritymode", propbuf, "");
715 
716     if (*propbuf != '\0') {
717         if (!strcmp(propbuf, "enforcing")) {
718             *mode = VERITY_MODE_DEFAULT;
719         }
720         return 0;
721     }
722 
723     if (get_verity_state_offset(fstab, &offset) < 0) {
724         /* fall back to stateless behavior */
725         return 0;
726     }
727 
728     if (was_verity_restart()) {
729         /* device was restarted after dm-verity detected a corrupted
730          * block, so use EIO mode */
731         return write_verity_state(fstab->verity_loc, offset, *mode);
732     }
733 
734     if (!compare_last_signature(fstab, &match) && !match) {
735         /* partition has been reflashed, reset dm-verity state */
736         *mode = VERITY_MODE_DEFAULT;
737         return write_verity_state(fstab->verity_loc, offset, *mode);
738     }
739 
740     return read_verity_state(fstab->verity_loc, offset, mode);
741 }
742 
fs_mgr_load_verity_state(int * mode)743 int fs_mgr_load_verity_state(int *mode)
744 {
745     char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
746     char propbuf[PROPERTY_VALUE_MAX];
747     int rc = -1;
748     int i;
749     int current;
750     struct fstab *fstab = NULL;
751 
752     /* return the default mode, unless any of the verified partitions are in
753      * logging mode, in which case return that */
754     *mode = VERITY_MODE_DEFAULT;
755 
756     property_get("ro.hardware", propbuf, "");
757     snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
758 
759     fstab = fs_mgr_read_fstab(fstab_filename);
760 
761     if (!fstab) {
762         ERROR("Failed to read %s\n", fstab_filename);
763         goto out;
764     }
765 
766     for (i = 0; i < fstab->num_entries; i++) {
767         if (!fs_mgr_is_verified(&fstab->recs[i])) {
768             continue;
769         }
770 
771         rc = load_verity_state(&fstab->recs[i], &current);
772         if (rc < 0) {
773             continue;
774         }
775 
776         if (current != VERITY_MODE_DEFAULT) {
777             *mode = current;
778             break;
779         }
780     }
781 
782     rc = 0;
783 
784 out:
785     if (fstab) {
786         fs_mgr_free_fstab(fstab);
787     }
788 
789     return rc;
790 }
791 
fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback)792 int fs_mgr_update_verity_state(fs_mgr_verity_state_callback callback)
793 {
794     alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
795     char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
796     char *mount_point;
797     char propbuf[PROPERTY_VALUE_MAX];
798     char *status;
799     int fd = -1;
800     int i;
801     int mode;
802     int rc = -1;
803     struct dm_ioctl *io = (struct dm_ioctl *) buffer;
804     struct fstab *fstab = NULL;
805 
806     if (!callback) {
807         return -1;
808     }
809 
810     if (fs_mgr_load_verity_state(&mode) == -1) {
811         return -1;
812     }
813 
814     fd = TEMP_FAILURE_RETRY(open("/dev/device-mapper", O_RDWR | O_CLOEXEC));
815 
816     if (fd == -1) {
817         ERROR("Error opening device mapper (%s)\n", strerror(errno));
818         goto out;
819     }
820 
821     property_get("ro.hardware", propbuf, "");
822     snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
823 
824     fstab = fs_mgr_read_fstab(fstab_filename);
825 
826     if (!fstab) {
827         ERROR("Failed to read %s\n", fstab_filename);
828         goto out;
829     }
830 
831     for (i = 0; i < fstab->num_entries; i++) {
832         if (!fs_mgr_is_verified(&fstab->recs[i])) {
833             continue;
834         }
835 
836         mount_point = basename(fstab->recs[i].mount_point);
837         verity_ioctl_init(io, mount_point, 0);
838 
839         if (ioctl(fd, DM_TABLE_STATUS, io)) {
840             ERROR("Failed to query DM_TABLE_STATUS for %s (%s)\n", mount_point,
841                 strerror(errno));
842             continue;
843         }
844 
845         status = &buffer[io->data_start + sizeof(struct dm_target_spec)];
846 
847         callback(&fstab->recs[i], mount_point, mode, *status);
848     }
849 
850     rc = 0;
851 
852 out:
853     if (fstab) {
854         fs_mgr_free_fstab(fstab);
855     }
856 
857     if (fd) {
858         close(fd);
859     }
860 
861     return rc;
862 }
863 
fs_mgr_setup_verity(struct fstab_rec * fstab)864 int fs_mgr_setup_verity(struct fstab_rec *fstab)
865 {
866     int retval = FS_MGR_SETUP_VERITY_FAIL;
867     int fd = -1;
868     char *invalid_table = NULL;
869     char *verity_blk_name = NULL;
870     struct fec_handle *f = NULL;
871     struct fec_verity_metadata verity;
872     struct verity_table_params params;
873 
874     alignas(dm_ioctl) char buffer[DM_BUF_SIZE];
875     struct dm_ioctl *io = (struct dm_ioctl *) buffer;
876     char *mount_point = basename(fstab->mount_point);
877 
878     if (fec_open(&f, fstab->blk_device, O_RDONLY, FEC_VERITY_DISABLE,
879             FEC_DEFAULT_ROOTS) < 0) {
880         ERROR("Failed to open '%s' (%s)\n", fstab->blk_device,
881             strerror(errno));
882         return retval;
883     }
884 
885     // read verity metadata
886     if (fec_verity_get_metadata(f, &verity) < 0) {
887         ERROR("Failed to get verity metadata '%s' (%s)\n", fstab->blk_device,
888             strerror(errno));
889         goto out;
890     }
891 
892 #ifdef ALLOW_ADBD_DISABLE_VERITY
893     if (verity.disabled) {
894         retval = FS_MGR_SETUP_VERITY_DISABLED;
895         INFO("Attempt to cleanly disable verity - only works in USERDEBUG\n");
896         goto out;
897     }
898 #endif
899 
900     // read ecc metadata
901     if (fec_ecc_get_metadata(f, &params.ecc) < 0) {
902         params.ecc.valid = false;
903     }
904 
905     params.ecc_dev = fstab->blk_device;
906 
907     // get the device mapper fd
908     if ((fd = open("/dev/device-mapper", O_RDWR)) < 0) {
909         ERROR("Error opening device mapper (%s)\n", strerror(errno));
910         goto out;
911     }
912 
913     // create the device
914     if (create_verity_device(io, mount_point, fd) < 0) {
915         ERROR("Couldn't create verity device!\n");
916         goto out;
917     }
918 
919     // get the name of the device file
920     if (get_verity_device_name(io, mount_point, fd, &verity_blk_name) < 0) {
921         ERROR("Couldn't get verity device number!\n");
922         goto out;
923     }
924 
925     if (load_verity_state(fstab, &params.mode) < 0) {
926         /* if accessing or updating the state failed, switch to the default
927          * safe mode. This makes sure the device won't end up in an endless
928          * restart loop, and no corrupted data will be exposed to userspace
929          * without a warning. */
930         params.mode = VERITY_MODE_EIO;
931     }
932 
933     // verify the signature on the table
934     if (verify_verity_signature(verity) < 0) {
935         if (params.mode == VERITY_MODE_LOGGING) {
936             // the user has been warned, allow mounting without dm-verity
937             retval = FS_MGR_SETUP_VERITY_SUCCESS;
938             goto out;
939         }
940 
941         // invalidate root hash and salt to trigger device-specific recovery
942         invalid_table = strdup(verity.table);
943 
944         if (!invalid_table ||
945                 invalidate_table(invalid_table, verity.table_length) < 0) {
946             goto out;
947         }
948 
949         params.table = invalid_table;
950     } else {
951         params.table = verity.table;
952     }
953 
954     INFO("Enabling dm-verity for %s (mode %d)\n", mount_point, params.mode);
955 
956     // load the verity mapping table
957     if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
958             format_verity_table) == 0) {
959         goto loaded;
960     }
961 
962     if (params.ecc.valid) {
963         // kernel may not support error correction, try without
964         INFO("Disabling error correction for %s\n", mount_point);
965         params.ecc.valid = false;
966 
967         if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
968                 format_verity_table) == 0) {
969             goto loaded;
970         }
971     }
972 
973     // try the legacy format for backwards compatibility
974     if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
975             format_legacy_verity_table) == 0) {
976         goto loaded;
977     }
978 
979     if (params.mode != VERITY_MODE_EIO) {
980         // as a last resort, EIO mode should always be supported
981         INFO("Falling back to EIO mode for %s\n", mount_point);
982         params.mode = VERITY_MODE_EIO;
983 
984         if (load_verity_table(io, mount_point, verity.data_size, fd, &params,
985                 format_legacy_verity_table) == 0) {
986             goto loaded;
987         }
988     }
989 
990     ERROR("Failed to load verity table for %s\n", mount_point);
991     goto out;
992 
993 loaded:
994 
995     // activate the device
996     if (resume_verity_table(io, mount_point, fd) < 0) {
997         goto out;
998     }
999 
1000     // mark the underlying block device as read-only
1001     fs_mgr_set_blk_ro(fstab->blk_device);
1002 
1003     // assign the new verity block device as the block device
1004     free(fstab->blk_device);
1005     fstab->blk_device = verity_blk_name;
1006     verity_blk_name = 0;
1007 
1008     // make sure we've set everything up properly
1009     if (test_access(fstab->blk_device) < 0) {
1010         goto out;
1011     }
1012 
1013     retval = FS_MGR_SETUP_VERITY_SUCCESS;
1014 
1015 out:
1016     if (fd != -1) {
1017         close(fd);
1018     }
1019 
1020     fec_close(f);
1021     free(invalid_table);
1022     free(verity_blk_name);
1023 
1024     return retval;
1025 }
1026