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