Support empty salt for verity, support no superblock.
[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 ? vp->salt_size * 2 + 1 : 2);
338         if (!hexsalt)
339                 goto out;
340         if (vp->salt_size)
341                 hex_key(hexsalt, vp->salt_size, vp->salt);
342         else
343                 strncpy(hexsalt, "-", 2);
344
345         max_size = strlen(hexroot) + strlen(hexsalt) +
346                    strlen(dmd->data_device) +
347                    strlen(dmd->u.verity.hash_device) +
348                    strlen(vp->hash_name) + 128;
349
350         params = crypt_safe_alloc(max_size);
351         if (!params)
352                 goto out;
353
354         r = snprintf(params, max_size,
355                      "%u %s %s %u %u %" PRIu64 " %" PRIu64 " %s %s %s",
356                      vp->version, dmd->data_device,
357                      dmd->u.verity.hash_device,
358                      vp->data_block_size, vp->hash_block_size,
359                      vp->data_size, dmd->u.verity.hash_offset,
360                      vp->hash_name, hexroot, hexsalt);
361         if (r < 0 || r >= max_size) {
362                 crypt_safe_free(params);
363                 params = NULL;
364         }
365         log_dbg("TABLE: %s", params);
366 out:
367         crypt_safe_free(hexroot);
368         crypt_safe_free(hexsalt);
369         return params;
370
371 }
372
373 /* DM helpers */
374 static int _dm_simple(int task, const char *name, int udev_wait)
375 {
376         int r = 0;
377         struct dm_task *dmt;
378         uint32_t cookie = 0;
379
380         if (!_dm_use_udev())
381                 udev_wait = 0;
382
383         if (!(dmt = dm_task_create(task)))
384                 return 0;
385
386         if (name && !dm_task_set_name(dmt, name))
387                 goto out;
388
389 #if HAVE_DECL_DM_TASK_RETRY_REMOVE
390         /* Used only in DM_DEVICE_REMOVE */
391         if (name && !dm_task_retry_remove(dmt))
392                 goto out;
393 #endif
394         if (udev_wait && !_dm_task_set_cookie(dmt, &cookie, 0))
395                 goto out;
396
397         r = dm_task_run(dmt);
398
399         if (udev_wait)
400                 (void)_dm_udev_wait(cookie);
401
402       out:
403         dm_task_destroy(dmt);
404         return r;
405 }
406
407 static int _error_device(const char *name, size_t size)
408 {
409         struct dm_task *dmt;
410         int r = 0;
411
412         if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
413                 return 0;
414
415         if (!dm_task_set_name(dmt, name))
416                 goto error;
417
418         if (!dm_task_add_target(dmt, UINT64_C(0), size, "error", ""))
419                 goto error;
420
421         if (!dm_task_set_ro(dmt))
422                 goto error;
423
424         if (!dm_task_no_open_count(dmt))
425                 goto error;
426
427         if (!dm_task_run(dmt))
428                 goto error;
429
430         if (!_dm_simple(DM_DEVICE_RESUME, name, 1)) {
431                 _dm_simple(DM_DEVICE_CLEAR, name, 0);
432                 goto error;
433         }
434
435         r = 1;
436
437 error:
438         dm_task_destroy(dmt);
439         return r;
440 }
441
442 int dm_remove_device(const char *name, int force, uint64_t size)
443 {
444         int r = -EINVAL;
445         int retries = force ? RETRY_COUNT : 1;
446         int error_target = 0;
447
448         if (!name || (force && !size))
449                 return -EINVAL;
450
451         do {
452                 r = _dm_simple(DM_DEVICE_REMOVE, name, 1) ? 0 : -EINVAL;
453                 if (--retries && r) {
454                         log_dbg("WARNING: other process locked internal device %s, %s.",
455                                 name, retries ? "retrying remove" : "giving up");
456                         if (force && (crypt_get_debug_level() == CRYPT_LOG_DEBUG))
457                                 debug_processes_using_device(name);
458                         sleep(1);
459                         if (force && !error_target) {
460                                 /* If force flag is set, replace device with error, read-only target.
461                                  * it should stop processes from reading it and also removed underlying
462                                  * device from mapping, so it is usable again.
463                                  * Force flag should be used only for temporary devices, which are
464                                  * intended to work inside cryptsetup only!
465                                  * Anyway, if some process try to read temporary cryptsetup device,
466                                  * it is bug - no other process should try touch it (e.g. udev).
467                                  */
468                                 _error_device(name, size);
469                                 error_target = 1;
470                         }
471                 }
472         } while (r == -EINVAL && retries);
473
474         dm_task_update_nodes();
475
476         return r;
477 }
478
479 #define UUID_LEN 37 /* 36 + \0, libuuid ... */
480 /*
481  * UUID has format: CRYPT-<devicetype>-[<uuid>-]<device name>
482  * CRYPT-PLAIN-name
483  * CRYPT-LUKS1-00000000000000000000000000000000-name
484  * CRYPT-TEMP-name
485  */
486 static void dm_prepare_uuid(const char *name, const char *type, const char *uuid, char *buf, size_t buflen)
487 {
488         char *ptr, uuid2[UUID_LEN] = {0};
489         uuid_t uu;
490         unsigned i = 0;
491
492         /* Remove '-' chars */
493         if (uuid && !uuid_parse(uuid, uu)) {
494                 for (ptr = uuid2, i = 0; i < UUID_LEN; i++)
495                         if (uuid[i] != '-') {
496                                 *ptr = uuid[i];
497                                 ptr++;
498                         }
499         }
500
501         i = snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s%s",
502                 type ?: "", type ? "-" : "",
503                 uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "",
504                 name);
505
506         log_dbg("DM-UUID is %s", buf);
507         if (i >= buflen)
508                 log_err(NULL, _("DM-UUID for device %s was truncated.\n"), name);
509 }
510
511 static int _dm_create_device(const char *name, const char *type,
512                              const char *device, uint32_t flags,
513                              const char *uuid, uint64_t size,
514                              char *params, int reload)
515 {
516         struct dm_task *dmt = NULL;
517         struct dm_info dmi;
518         char dev_uuid[DM_UUID_LEN] = {0};
519         int r = -EINVAL;
520         uint32_t read_ahead = 0;
521         uint32_t cookie = 0;
522         uint16_t udev_flags = 0;
523
524         if (flags & CRYPT_ACTIVATE_PRIVATE)
525                 udev_flags = CRYPT_TEMP_UDEV_FLAGS;
526
527         /* All devices must have DM_UUID, only resize on old device is exception */
528         if (reload) {
529                 if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
530                         goto out_no_removal;
531
532                 if (!dm_task_set_name(dmt, name))
533                         goto out_no_removal;
534         } else {
535                 dm_prepare_uuid(name, type, uuid, dev_uuid, sizeof(dev_uuid));
536
537                 if (!(dmt = dm_task_create(DM_DEVICE_CREATE)))
538                         goto out_no_removal;
539
540                 if (!dm_task_set_name(dmt, name))
541                         goto out_no_removal;
542
543                 if (!dm_task_set_uuid(dmt, dev_uuid))
544                         goto out_no_removal;
545
546                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
547                         goto out_no_removal;
548         }
549
550         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
551                 goto out_no_removal;
552         if ((flags & CRYPT_ACTIVATE_READONLY) && !dm_task_set_ro(dmt))
553                 goto out_no_removal;
554
555         if (!dm_task_add_target(dmt, 0, size,
556                 !strcmp("VERITY", type) ? DM_VERITY_TARGET : DM_CRYPT_TARGET, params))
557                 goto out_no_removal;
558
559 #ifdef DM_READ_AHEAD_MINIMUM_FLAG
560         if (device_read_ahead(device, &read_ahead) &&
561             !dm_task_set_read_ahead(dmt, read_ahead, DM_READ_AHEAD_MINIMUM_FLAG))
562                 goto out_no_removal;
563 #endif
564
565         if (!dm_task_run(dmt))
566                 goto out_no_removal;
567
568         if (reload) {
569                 dm_task_destroy(dmt);
570                 if (!(dmt = dm_task_create(DM_DEVICE_RESUME)))
571                         goto out;
572                 if (!dm_task_set_name(dmt, name))
573                         goto out;
574                 if (uuid && !dm_task_set_uuid(dmt, dev_uuid))
575                         goto out;
576                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
577                         goto out;
578                 if (!dm_task_run(dmt))
579                         goto out;
580         }
581
582         if (!dm_task_get_info(dmt, &dmi))
583                 goto out;
584
585         r = 0;
586 out:
587         if (_dm_use_udev()) {
588                 (void)_dm_udev_wait(cookie);
589                 cookie = 0;
590         }
591
592         if (r < 0 && !reload)
593                 dm_remove_device(name, 0, 0);
594
595 out_no_removal:
596         if (cookie && _dm_use_udev())
597                 (void)_dm_udev_wait(cookie);
598
599         if (params)
600                 crypt_safe_free(params);
601         if (dmt)
602                 dm_task_destroy(dmt);
603
604         dm_task_update_nodes();
605         return r;
606 }
607
608 int dm_create_device(const char *name,
609                      const char *type,
610                      struct crypt_dm_active_device *dmd,
611                      int reload)
612 {
613         char *table_params = NULL;
614
615         if (dmd->target == DM_CRYPT)
616                 table_params = get_dm_crypt_params(dmd);
617         else if (dmd->target == DM_VERITY)
618                 table_params = get_dm_verity_params(dmd->u.verity.vp, dmd);
619
620         if (!table_params)
621                 return -EINVAL;
622
623         return _dm_create_device(name, type, dmd->data_device, dmd->flags,
624                                  dmd->uuid, dmd->size, table_params, reload);
625 }
626
627 static int dm_status_dmi(const char *name, struct dm_info *dmi,
628                           const char *target, char **status_line)
629 {
630         struct dm_task *dmt;
631         uint64_t start, length;
632         char *target_type, *params = NULL;
633         void *next = NULL;
634         int r = -EINVAL;
635
636         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
637                 goto out;
638
639         if (!dm_task_set_name(dmt, name))
640                 goto out;
641
642         if (!dm_task_run(dmt))
643                 goto out;
644
645         if (!dm_task_get_info(dmt, dmi))
646                 goto out;
647
648         if (!dmi->exists) {
649                 r = -ENODEV;
650                 goto out;
651         }
652
653         next = dm_get_next_target(dmt, next, &start, &length,
654                                   &target_type, &params);
655
656         if (!target_type || start != 0 || next)
657                 goto out;
658
659         if (target && strcmp(target_type, target))
660                 goto out;
661
662         /* for target == NULL check all supported */
663         if (!target && (strcmp(target_type, DM_CRYPT_TARGET) &&
664                         strcmp(target_type, DM_VERITY_TARGET)))
665                 goto out;
666         r = 0;
667 out:
668         if (!r && status_line && !(*status_line = strdup(params)))
669                 r = -ENOMEM;
670
671         if (dmt)
672                 dm_task_destroy(dmt);
673
674         return r;
675 }
676
677 int dm_status_device(const char *name)
678 {
679         int r;
680         struct dm_info dmi;
681
682         r = dm_status_dmi(name, &dmi, NULL, NULL);
683         if (r < 0)
684                 return r;
685
686         return (dmi.open_count > 0);
687 }
688
689 int dm_status_suspended(const char *name)
690 {
691         int r;
692         struct dm_info dmi;
693
694         r = dm_status_dmi(name, &dmi, DM_CRYPT_TARGET, NULL);
695         if (r < 0)
696                 return r;
697
698         return dmi.suspended ? 1 : 0;
699 }
700
701 int dm_status_verity_ok(const char *name)
702 {
703         int r;
704         struct dm_info dmi;
705         char *status_line = NULL;
706
707         r = dm_status_dmi(name, &dmi, DM_VERITY_TARGET, &status_line);
708         if (r < 0 || !status_line) {
709                 free(status_line);
710                 return r;
711         }
712
713         log_dbg("Verity volume %s status is %s.", name, status_line ?: "");
714         r = status_line[0] == 'V' ? 1 : 0;
715         free(status_line);
716
717         return r;
718 }
719
720 /* FIXME use hex wrapper, user val wrappers for line parsing */
721 static int _dm_query_crypt(uint32_t get_flags,
722                            struct dm_info *dmi,
723                            char *params,
724                            struct crypt_dm_active_device *dmd)
725 {
726         uint64_t val64;
727         char *rcipher, *key_, *rdevice, *endp, buffer[3], *arg;
728         unsigned int i;
729
730         memset(dmd, 0, sizeof(*dmd));
731         dmd->target = DM_CRYPT;
732
733         rcipher = strsep(&params, " ");
734         /* cipher */
735         if (get_flags & DM_ACTIVE_CRYPT_CIPHER)
736                 dmd->u.crypt.cipher = strdup(rcipher);
737
738         /* skip */
739         key_ = strsep(&params, " ");
740         if (!params)
741                 return -EINVAL;
742         val64 = strtoull(params, &params, 10);
743         if (*params != ' ')
744                 return -EINVAL;
745         params++;
746
747         dmd->u.crypt.iv_offset = val64;
748
749         /* device */
750         rdevice = strsep(&params, " ");
751         if (get_flags & DM_ACTIVE_DEVICE)
752                 dmd->data_device = crypt_lookup_dev(rdevice);
753
754         /*offset */
755         if (!params)
756                 return -EINVAL;
757         val64 = strtoull(params, &params, 10);
758         dmd->u.crypt.offset = val64;
759
760         /* Features section, available since crypt target version 1.11 */
761         if (*params) {
762                 if (*params != ' ')
763                         return -EINVAL;
764                 params++;
765
766                 /* Number of arguments */
767                 val64 = strtoull(params, &params, 10);
768                 if (*params != ' ')
769                         return -EINVAL;
770                 params++;
771
772                 for (i = 0; i < val64; i++) {
773                         if (!params)
774                                 return -EINVAL;
775                         arg = strsep(&params, " ");
776                         if (!strcasecmp(arg, "allow_discards"))
777                                 dmd->flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS;
778                         else /* unknown option */
779                                 return -EINVAL;
780                 }
781
782                 /* All parameters shold be processed */
783                 if (params)
784                         return -EINVAL;
785         }
786
787         /* Never allow to return empty key */
788         if ((get_flags & DM_ACTIVE_CRYPT_KEY) && dmi->suspended) {
789                 log_dbg("Cannot read volume key while suspended.");
790                 return -EINVAL;
791         }
792
793         if (get_flags & DM_ACTIVE_CRYPT_KEYSIZE) {
794                 dmd->u.crypt.vk = crypt_alloc_volume_key(strlen(key_) / 2, NULL);
795                 if (!dmd->u.crypt.vk)
796                         return -ENOMEM;
797
798                 if (get_flags & DM_ACTIVE_CRYPT_KEY) {
799                         buffer[2] = '\0';
800                         for(i = 0; i < dmd->u.crypt.vk->keylength; i++) {
801                                 memcpy(buffer, &key_[i * 2], 2);
802                                 dmd->u.crypt.vk->key[i] = strtoul(buffer, &endp, 16);
803                                 if (endp != &buffer[2]) {
804                                         crypt_free_volume_key(dmd->u.crypt.vk);
805                                         dmd->u.crypt.vk = NULL;
806                                         return -EINVAL;
807                                 }
808                         }
809                 }
810         }
811         memset(key_, 0, strlen(key_));
812
813         return 0;
814 }
815
816 static int _dm_query_verity(uint32_t get_flags,
817                              struct dm_info *dmi,
818                              char *params,
819                              struct crypt_dm_active_device *dmd)
820 {
821         struct crypt_params_verity *vp = NULL;
822         uint32_t val32;
823         uint64_t val64;
824         size_t len;
825         char *str, *str2;
826
827         if (get_flags & DM_ACTIVE_VERITY_PARAMS)
828                 vp = dmd->u.verity.vp;
829
830         memset(dmd, 0, sizeof(*dmd));
831
832         dmd->target = DM_VERITY;
833         dmd->u.verity.vp = vp;
834
835         /* version */
836         val32 = strtoul(params, &params, 10);
837         if (*params != ' ')
838                 return -EINVAL;
839         if (vp)
840                 vp->version = val32;
841         params++;
842
843         /* data device */
844         str = strsep(&params, " ");
845         if (!params)
846                 return -EINVAL;
847         if (get_flags & DM_ACTIVE_DEVICE)
848                 dmd->data_device = crypt_lookup_dev(str);
849
850         /* hash device */
851         str = strsep(&params, " ");
852         if (!params)
853                 return -EINVAL;
854         if (get_flags & DM_ACTIVE_VERITY_HASH_DEVICE)
855                 dmd->u.verity.hash_device = crypt_lookup_dev(str);
856
857         /* data block size*/
858         val32 = strtoul(params, &params, 10);
859         if (*params != ' ')
860                 return -EINVAL;
861         if (vp)
862                 vp->data_block_size = val32;
863         params++;
864
865         /* hash block size */
866         val32 = strtoul(params, &params, 10);
867         if (*params != ' ')
868                 return -EINVAL;
869         if (vp)
870                 vp->hash_block_size = val32;
871         params++;
872
873         /* data blocks */
874         val64 = strtoull(params, &params, 10);
875         if (*params != ' ')
876                 return -EINVAL;
877         if (vp)
878                 vp->data_size = val64;
879         params++;
880
881         /* hash start */
882         val64 = strtoull(params, &params, 10);
883         if (*params != ' ')
884                 return -EINVAL;
885         dmd->u.verity.hash_offset = val64;
886         params++;
887
888         /* hash algorithm */
889         str = strsep(&params, " ");
890         if (!params)
891                 return -EINVAL;
892         if (vp)
893                 vp->hash_name = strdup(str);
894
895         /* root digest */
896         str = strsep(&params, " ");
897         if (!params)
898                 return -EINVAL;
899         len = strlen(str) / 2;
900         dmd->u.verity.root_hash_size = len;
901         if (get_flags & DM_ACTIVE_VERITY_ROOT_HASH) {
902                 if (!(str2 = malloc(len)))
903                         return -ENOMEM;
904                 if (hex_to_bytes(str, str2) != len)
905                         return -EINVAL;
906                 dmd->u.verity.root_hash = str2;
907         }
908
909         /* salt */
910         str = strsep(&params, " ");
911         if (params)
912                 return -EINVAL;
913         if (vp) {
914                 len = strlen(str) / 2;
915                 vp->salt_size = len;
916                 if (!(str2 = malloc(len)))
917                         return -ENOMEM;
918                 if (hex_to_bytes(str, str2) != len)
919                         return -EINVAL;
920                 vp->salt = str2;
921         }
922
923         return 0;
924 }
925
926 int dm_query_device(const char *name, uint32_t get_flags,
927                     struct crypt_dm_active_device *dmd)
928 {
929         struct dm_task *dmt;
930         struct dm_info dmi;
931         uint64_t start, length;
932         char *target_type, *params;
933         const char *tmp_uuid;
934         void *next = NULL;
935         int r = -EINVAL;
936
937         if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
938                 goto out;
939         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
940                 goto out;
941         if (!dm_task_set_name(dmt, name))
942                 goto out;
943         r = -ENODEV;
944         if (!dm_task_run(dmt))
945                 goto out;
946
947         r = -EINVAL;
948         if (!dm_task_get_info(dmt, &dmi))
949                 goto out;
950
951         if (!dmi.exists) {
952                 r = -ENODEV;
953                 goto out;
954         }
955
956         next = dm_get_next_target(dmt, next, &start, &length,
957                                   &target_type, &params);
958
959         if (!target_type || start != 0 || next)
960                 goto out;
961
962         if (!strcmp(target_type, DM_CRYPT_TARGET))
963                 r = _dm_query_crypt(get_flags, &dmi, params, dmd);
964         else if (!strcmp(target_type, DM_VERITY_TARGET))
965                 r = _dm_query_verity(get_flags, &dmi, params, dmd);
966         else
967                 r = -EINVAL;
968
969         if (r < 0)
970                 goto out;
971
972         dmd->size = length;
973
974         if (dmi.read_only)
975                 dmd->flags |= CRYPT_ACTIVATE_READONLY;
976
977         tmp_uuid = dm_task_get_uuid(dmt);
978         if (!tmp_uuid)
979                 dmd->flags |= CRYPT_ACTIVATE_NO_UUID;
980         else if (get_flags & DM_ACTIVE_UUID) {
981                 if (!strncmp(tmp_uuid, DM_UUID_PREFIX, DM_UUID_PREFIX_LEN))
982                         dmd->uuid = strdup(tmp_uuid + DM_UUID_PREFIX_LEN);
983         }
984
985         r = (dmi.open_count > 0);
986 out:
987         if (dmt)
988                 dm_task_destroy(dmt);
989
990         return r;
991 }
992
993 static int _dm_message(const char *name, const char *msg)
994 {
995         int r = 0;
996         struct dm_task *dmt;
997
998         if (!(dmt = dm_task_create(DM_DEVICE_TARGET_MSG)))
999                 return 0;
1000
1001         if ((dm_flags() & DM_SECURE_SUPPORTED) && !dm_task_secure_data(dmt))
1002                 goto out;
1003
1004         if (name && !dm_task_set_name(dmt, name))
1005                 goto out;
1006
1007         if (!dm_task_set_sector(dmt, (uint64_t) 0))
1008                 goto out;
1009
1010         if (!dm_task_set_message(dmt, msg))
1011                 goto out;
1012
1013         r = dm_task_run(dmt);
1014
1015       out:
1016         dm_task_destroy(dmt);
1017         return r;
1018 }
1019
1020 int dm_suspend_and_wipe_key(const char *name)
1021 {
1022         if (!_dm_check_versions())
1023                 return -ENOTSUP;
1024
1025         if (!(_dm_crypt_flags & DM_KEY_WIPE_SUPPORTED))
1026                 return -ENOTSUP;
1027
1028         if (!_dm_simple(DM_DEVICE_SUSPEND, name, 0))
1029                 return -EINVAL;
1030
1031         if (!_dm_message(name, "key wipe")) {
1032                 _dm_simple(DM_DEVICE_RESUME, name, 1);
1033                 return -EINVAL;
1034         }
1035
1036         return 0;
1037 }
1038
1039 int dm_resume_and_reinstate_key(const char *name,
1040                                 size_t key_size,
1041                                 const char *key)
1042 {
1043         int msg_size = key_size * 2 + 10; // key set <key>
1044         char *msg;
1045         int r = 0;
1046
1047         if (!_dm_check_versions())
1048                 return -ENOTSUP;
1049
1050         if (!(_dm_crypt_flags & DM_KEY_WIPE_SUPPORTED))
1051                 return -ENOTSUP;
1052
1053         msg = crypt_safe_alloc(msg_size);
1054         if (!msg)
1055                 return -ENOMEM;
1056
1057         memset(msg, 0, msg_size);
1058         strcpy(msg, "key set ");
1059         hex_key(&msg[8], key_size, key);
1060
1061         if (!_dm_message(name, msg) ||
1062             !_dm_simple(DM_DEVICE_RESUME, name, 1))
1063                 r = -EINVAL;
1064
1065         crypt_safe_free(msg);
1066         return r;
1067 }
1068
1069 const char *dm_get_dir(void)
1070 {
1071         return dm_dir();
1072 }
1073
1074 int dm_is_dm_device(int major, int minor)
1075 {
1076         return dm_is_dm_major((uint32_t)major);
1077 }
1078
1079 int dm_is_dm_kernel_name(const char *name)
1080 {
1081         return strncmp(name, "dm-", 3) ? 0 : 1;
1082 }
1083
1084 int dm_check_segment(const char *name, uint64_t offset, uint64_t size)
1085 {
1086         struct crypt_dm_active_device dmd;
1087         int r;
1088
1089         log_dbg("Checking segments for device %s.", name);
1090
1091         r = dm_query_device(name, 0, &dmd);
1092         if (r < 0)
1093                 return r;
1094
1095         if (offset >= (dmd.u.crypt.offset + dmd.size) ||
1096            (offset + size) <= dmd.u.crypt.offset)
1097                 r = 0;
1098         else
1099                 r = -EBUSY;
1100
1101         log_dbg("seg: %" PRIu64 " - %" PRIu64 ", new %" PRIu64 " - %" PRIu64 "%s",
1102                dmd.u.crypt.offset, dmd.u.crypt.offset + dmd.size, offset, offset + size,
1103                r ? " (overlapping)" : " (ok)");
1104
1105         return r;
1106 }