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