Support init_by_name for verity.
[platform/upstream/cryptsetup.git] / lib / libdevmapper.c
1 /*
2  * libdevmapper - device-mapper backend for cryptsetup
3  *
4  * Copyright (C) 2004, Christophe Saout <christophe@saout.de>
5  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
6  * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * version 2 as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include <stdio.h>
23 #include <dirent.h>
24 #include <errno.h>
25 #include <libdevmapper.h>
26 #include <fcntl.h>
27 #include <linux/fs.h>
28 #include <uuid/uuid.h>
29
30 #include "internal.h"
31
32 #define DM_UUID_LEN             129
33 #define DM_UUID_PREFIX          "CRYPT-"
34 #define DM_UUID_PREFIX_LEN      6
35 #define DM_CRYPT_TARGET         "crypt"
36 #define DM_VERITY_TARGET        "verity"
37 #define RETRY_COUNT             5
38
39 /* Set if dm-crypt version was probed */
40 static int _dm_crypt_checked = 0;
41 static uint32_t _dm_crypt_flags = 0;
42
43 static int _dm_use_count = 0;
44 static struct crypt_device *_context = NULL;
45
46 /* Check if we have DM flag to instruct kernel to force wipe buffers */
47 #if !HAVE_DECL_DM_TASK_SECURE_DATA
48 static int dm_task_secure_data(struct dm_task *dmt) { return 1; }
49 #endif
50
51 /* Compatibility for old device-mapper without udev support */
52 #if HAVE_DECL_DM_UDEV_DISABLE_DISK_RULES_FLAG
53 #define CRYPT_TEMP_UDEV_FLAGS   DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG | \
54                                 DM_UDEV_DISABLE_DISK_RULES_FLAG | \
55                                 DM_UDEV_DISABLE_OTHER_RULES_FLAG
56 #define _dm_task_set_cookie     dm_task_set_cookie
57 #define _dm_udev_wait           dm_udev_wait
58 #else
59 #define CRYPT_TEMP_UDEV_FLAGS   0
60 static int _dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags) { return 0; }
61 static int _dm_udev_wait(uint32_t cookie) { return 0; };
62 #endif
63
64 static int _dm_use_udev(void)
65 {
66 #ifdef USE_UDEV /* cannot be enabled if devmapper is too old */
67         return dm_udev_get_sync_support();
68 #else
69         return 0;
70 #endif
71 }
72
73 __attribute__((format(printf, 4, 5)))
74 static void set_dm_error(int level,
75                          const char *file __attribute__((unused)),
76                          int line __attribute__((unused)),
77                          const char *f, ...)
78 {
79         char *msg = NULL;
80         va_list va;
81
82         va_start(va, f);
83         if (vasprintf(&msg, f, va) > 0) {
84                 if (level < 4) {
85                         log_err(_context, msg);
86                         log_err(_context, "\n");
87                 } else
88                         log_dbg(msg);
89         }
90         free(msg);
91         va_end(va);
92 }
93
94 static int _dm_simple(int task, const char *name, int udev_wait);
95
96 static void _dm_set_crypt_compat(const char *dm_version, unsigned crypt_maj,
97                                  unsigned crypt_min, unsigned crypt_patch)
98 {
99         unsigned dm_maj, dm_min, dm_patch;
100
101         if (sscanf(dm_version, "%u.%u.%u", &dm_maj, &dm_min, &dm_patch) != 3)
102                 dm_maj = dm_min = dm_patch = 0;
103
104         log_dbg("Detected dm-crypt version %i.%i.%i, dm-ioctl version %u.%u.%u.",
105                 crypt_maj, crypt_min, crypt_patch, dm_maj, dm_min, dm_patch);
106
107         if (crypt_maj >= 1 && crypt_min >= 2)
108                 _dm_crypt_flags |= DM_KEY_WIPE_SUPPORTED;
109         else
110                 log_dbg("Suspend and resume disabled, no wipe key support.");
111
112         if (crypt_maj >= 1 && crypt_min >= 10)
113                 _dm_crypt_flags |= DM_LMK_SUPPORTED;
114
115         if (dm_maj >= 4 && dm_min >= 20)
116                 _dm_crypt_flags |= DM_SECURE_SUPPORTED;
117
118         /* not perfect, 2.6.33 supports with 1.7.0 */
119         if (crypt_maj >= 1 && crypt_min >= 8)
120                 _dm_crypt_flags |= DM_PLAIN64_SUPPORTED;
121
122         if (crypt_maj >= 1 && crypt_min >= 11)
123                 _dm_crypt_flags |= DM_DISCARDS_SUPPORTED;
124
125         /* Repeat test if dm-crypt is not present */
126         if (crypt_maj > 0)
127                 _dm_crypt_checked = 1;
128 }
129
130 static void _dm_set_verity_compat(const char *dm_version, unsigned verity_maj,
131                                    unsigned verity_min, unsigned verity_patch)
132 {
133         if (verity_maj > 0)
134                 _dm_crypt_flags |= DM_VERITY_SUPPORTED;
135
136         log_dbg("Detected dm-verity version %i.%i.%i.",
137                 verity_maj, verity_min, verity_patch);
138 }
139
140 static int _dm_check_versions(void)
141 {
142         struct dm_task *dmt;
143         struct dm_versions *target, *last_target;
144         char dm_version[16];
145
146         if (_dm_crypt_checked)
147                 return 1;
148
149         /* FIXME: add support to DM so it forces crypt target module load here */
150         if (!(dmt = dm_task_create(DM_DEVICE_LIST_VERSIONS)))
151                 return 0;
152
153         if (!dm_task_run(dmt)) {
154                 dm_task_destroy(dmt);
155                 return 0;
156         }
157
158         if (!dm_task_get_driver_version(dmt, dm_version, sizeof(dm_version))) {
159                 dm_task_destroy(dmt);
160                 return 0;
161         }
162
163         target = dm_task_get_versions(dmt);
164         do {
165                 last_target = target;
166                 if (!strcmp(DM_CRYPT_TARGET, target->name)) {
167                         _dm_set_crypt_compat(dm_version,
168                                              (unsigned)target->version[0],
169                                              (unsigned)target->version[1],
170                                              (unsigned)target->version[2]);
171                 } else if (!strcmp(DM_VERITY_TARGET, target->name)) {
172                         _dm_set_verity_compat(dm_version,
173                                              (unsigned)target->version[0],
174                                              (unsigned)target->version[1],
175                                              (unsigned)target->version[2]);
176                 }
177                 target = (struct dm_versions *)((char *) target + target->next);
178         } while (last_target != target);
179
180         dm_task_destroy(dmt);
181         return 1;
182 }
183
184 uint32_t dm_flags(void)
185 {
186         if (!_dm_crypt_checked)
187                 _dm_check_versions();
188
189         return _dm_crypt_flags;
190 }
191
192 int dm_init(struct crypt_device *context, int check_kernel)
193 {
194         if (!_dm_use_count++) {
195                 log_dbg("Initialising device-mapper backend%s, UDEV is %sabled.",
196                         check_kernel ? "" : " (NO kernel check requested)",
197                         _dm_use_udev() ? "en" : "dis");
198                 if (check_kernel && !_dm_check_versions()) {
199                         log_err(context, _("Cannot initialize device-mapper. Is dm_mod kernel module loaded?\n"));
200                         return -1;
201                 }
202                 if (getuid() || geteuid())
203                         log_dbg(("WARNING: Running as a non-root user. Functionality may be unavailable."));
204                 dm_log_init(set_dm_error);
205                 dm_log_init_verbose(10);
206         }
207
208         // FIXME: global context is not safe
209         if (context)
210                 _context = context;
211
212         return 1;       /* unsafe memory */
213 }
214
215 void dm_exit(void)
216 {
217         if (_dm_use_count && (!--_dm_use_count)) {
218                 log_dbg("Releasing device-mapper backend.");
219                 dm_log_init_verbose(0);
220                 dm_log_init(NULL);
221                 dm_lib_release();
222                 _context = NULL;
223         }
224 }
225
226 /* Return path to DM device */
227 char *dm_device_path(const char *prefix, int major, int minor)
228 {
229         struct dm_task *dmt;
230         const char *name;
231         char path[PATH_MAX];
232
233         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
234                 return NULL;
235         if (!dm_task_set_minor(dmt, minor) ||
236             !dm_task_set_major(dmt, major) ||
237             !dm_task_run(dmt) ||
238             !(name = dm_task_get_name(dmt))) {
239                 dm_task_destroy(dmt);
240                 return NULL;
241         }
242
243         if (snprintf(path, sizeof(path), "%s%s", prefix ?: "", name) < 0)
244                 path[0] = '\0';
245
246         dm_task_destroy(dmt);
247
248         return strdup(path);
249 }
250
251 static void hex_key(char *hexkey, size_t key_size, const char *key)
252 {
253         unsigned i;
254
255         for(i = 0; i < key_size; i++)
256                 sprintf(&hexkey[i * 2], "%02x", (unsigned char)key[i]);
257 }
258
259 static int hex_to_bytes(const char *hex, char *result)
260 {
261         char buf[3] = "xx\0", *endp;
262         int i, len;
263
264         len = strlen(hex) / 2;
265         for (i = 0; i < len; i++) {
266                 memcpy(buf, &hex[i * 2], 2);
267                 result[i] = strtoul(buf, &endp, 16);
268                 if (endp != &buf[2])
269                         return -EINVAL;
270         }
271         return i;
272 }
273
274 /* http://code.google.com/p/cryptsetup/wiki/DMCrypt */
275 static char *get_dm_crypt_params(struct crypt_dm_active_device *dmd)
276 {
277         int r, max_size, null_cipher = 0;
278         char *params, *hexkey;
279         const char *features = "";
280
281         if (!dmd)
282                 return NULL;
283
284         if (dmd->flags & CRYPT_ACTIVATE_ALLOW_DISCARDS) {
285                 if (dm_flags() & DM_DISCARDS_SUPPORTED) {
286                         features = " 1 allow_discards";
287                         log_dbg("Discard/TRIM is allowed.");
288                 } else
289                         log_dbg("Discard/TRIM is not supported by the kernel.");
290         }
291
292         if (!strncmp(dmd->u.crypt.cipher, "cipher_null-", 12))
293                 null_cipher = 1;
294
295         hexkey = crypt_safe_alloc(null_cipher ? 2 : (dmd->u.crypt.vk->keylength * 2 + 1));
296         if (!hexkey)
297                 return NULL;
298
299         if (null_cipher)
300                 strncpy(hexkey, "-", 2);
301         else
302                 hex_key(hexkey, dmd->u.crypt.vk->keylength, dmd->u.crypt.vk->key);
303
304         max_size = strlen(hexkey) + strlen(dmd->u.crypt.cipher) +
305                    strlen(dmd->data_device) + strlen(features) + 64;
306         params = crypt_safe_alloc(max_size);
307         if (!params)
308                 goto out;
309
310         r = snprintf(params, max_size, "%s %s %" PRIu64 " %s %" PRIu64 "%s",
311                      dmd->u.crypt.cipher, hexkey, dmd->u.crypt.iv_offset,
312                      dmd->data_device, dmd->u.crypt.offset, features);
313         if (r < 0 || r >= max_size) {
314                 crypt_safe_free(params);
315                 params = NULL;
316         }
317 out:
318         crypt_safe_free(hexkey);
319         return params;
320 }
321
322 /* http://code.google.com/p/cryptsetup/wiki/DMVerity */
323 static char *get_dm_verity_params(struct crypt_params_verity *vp,
324                                    struct crypt_dm_active_device *dmd)
325 {
326         int max_size, r;
327         char *params = NULL, *hexroot = NULL, *hexsalt = NULL;
328
329         if (!vp || !dmd)
330                 return NULL;
331
332         hexroot = crypt_safe_alloc(dmd->u.verity.root_hash_size * 2 + 1);
333         if (!hexroot)
334                 goto out;
335         hex_key(hexroot, dmd->u.verity.root_hash_size, dmd->u.verity.root_hash);
336
337         hexsalt = crypt_safe_alloc(vp->salt_size * 2 + 1);
338         if (!hexsalt)
339                 goto out;
340         hex_key(hexsalt, vp->salt_size, vp->salt);
341
342         max_size = strlen(hexroot) + strlen(hexsalt) +
343                    strlen(dmd->data_device) +
344                    strlen(dmd->u.verity.hash_device) +
345                    strlen(vp->hash_name) + 128;
346
347         params = crypt_safe_alloc(max_size);
348         if (!params)
349                 goto out;
350
351         r = snprintf(params, max_size,
352                      "%u %s %s %u %u %" PRIu64 " %" PRIu64 " %s %s %s",
353                      vp->version, dmd->data_device,
354                      dmd->u.verity.hash_device,
355                      vp->data_block_size, vp->hash_block_size,
356                      vp->data_size, dmd->u.verity.hash_offset,
357                      vp->hash_name, hexroot, hexsalt);
358         if (r < 0 || r >= max_size) {
359                 crypt_safe_free(params);
360                 params = NULL;
361         }
362         log_dbg("TABLE: %s", params);
363 out:
364         crypt_safe_free(hexroot);
365         crypt_safe_free(hexsalt);
366         return params;
367
368 }
369
370 /* DM helpers */
371 static int _dm_simple(int task, const char *name, int udev_wait)
372 {
373         int r = 0;
374         struct dm_task *dmt;
375         uint32_t cookie = 0;
376
377         if (!_dm_use_udev())
378                 udev_wait = 0;
379
380         if (!(dmt = dm_task_create(task)))
381                 return 0;
382
383         if (name && !dm_task_set_name(dmt, name))
384                 goto out;
385
386 #if HAVE_DECL_DM_TASK_RETRY_REMOVE
387         /* Used only in DM_DEVICE_REMOVE */
388         if (name && !dm_task_retry_remove(dmt))
389                 goto out;
390 #endif
391         if (udev_wait && !_dm_task_set_cookie(dmt, &cookie, 0))
392                 goto out;
393
394         r = dm_task_run(dmt);
395
396         if (udev_wait)
397                 (void)_dm_udev_wait(cookie);
398
399       out:
400         dm_task_destroy(dmt);
401         return r;
402 }
403
404 static int _error_device(const char *name, size_t size)
405 {
406         struct dm_task *dmt;
407         int r = 0;
408
409         if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
410                 return 0;
411
412         if (!dm_task_set_name(dmt, name))
413                 goto error;
414
415         if (!dm_task_add_target(dmt, UINT64_C(0), size, "error", ""))
416                 goto error;
417
418         if (!dm_task_set_ro(dmt))
419                 goto error;
420
421         if (!dm_task_no_open_count(dmt))
422                 goto error;
423
424         if (!dm_task_run(dmt))
425                 goto error;
426
427         if (!_dm_simple(DM_DEVICE_RESUME, name, 1)) {
428                 _dm_simple(DM_DEVICE_CLEAR, name, 0);
429                 goto error;
430         }
431
432         r = 1;
433
434 error:
435         dm_task_destroy(dmt);
436         return r;
437 }
438
439 int dm_remove_device(const char *name, int force, uint64_t size)
440 {
441         int r = -EINVAL;
442         int retries = force ? RETRY_COUNT : 1;
443         int error_target = 0;
444
445         if (!name || (force && !size))
446                 return -EINVAL;
447
448         do {
449                 r = _dm_simple(DM_DEVICE_REMOVE, name, 1) ? 0 : -EINVAL;
450                 if (--retries && r) {
451                         log_dbg("WARNING: other process locked internal device %s, %s.",
452                                 name, retries ? "retrying remove" : "giving up");
453                         if (force && (crypt_get_debug_level() == CRYPT_LOG_DEBUG))
454                                 debug_processes_using_device(name);
455                         sleep(1);
456                         if (force && !error_target) {
457                                 /* If force flag is set, replace device with error, read-only target.
458                                  * it should stop processes from reading it and also removed underlying
459                                  * device from mapping, so it is usable again.
460                                  * Force flag should be used only for temporary devices, which are
461                                  * intended to work inside cryptsetup only!
462                                  * Anyway, if some process try to read temporary cryptsetup device,
463                                  * it is bug - no other process should try touch it (e.g. udev).
464                                  */
465                                 _error_device(name, size);
466                                 error_target = 1;
467                         }
468                 }
469         } while (r == -EINVAL && retries);
470
471         dm_task_update_nodes();
472
473         return r;
474 }
475
476 #define UUID_LEN 37 /* 36 + \0, libuuid ... */
477 /*
478  * UUID has format: CRYPT-<devicetype>-[<uuid>-]<device name>
479  * CRYPT-PLAIN-name
480  * CRYPT-LUKS1-00000000000000000000000000000000-name
481  * CRYPT-TEMP-name
482  */
483 static void dm_prepare_uuid(const char *name, const char *type, const char *uuid, char *buf, size_t buflen)
484 {
485         char *ptr, uuid2[UUID_LEN] = {0};
486         uuid_t uu;
487         unsigned i = 0;
488
489         /* Remove '-' chars */
490         if (uuid && !uuid_parse(uuid, uu)) {
491                 for (ptr = uuid2, i = 0; i < UUID_LEN; i++)
492                         if (uuid[i] != '-') {
493                                 *ptr = uuid[i];
494                                 ptr++;
495                         }
496         }
497
498         i = snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s%s",
499                 type ?: "", type ? "-" : "",
500                 uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "",
501                 name);
502
503         log_dbg("DM-UUID is %s", buf);
504         if (i >= buflen)
505                 log_err(NULL, _("DM-UUID for device %s was truncated.\n"), name);
506 }
507
508 static int _dm_create_device(const char *name, const char *type,
509                              const char *device, uint32_t flags,
510                              const char *uuid, uint64_t size,
511                              char *params, int reload)
512 {
513         struct dm_task *dmt = NULL;
514         struct dm_info dmi;
515         char dev_uuid[DM_UUID_LEN] = {0};
516         int r = -EINVAL;
517         uint32_t read_ahead = 0;
518         uint32_t cookie = 0;
519         uint16_t udev_flags = 0;
520
521         if (flags & CRYPT_ACTIVATE_PRIVATE)
522                 udev_flags = CRYPT_TEMP_UDEV_FLAGS;
523
524         /* All devices must have DM_UUID, only resize on old device is exception */
525         if (reload) {
526                 if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
527                         goto out_no_removal;
528
529                 if (!dm_task_set_name(dmt, name))
530                         goto out_no_removal;
531         } else {
532                 dm_prepare_uuid(name, type, uuid, dev_uuid, sizeof(dev_uuid));
533
534                 if (!(dmt = dm_task_create(DM_DEVICE_CREATE)))
535                         goto out_no_removal;
536
537                 if (!dm_task_set_name(dmt, name))
538                         goto out_no_removal;
539
540                 if (!dm_task_set_uuid(dmt, dev_uuid))
541                         goto out_no_removal;
542
543                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
544                         goto out_no_removal;
545         }
546
547         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
548                 goto out_no_removal;
549         if ((flags & CRYPT_ACTIVATE_READONLY) && !dm_task_set_ro(dmt))
550                 goto out_no_removal;
551
552         if (!dm_task_add_target(dmt, 0, size,
553                 !strcmp("VERITY", type) ? DM_VERITY_TARGET : DM_CRYPT_TARGET, params))
554                 goto out_no_removal;
555
556 #ifdef DM_READ_AHEAD_MINIMUM_FLAG
557         if (device_read_ahead(device, &read_ahead) &&
558             !dm_task_set_read_ahead(dmt, read_ahead, DM_READ_AHEAD_MINIMUM_FLAG))
559                 goto out_no_removal;
560 #endif
561
562         if (!dm_task_run(dmt))
563                 goto out_no_removal;
564
565         if (reload) {
566                 dm_task_destroy(dmt);
567                 if (!(dmt = dm_task_create(DM_DEVICE_RESUME)))
568                         goto out;
569                 if (!dm_task_set_name(dmt, name))
570                         goto out;
571                 if (uuid && !dm_task_set_uuid(dmt, dev_uuid))
572                         goto out;
573                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
574                         goto out;
575                 if (!dm_task_run(dmt))
576                         goto out;
577         }
578
579         if (!dm_task_get_info(dmt, &dmi))
580                 goto out;
581
582         r = 0;
583 out:
584         if (_dm_use_udev()) {
585                 (void)_dm_udev_wait(cookie);
586                 cookie = 0;
587         }
588
589         if (r < 0 && !reload)
590                 dm_remove_device(name, 0, 0);
591
592 out_no_removal:
593         if (cookie && _dm_use_udev())
594                 (void)_dm_udev_wait(cookie);
595
596         if (params)
597                 crypt_safe_free(params);
598         if (dmt)
599                 dm_task_destroy(dmt);
600
601         dm_task_update_nodes();
602         return r;
603 }
604
605 int dm_create_device(const char *name,
606                      const char *type,
607                      struct crypt_dm_active_device *dmd,
608                      int reload)
609 {
610         char *table_params = NULL;
611
612         if (dmd->target == DM_CRYPT)
613                 table_params = get_dm_crypt_params(dmd);
614         else if (dmd->target == DM_VERITY)
615                 table_params = get_dm_verity_params(dmd->u.verity.vp, dmd);
616
617         if (!table_params)
618                 return -EINVAL;
619
620         return _dm_create_device(name, type, dmd->data_device, dmd->flags,
621                                  dmd->uuid, dmd->size, table_params, reload);
622 }
623
624 static int dm_status_dmi(const char *name, struct dm_info *dmi,
625                           const char *target, char **status_line)
626 {
627         struct dm_task *dmt;
628         uint64_t start, length;
629         char *target_type, *params = NULL;
630         void *next = NULL;
631         int r = -EINVAL;
632
633         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
634                 goto out;
635
636         if (!dm_task_set_name(dmt, name))
637                 goto out;
638
639         if (!dm_task_run(dmt))
640                 goto out;
641
642         if (!dm_task_get_info(dmt, dmi))
643                 goto out;
644
645         if (!dmi->exists) {
646                 r = -ENODEV;
647                 goto out;
648         }
649
650         next = dm_get_next_target(dmt, next, &start, &length,
651                                   &target_type, &params);
652
653         if (!target_type || start != 0 || next)
654                 goto out;
655
656         if (target && strcmp(target_type, target))
657                 goto out;
658
659         /* for target == NULL check all supported */
660         if (!target && (strcmp(target_type, DM_CRYPT_TARGET) &&
661                         strcmp(target_type, DM_VERITY_TARGET)))
662                 goto out;
663         r = 0;
664 out:
665         if (!r && status_line && !(*status_line = strdup(params)))
666                 r = -ENOMEM;
667
668         if (dmt)
669                 dm_task_destroy(dmt);
670
671         return r;
672 }
673
674 int dm_status_device(const char *name)
675 {
676         int r;
677         struct dm_info dmi;
678
679         r = dm_status_dmi(name, &dmi, NULL, NULL);
680         if (r < 0)
681                 return r;
682
683         return (dmi.open_count > 0);
684 }
685
686 int dm_status_suspended(const char *name)
687 {
688         int r;
689         struct dm_info dmi;
690
691         r = dm_status_dmi(name, &dmi, DM_CRYPT_TARGET, NULL);
692         if (r < 0)
693                 return r;
694
695         return dmi.suspended ? 1 : 0;
696 }
697
698 int dm_status_verity_ok(const char *name)
699 {
700         int r;
701         struct dm_info dmi;
702         char *status_line = NULL;
703
704         r = dm_status_dmi(name, &dmi, DM_VERITY_TARGET, &status_line);
705         if (r < 0 || !status_line) {
706                 free(status_line);
707                 return r;
708         }
709
710         log_dbg("Verity volume %s status is %s.", name, status_line ?: "");
711         r = status_line[0] == 'V' ? 1 : 0;
712         free(status_line);
713
714         return r;
715 }
716
717 /* FIXME use hex wrapper, user val wrappers for line parsing */
718 static int _dm_query_crypt(uint32_t get_flags,
719                            struct dm_info *dmi,
720                            char *params,
721                            struct crypt_dm_active_device *dmd)
722 {
723         uint64_t val64;
724         char *rcipher, *key_, *rdevice, *endp, buffer[3], *arg;
725         unsigned int i;
726
727         memset(dmd, 0, sizeof(*dmd));
728         dmd->target = DM_CRYPT;
729
730         rcipher = strsep(&params, " ");
731         /* cipher */
732         if (get_flags & DM_ACTIVE_CRYPT_CIPHER)
733                 dmd->u.crypt.cipher = strdup(rcipher);
734
735         /* skip */
736         key_ = strsep(&params, " ");
737         if (!params)
738                 return -EINVAL;
739         val64 = strtoull(params, &params, 10);
740         if (*params != ' ')
741                 return -EINVAL;
742         params++;
743
744         dmd->u.crypt.iv_offset = val64;
745
746         /* device */
747         rdevice = strsep(&params, " ");
748         if (get_flags & DM_ACTIVE_DEVICE)
749                 dmd->data_device = crypt_lookup_dev(rdevice);
750
751         /*offset */
752         if (!params)
753                 return -EINVAL;
754         val64 = strtoull(params, &params, 10);
755         dmd->u.crypt.offset = val64;
756
757         /* Features section, available since crypt target version 1.11 */
758         if (*params) {
759                 if (*params != ' ')
760                         return -EINVAL;
761                 params++;
762
763                 /* Number of arguments */
764                 val64 = strtoull(params, &params, 10);
765                 if (*params != ' ')
766                         return -EINVAL;
767                 params++;
768
769                 for (i = 0; i < val64; i++) {
770                         if (!params)
771                                 return -EINVAL;
772                         arg = strsep(&params, " ");
773                         if (!strcasecmp(arg, "allow_discards"))
774                                 dmd->flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
775                         else /* unknown option */
776                                 return -EINVAL;
777                 }
778
779                 /* All parameters shold be processed */
780                 if (params)
781                         return -EINVAL;
782         }
783
784         /* Never allow to return empty key */
785         if ((get_flags & DM_ACTIVE_CRYPT_KEY) && dmi->suspended) {
786                 log_dbg("Cannot read volume key while suspended.");
787                 return -EINVAL;
788         }
789
790         if (get_flags & DM_ACTIVE_CRYPT_KEYSIZE) {
791                 dmd->u.crypt.vk = crypt_alloc_volume_key(strlen(key_) / 2, NULL);
792                 if (!dmd->u.crypt.vk)
793                         return -ENOMEM;
794
795                 if (get_flags & DM_ACTIVE_CRYPT_KEY) {
796                         buffer[2] = '\0';
797                         for(i = 0; i < dmd->u.crypt.vk->keylength; i++) {
798                                 memcpy(buffer, &key_[i * 2], 2);
799                                 dmd->u.crypt.vk->key[i] = strtoul(buffer, &endp, 16);
800                                 if (endp != &buffer[2]) {
801                                         crypt_free_volume_key(dmd->u.crypt.vk);
802                                         dmd->u.crypt.vk = NULL;
803                                         return -EINVAL;
804                                 }
805                         }
806                 }
807         }
808         memset(key_, 0, strlen(key_));
809
810         return 0;
811 }
812
813 static int _dm_query_verity(uint32_t get_flags,
814                              struct dm_info *dmi,
815                              char *params,
816                              struct crypt_dm_active_device *dmd)
817 {
818         struct crypt_params_verity *vp = NULL;
819         uint32_t val32;
820         uint64_t val64;
821         size_t len;
822         char *str, *str2;
823
824         if (get_flags & DM_ACTIVE_VERITY_PARAMS)
825                 vp = dmd->u.verity.vp;
826
827         memset(dmd, 0, sizeof(*dmd));
828
829         dmd->target = DM_VERITY;
830         dmd->u.verity.vp = vp;
831
832         /* version */
833         val32 = strtoul(params, &params, 10);
834         if (*params != ' ')
835                 return -EINVAL;
836         if (vp)
837                 vp->version = val32;
838         params++;
839
840         /* data device */
841         str = strsep(&params, " ");
842         if (!params)
843                 return -EINVAL;
844         if (get_flags & DM_ACTIVE_DEVICE)
845                 dmd->data_device = crypt_lookup_dev(str);
846
847         /* hash device */
848         str = strsep(&params, " ");
849         if (!params)
850                 return -EINVAL;
851         if (get_flags & DM_ACTIVE_VERITY_HASH_DEVICE)
852                 dmd->u.verity.hash_device = crypt_lookup_dev(str);
853
854         /* data block size*/
855         val32 = strtoul(params, &params, 10);
856         if (*params != ' ')
857                 return -EINVAL;
858         if (vp)
859                 vp->data_block_size = val32;
860         params++;
861
862         /* hash block size */
863         val32 = strtoul(params, &params, 10);
864         if (*params != ' ')
865                 return -EINVAL;
866         if (vp)
867                 vp->hash_block_size = val32;
868         params++;
869
870         /* data blocks */
871         val64 = strtoull(params, &params, 10);
872         if (*params != ' ')
873                 return -EINVAL;
874         if (vp)
875                 vp->data_size = val64;
876         params++;
877
878         /* hash start */
879         val64 = strtoull(params, &params, 10);
880         if (*params != ' ')
881                 return -EINVAL;
882         dmd->u.verity.hash_offset = val64;
883         params++;
884
885         /* hash algorithm */
886         str = strsep(&params, " ");
887         if (!params)
888                 return -EINVAL;
889         if (vp)
890                 vp->hash_name = strdup(str);
891
892         /* root digest */
893         str = strsep(&params, " ");
894         if (!params)
895                 return -EINVAL;
896         len = strlen(str) / 2;
897         dmd->u.verity.root_hash_size = len;
898         if (get_flags & DM_ACTIVE_VERITY_ROOT_HASH) {
899                 if (!(str2 = malloc(len)))
900                         return -ENOMEM;
901                 if (hex_to_bytes(str, str2) != len)
902                         return -EINVAL;
903                 dmd->u.verity.root_hash = str2;
904         }
905
906         /* salt */
907         str = strsep(&params, " ");
908         if (params)
909                 return -EINVAL;
910         if (vp) {
911                 len = strlen(str) / 2;
912                 vp->salt_size = len;
913                 if (!(str2 = malloc(len)))
914                         return -ENOMEM;
915                 if (hex_to_bytes(str, str2) != len)
916                         return -EINVAL;
917                 vp->salt = str2;
918         }
919
920         return 0;
921 }
922
923 int dm_query_device(const char *name, uint32_t get_flags,
924                     struct crypt_dm_active_device *dmd)
925 {
926         struct dm_task *dmt;
927         struct dm_info dmi;
928         uint64_t start, length;
929         char *target_type, *params;
930         const char *tmp_uuid;
931         void *next = NULL;
932         int r = -EINVAL;
933
934         if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
935                 goto out;
936         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
937                 goto out;
938         if (!dm_task_set_name(dmt, name))
939                 goto out;
940         r = -ENODEV;
941         if (!dm_task_run(dmt))
942                 goto out;
943
944         r = -EINVAL;
945         if (!dm_task_get_info(dmt, &dmi))
946                 goto out;
947
948         if (!dmi.exists) {
949                 r = -ENODEV;
950                 goto out;
951         }
952
953         next = dm_get_next_target(dmt, next, &start, &length,
954                                   &target_type, &params);
955
956         if (!target_type || start != 0 || next)
957                 goto out;
958
959         if (!strcmp(target_type, DM_CRYPT_TARGET))
960                 r = _dm_query_crypt(get_flags, &dmi, params, dmd);
961         else if (!strcmp(target_type, DM_VERITY_TARGET))
962                 r = _dm_query_verity(get_flags, &dmi, params, dmd);
963         else
964                 r = -EINVAL;
965
966         if (r < 0)
967                 goto out;
968
969         dmd->size = length;
970
971         if (dmi.read_only)
972                 dmd->flags |= CRYPT_ACTIVATE_READONLY;
973
974         tmp_uuid = dm_task_get_uuid(dmt);
975         if (!tmp_uuid)
976                 dmd->flags |= CRYPT_ACTIVATE_NO_UUID;
977         else if (get_flags & DM_ACTIVE_UUID) {
978                 if (!strncmp(tmp_uuid, DM_UUID_PREFIX, DM_UUID_PREFIX_LEN))
979                         dmd->uuid = strdup(tmp_uuid + DM_UUID_PREFIX_LEN);
980         }
981
982         r = (dmi.open_count > 0);
983 out:
984         if (dmt)
985                 dm_task_destroy(dmt);
986
987         return r;
988 }
989
990 static int _dm_message(const char *name, const char *msg)
991 {
992         int r = 0;
993         struct dm_task *dmt;
994
995         if (!(dmt = dm_task_create(DM_DEVICE_TARGET_MSG)))
996                 return 0;
997
998         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
999                 goto out;
1000
1001         if (name && !dm_task_set_name(dmt, name))
1002                 goto out;
1003
1004         if (!dm_task_set_sector(dmt, (uint64_t) 0))
1005                 goto out;
1006
1007         if (!dm_task_set_message(dmt, msg))
1008                 goto out;
1009
1010         r = dm_task_run(dmt);
1011
1012       out:
1013         dm_task_destroy(dmt);
1014         return r;
1015 }
1016
1017 int dm_suspend_and_wipe_key(const char *name)
1018 {
1019         if (!_dm_check_versions())
1020                 return -ENOTSUP;
1021
1022         if (!(_dm_crypt_flags & DM_KEY_WIPE_SUPPORTED))
1023                 return -ENOTSUP;
1024
1025         if (!_dm_simple(DM_DEVICE_SUSPEND, name, 0))
1026                 return -EINVAL;
1027
1028         if (!_dm_message(name, "key wipe")) {
1029                 _dm_simple(DM_DEVICE_RESUME, name, 1);
1030                 return -EINVAL;
1031         }
1032
1033         return 0;
1034 }
1035
1036 int dm_resume_and_reinstate_key(const char *name,
1037                                 size_t key_size,
1038                                 const char *key)
1039 {
1040         int msg_size = key_size * 2 + 10; // key set <key>
1041         char *msg;
1042         int r = 0;
1043
1044         if (!_dm_check_versions())
1045                 return -ENOTSUP;
1046
1047         if (!(_dm_crypt_flags & DM_KEY_WIPE_SUPPORTED))
1048                 return -ENOTSUP;
1049
1050         msg = crypt_safe_alloc(msg_size);
1051         if (!msg)
1052                 return -ENOMEM;
1053
1054         memset(msg, 0, msg_size);
1055         strcpy(msg, "key set ");
1056         hex_key(&msg[8], key_size, key);
1057
1058         if (!_dm_message(name, msg) ||
1059             !_dm_simple(DM_DEVICE_RESUME, name, 1))
1060                 r = -EINVAL;
1061
1062         crypt_safe_free(msg);
1063         return r;
1064 }
1065
1066 const char *dm_get_dir(void)
1067 {
1068         return dm_dir();
1069 }
1070
1071 int dm_is_dm_device(int major, int minor)
1072 {
1073         return dm_is_dm_major((uint32_t)major);
1074 }
1075
1076 int dm_is_dm_kernel_name(const char *name)
1077 {
1078         return strncmp(name, "dm-", 3) ? 0 : 1;
1079 }
1080
1081 int dm_check_segment(const char *name, uint64_t offset, uint64_t size)
1082 {
1083         struct crypt_dm_active_device dmd;
1084         int r;
1085
1086         log_dbg("Checking segments for device %s.", name);
1087
1088         r = dm_query_device(name, 0, &dmd);
1089         if (r < 0)
1090                 return r;
1091
1092         if (offset >= (dmd.u.crypt.offset + dmd.size) ||
1093            (offset + size) <= dmd.u.crypt.offset)
1094                 r = 0;
1095         else
1096                 r = -EBUSY;
1097
1098         log_dbg("seg: %" PRIu64 " - %" PRIu64 ", new %" PRIu64 " - %" PRIu64 "%s",
1099                dmd.u.crypt.offset, dmd.u.crypt.offset + dmd.size, offset, offset + size,
1100                r ? " (overlapping)" : " (ok)");
1101
1102         return r;
1103 }