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