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