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