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