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