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