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