Fix previous commit to properly check udev flag definition.
[platform/upstream/cryptsetup.git] / lib / libdevmapper.c
1 #include <sys/ioctl.h>
2 #include <sys/stat.h>
3 #include <stdio.h>
4 #include <dirent.h>
5 #include <errno.h>
6 #include <libdevmapper.h>
7 #include <fcntl.h>
8 #include <linux/fs.h>
9 #include <uuid/uuid.h>
10
11 #include "internal.h"
12 #include "luks.h"
13
14 #define DEVICE_DIR              "/dev"
15 #define DM_UUID_LEN             129
16 #define DM_UUID_PREFIX          "CRYPT-"
17 #define DM_UUID_PREFIX_LEN      6
18 #define DM_CRYPT_TARGET         "crypt"
19 #define RETRY_COUNT             5
20
21 /* Set if dm-crypt version was probed */
22 static int _dm_crypt_checked = 0;
23 static int _dm_crypt_wipe_key_supported = 0;
24
25 static int _dm_use_count = 0;
26 static struct crypt_device *_context = NULL;
27
28 /* Compatibility for old device-mapper without udev support */
29 #if HAVE_DECL_DM_UDEV_DISABLE_DISK_RULES_FLAG
30 #define CRYPT_TEMP_UDEV_FLAGS   DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG | \
31                                 DM_UDEV_DISABLE_DISK_RULES_FLAG | \
32                                 DM_UDEV_DISABLE_OTHER_RULES_FLAG
33 #define _dm_task_set_cookie     dm_task_set_cookie
34 #define _dm_udev_wait           dm_udev_wait
35 #else
36 #define CRYPT_TEMP_UDEV_FLAGS   0
37 static int _dm_task_set_cookie(struct dm_task *dmt, uint32_t *cookie, uint16_t flags) { return 0; }
38 static int _dm_udev_wait(uint32_t cookie) { return 0; };
39 #endif
40
41 static int _dm_use_udev()
42 {
43 #ifdef USE_UDEV /* cannot be enabled if devmapper is too old */
44         return dm_udev_get_sync_support();
45 #else
46         return 0;
47 #endif
48 }
49
50 static void set_dm_error(int level, const char *file, int line,
51                          const char *f, ...)
52 {
53         char *msg = NULL;
54         va_list va;
55
56         va_start(va, f);
57         if (vasprintf(&msg, f, va) > 0) {
58                 if (level < 4) {
59                         log_err(_context, msg);
60                         log_err(_context, "\n");
61                 } else
62                         log_dbg(msg);
63         }
64         free(msg);
65         va_end(va);
66 }
67
68 static int _dm_simple(int task, const char *name, int udev_wait);
69
70 static void _dm_set_crypt_compat(int maj, int min, int patch)
71 {
72         log_dbg("Detected dm-crypt target of version %i.%i.%i.", maj, min, patch);
73
74         if (maj >= 1 && min >=2)
75                 _dm_crypt_wipe_key_supported = 1;
76         else
77                 log_dbg("Suspend and resume disabled, no wipe key support.");
78
79         _dm_crypt_checked = 1;
80 }
81
82 static int _dm_check_versions(void)
83 {
84         struct dm_task *dmt;
85         struct dm_versions *target, *last_target;
86
87         if (_dm_crypt_checked)
88                 return 1;
89
90         if (!(dmt = dm_task_create(DM_DEVICE_LIST_VERSIONS)))
91                 return 0;
92
93         if (!dm_task_run(dmt)) {
94                 dm_task_destroy(dmt);
95                 return 0;
96         }
97
98         target = dm_task_get_versions(dmt);
99         do {
100                 last_target = target;
101                 if (!strcmp(DM_CRYPT_TARGET, target->name)) {
102                         _dm_set_crypt_compat((int)target->version[0],
103                                              (int)target->version[1],
104                                              (int)target->version[2]);
105                 }
106                 target = (void *) target + target->next;
107         } while (last_target != target);
108
109         dm_task_destroy(dmt);
110         return 1;
111 }
112
113 int dm_init(struct crypt_device *context, int check_kernel)
114 {
115         if (!_dm_use_count++) {
116                 log_dbg("Initialising device-mapper backend%s, UDEV is %sabled.",
117                         check_kernel ? "" : " (NO kernel check requested)",
118                         _dm_use_udev() ? "en" : "dis");
119                 if (check_kernel && !_dm_check_versions()) {
120                         log_err(context, _("Cannot initialize device-mapper. Is dm_mod kernel module loaded?\n"));
121                         return -1;
122                 }
123                 if (getuid() || geteuid())
124                         log_dbg(("WARNING: Running as a non-root user. Functionality may be unavailable."));
125                 dm_log_init(set_dm_error);
126                 dm_log_init_verbose(10);
127         }
128
129         // FIXME: global context is not safe
130         if (context)
131                 _context = context;
132
133         return 1;       /* unsafe memory */
134 }
135
136 void dm_exit(void)
137 {
138         if (_dm_use_count && (!--_dm_use_count)) {
139                 log_dbg("Releasing device-mapper backend.");
140                 dm_log_init_verbose(0);
141                 dm_log_init(NULL);
142                 dm_lib_release();
143                 _context = NULL;
144         }
145 }
146
147 static char *__lookup_dev(char *path, dev_t dev, int dir_level, const int max_level)
148 {
149         struct dirent *entry;
150         struct stat st;
151         char *ptr;
152         char *result = NULL;
153         DIR *dir;
154         int space;
155
156         /* Ignore strange nested directories */
157         if (dir_level > max_level)
158                 return NULL;
159
160         path[PATH_MAX - 1] = '\0';
161         ptr = path + strlen(path);
162         *ptr++ = '/';
163         *ptr = '\0';
164         space = PATH_MAX - (ptr - path);
165
166         dir = opendir(path);
167         if (!dir)
168                 return NULL;
169
170         while((entry = readdir(dir))) {
171                 if (entry->d_name[0] == '.' ||
172                     !strncmp(entry->d_name, "..", 2))
173                         continue;
174
175                 strncpy(ptr, entry->d_name, space);
176                 if (stat(path, &st) < 0)
177                         continue;
178
179                 if (S_ISDIR(st.st_mode)) {
180                         result = __lookup_dev(path, dev, dir_level + 1, max_level);
181                         if (result)
182                                 break;
183                 } else if (S_ISBLK(st.st_mode)) {
184                         /* workaround: ignore dm-X devices, these are internal kernel names */
185                         if (dir_level == 0 && !strncmp(entry->d_name, "dm-", 3))
186                                 continue;
187                         if (st.st_rdev == dev) {
188                                 result = strdup(path);
189                                 break;
190                         }
191                 }
192         }
193
194         closedir(dir);
195         return result;
196 }
197
198 static char *lookup_dev(const char *dev_id)
199 {
200         uint32_t major, minor;
201         dev_t dev;
202         char *result = NULL, buf[PATH_MAX + 1];
203
204         if (sscanf(dev_id, "%" PRIu32 ":%" PRIu32, &major, &minor) != 2)
205                 return NULL;
206
207         dev = makedev(major, minor);
208         strncpy(buf, DEVICE_DIR, PATH_MAX);
209         buf[PATH_MAX] = '\0';
210
211         /* First try low level device */
212         if ((result = __lookup_dev(buf, dev, 0, 0)))
213                 return result;
214
215         /* If it is dm, try DM dir  */
216         if (dm_is_dm_major(major)) {
217                 strncpy(buf, dm_dir(), PATH_MAX);
218                 if ((result = __lookup_dev(buf, dev, 0, 0)))
219                         return result;
220         }
221
222         strncpy(buf, DEVICE_DIR, PATH_MAX);
223         result = __lookup_dev(buf, dev, 0, 4);
224
225         /* If not found, return NULL */
226         return result;
227 }
228
229 static int _dev_read_ahead(const char *dev, uint32_t *read_ahead)
230 {
231         int fd, r = 0;
232         long read_ahead_long;
233
234         if ((fd = open(dev, O_RDONLY)) < 0)
235                 return 0;
236
237         r = ioctl(fd, BLKRAGET, &read_ahead_long) ? 0 : 1;
238         close(fd);
239
240         if (r)
241                 *read_ahead = (uint32_t) read_ahead_long;
242
243         return r;
244 }
245
246 static void hex_key(char *hexkey, size_t key_size, const char *key)
247 {
248         int i;
249
250         for(i = 0; i < key_size; i++)
251                 sprintf(&hexkey[i * 2], "%02x", (unsigned char)key[i]);
252 }
253
254 static char *get_params(const char *device, uint64_t skip, uint64_t offset,
255                         const char *cipher, size_t key_size, const char *key)
256 {
257         char *params;
258         char *hexkey;
259
260         hexkey = safe_alloc(key_size * 2 + 1);
261         if (!hexkey)
262                 return NULL;
263
264         hex_key(hexkey, key_size, key);
265
266         params = safe_alloc(strlen(hexkey) + strlen(cipher) + strlen(device) + 64);
267         if (!params)
268                 goto out;
269
270         sprintf(params, "%s %s %" PRIu64 " %s %" PRIu64,
271                 cipher, hexkey, skip, device, offset);
272
273 out:
274         safe_free(hexkey);
275         return params;
276 }
277
278 /* DM helpers */
279 static int _dm_simple(int task, const char *name, int udev_wait)
280 {
281         int r = 0;
282         struct dm_task *dmt;
283         uint32_t cookie = 0;
284
285         if (!_dm_use_udev())
286                 udev_wait = 0;
287
288         if (!(dmt = dm_task_create(task)))
289                 return 0;
290
291         if (name && !dm_task_set_name(dmt, name))
292                 goto out;
293
294         if (udev_wait && !_dm_task_set_cookie(dmt, &cookie, 0))
295                 goto out;
296
297         r = dm_task_run(dmt);
298
299         if (udev_wait)
300                 (void)_dm_udev_wait(cookie);
301
302       out:
303         dm_task_destroy(dmt);
304         return r;
305 }
306
307 static int _error_device(const char *name, size_t size)
308 {
309         struct dm_task *dmt;
310         int r = 0;
311
312         if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
313                 return 0;
314
315         if (!dm_task_set_name(dmt, name))
316                 goto error;
317
318         if (!dm_task_add_target(dmt, UINT64_C(0), size, "error", ""))
319                 goto error;
320
321         if (!dm_task_set_ro(dmt))
322                 goto error;
323
324         if (!dm_task_no_open_count(dmt))
325                 goto error;
326
327         if (!dm_task_run(dmt))
328                 goto error;
329
330         if (!_dm_simple(DM_DEVICE_RESUME, name, 1)) {
331                 _dm_simple(DM_DEVICE_CLEAR, name, 0);
332                 goto error;
333         }
334
335         r = 1;
336
337 error:
338         dm_task_destroy(dmt);
339         return r;
340 }
341
342 int dm_remove_device(const char *name, int force, uint64_t size)
343 {
344         int r = -EINVAL;
345         int retries = force ? RETRY_COUNT : 1;
346         int error_target = 0;
347
348         if (!name || (force && !size))
349                 return -EINVAL;
350
351         do {
352                 r = _dm_simple(DM_DEVICE_REMOVE, name, 1) ? 0 : -EINVAL;
353                 if (--retries && r) {
354                         log_dbg("WARNING: other process locked internal device %s, %s.",
355                                 name, retries ? "retrying remove" : "giving up");
356                         if (force && (crypt_get_debug_level() == CRYPT_LOG_DEBUG))
357                                 debug_processes_using_device(name);
358                         sleep(1);
359                         if (force && !error_target) {
360                                 /* If force flag is set, replace device with error, read-only target.
361                                  * it should stop processes from reading it and also removed underlying
362                                  * device from mapping, so it is usable again.
363                                  * Force flag should be used only for temporary devices, which are
364                                  * intended to work inside cryptsetup only!
365                                  * Anyway, if some process try to read temporary cryptsetup device,
366                                  * it is bug - no other process should try touch it (e.g. udev).
367                                  */
368                                 _error_device(name, size);
369                                 error_target = 1;
370                         }
371                 }
372         } while (r == -EINVAL && retries);
373
374         dm_task_update_nodes();
375
376         return r;
377 }
378
379 #define UUID_LEN 37 /* 36 + \0, libuuid ... */
380 /*
381  * UUID has format: CRYPT-<devicetype>-[<uuid>-]<device name>
382  * CRYPT-PLAIN-name
383  * CRYPT-LUKS1-00000000000000000000000000000000-name
384  * CRYPT-TEMP-name
385  */
386 static void dm_prepare_uuid(const char *name, const char *type, const char *uuid, char *buf, size_t buflen)
387 {
388         char *ptr, uuid2[UUID_LEN] = {0};
389         uuid_t uu;
390         int i = 0;
391
392         /* Remove '-' chars */
393         if (uuid && !uuid_parse(uuid, uu)) {
394                 for (ptr = uuid2, i = 0; i < UUID_LEN; i++)
395                         if (uuid[i] != '-') {
396                                 *ptr = uuid[i];
397                                 ptr++;
398                         }
399         }
400
401         i = snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s%s",
402                 type ?: "", type ? "-" : "",
403                 uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "",
404                 name);
405
406         log_dbg("DM-UUID is %s", buf);
407         if (i >= buflen)
408                 log_err(NULL, _("DM-UUID for device %s was truncated.\n"), name);
409 }
410
411 int dm_create_device(const char *name,
412                      const char *device,
413                      const char *cipher,
414                      const char *type,
415                      const char *uuid,
416                      uint64_t size,
417                      uint64_t skip,
418                      uint64_t offset,
419                      size_t key_size,
420                      const char *key,
421                      int read_only,
422                      int reload)
423 {
424         struct dm_task *dmt = NULL;
425         struct dm_info dmi;
426         char *params = NULL;
427         char *error = NULL;
428         char dev_uuid[DM_UUID_LEN] = {0};
429         int r = -EINVAL;
430         uint32_t read_ahead = 0;
431         uint32_t cookie = 0;
432         uint16_t udev_flags = 0;
433
434         params = get_params(device, skip, offset, cipher, key_size, key);
435         if (!params)
436                 goto out_no_removal;
437
438         if (type && !strncmp(type, "TEMP", 4))
439                 udev_flags = CRYPT_TEMP_UDEV_FLAGS;
440
441         /* All devices must have DM_UUID, only resize on old device is exception */
442         if (reload) {
443                 if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
444                         goto out_no_removal;
445
446                 if (!dm_task_set_name(dmt, name))
447                         goto out_no_removal;
448         } else {
449                 dm_prepare_uuid(name, type, uuid, dev_uuid, sizeof(dev_uuid));
450
451                 if (!(dmt = dm_task_create(DM_DEVICE_CREATE)))
452                         goto out_no_removal;
453
454                 if (!dm_task_set_name(dmt, name))
455                         goto out_no_removal;
456
457                 if (!dm_task_set_uuid(dmt, dev_uuid))
458                         goto out_no_removal;
459
460                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
461                         goto out_no_removal;
462         }
463
464         if (read_only && !dm_task_set_ro(dmt))
465                 goto out_no_removal;
466         if (!dm_task_add_target(dmt, 0, size, DM_CRYPT_TARGET, params))
467                 goto out_no_removal;
468
469 #ifdef DM_READ_AHEAD_MINIMUM_FLAG
470         if (_dev_read_ahead(device, &read_ahead) &&
471             !dm_task_set_read_ahead(dmt, read_ahead, DM_READ_AHEAD_MINIMUM_FLAG))
472                 goto out_no_removal;
473 #endif
474
475         if (!dm_task_run(dmt))
476                 goto out_no_removal;
477
478         if (reload) {
479                 dm_task_destroy(dmt);
480                 if (!(dmt = dm_task_create(DM_DEVICE_RESUME)))
481                         goto out;
482                 if (!dm_task_set_name(dmt, name))
483                         goto out;
484                 if (uuid && !dm_task_set_uuid(dmt, dev_uuid))
485                         goto out;
486                 if (_dm_use_udev() && !_dm_task_set_cookie(dmt, &cookie, udev_flags))
487                         goto out;
488                 if (!dm_task_run(dmt))
489                         goto out;
490         }
491
492         if (!dm_task_get_info(dmt, &dmi))
493                 goto out;
494
495         r = 0;
496 out:
497         if (_dm_use_udev()) {
498                 (void)_dm_udev_wait(cookie);
499                 cookie = 0;
500         }
501
502         if (r < 0 && !reload) {
503                 if (get_error())
504                         error = strdup(get_error());
505
506                 dm_remove_device(name, 0, 0);
507
508                 if (error) {
509                         set_error(error);
510                         free(error);
511                 }
512         }
513
514 out_no_removal:
515         if (cookie && _dm_use_udev())
516                 (void)_dm_udev_wait(cookie);
517
518         if (params)
519                 safe_free(params);
520         if (dmt)
521                 dm_task_destroy(dmt);
522
523         dm_task_update_nodes();
524         return r;
525 }
526
527 int dm_status_device(const char *name)
528 {
529         struct dm_task *dmt;
530         struct dm_info dmi;
531         uint64_t start, length;
532         char *target_type, *params;
533         void *next = NULL;
534         int r = -EINVAL;
535
536         if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
537                 return -EINVAL;
538
539         if (!dm_task_set_name(dmt, name)) {
540                 r = -EINVAL;
541                 goto out;
542         }
543
544         if (!dm_task_run(dmt)) {
545                 r = -EINVAL;
546                 goto out;
547         }
548
549         if (!dm_task_get_info(dmt, &dmi)) {
550                 r = -EINVAL;
551                 goto out;
552         }
553
554         if (!dmi.exists) {
555                 r = -ENODEV;
556                 goto out;
557         }
558
559         next = dm_get_next_target(dmt, next, &start, &length,
560                                   &target_type, &params);
561         if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
562             start != 0 || next)
563                 r = -EINVAL;
564         else
565                 r = (dmi.open_count > 0);
566 out:
567         if (dmt)
568                 dm_task_destroy(dmt);
569
570         return r;
571 }
572
573 int dm_query_device(const char *name,
574                     char **device,
575                     uint64_t *size,
576                     uint64_t *skip,
577                     uint64_t *offset,
578                     char **cipher,
579                     int *key_size,
580                     char **key,
581                     int *read_only,
582                     int *suspended,
583                     char **uuid)
584 {
585         struct dm_task *dmt;
586         struct dm_info dmi;
587         uint64_t start, length, val64;
588         char *target_type, *params, *rcipher, *key_, *rdevice, *endp, buffer[3], *tmp_uuid;
589         void *next = NULL;
590         int i, r = -EINVAL;
591
592         if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
593                 goto out;
594         if (!dm_task_set_name(dmt, name))
595                 goto out;
596         r = -ENODEV;
597         if (!dm_task_run(dmt))
598                 goto out;
599
600         r = -EINVAL;
601         if (!dm_task_get_info(dmt, &dmi))
602                 goto out;
603
604         if (!dmi.exists) {
605                 r = -ENODEV;
606                 goto out;
607         }
608
609         next = dm_get_next_target(dmt, next, &start, &length,
610                                   &target_type, &params);
611         if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
612             start != 0 || next)
613                 goto out;
614
615         if (size)
616                 *size = length;
617
618         rcipher = strsep(&params, " ");
619         /* cipher */
620         if (cipher)
621                 *cipher = strdup(rcipher);
622
623         /* skip */
624         key_ = strsep(&params, " ");
625         if (!params)
626                 goto out;
627         val64 = strtoull(params, &params, 10);
628         if (*params != ' ')
629                 goto out;
630         params++;
631         if (skip)
632                 *skip = val64;
633
634         /* device */
635         rdevice = strsep(&params, " ");
636         if (device)
637                 *device = lookup_dev(rdevice);
638
639         /*offset */
640         if (!params)
641                 goto out;
642         val64 = strtoull(params, &params, 10);
643         if (*params)
644                 goto out;
645         if (offset)
646                 *offset = val64;
647
648         /* key_size */
649         if (key_size)
650                 *key_size = strlen(key_) / 2;
651
652         /* key */
653         if (key_size && key) {
654                 *key = safe_alloc(*key_size);
655                 if (!*key) {
656                         r = -ENOMEM;
657                         goto out;
658                 }
659
660                 buffer[2] = '\0';
661                 for(i = 0; i < *key_size; i++) {
662                         memcpy(buffer, &key_[i * 2], 2);
663                         (*key)[i] = strtoul(buffer, &endp, 16);
664                         if (endp != &buffer[2]) {
665                                 safe_free(key);
666                                 *key = NULL;
667                                 goto out;
668                         }
669                 }
670         }
671         memset(key_, 0, strlen(key_));
672
673         if (read_only)
674                 *read_only = dmi.read_only;
675
676         if (suspended)
677                 *suspended = dmi.suspended;
678
679         if (uuid && (tmp_uuid = (char*)dm_task_get_uuid(dmt)) &&
680             !strncmp(tmp_uuid, DM_UUID_PREFIX, DM_UUID_PREFIX_LEN))
681                 *uuid = strdup(tmp_uuid + DM_UUID_PREFIX_LEN);
682
683         r = (dmi.open_count > 0);
684 out:
685         if (dmt)
686                 dm_task_destroy(dmt);
687
688         return r;
689 }
690
691 static int _dm_message(const char *name, const char *msg)
692 {
693         int r = 0;
694         struct dm_task *dmt;
695
696         if (!(dmt = dm_task_create(DM_DEVICE_TARGET_MSG)))
697                 return 0;
698
699         if (name && !dm_task_set_name(dmt, name))
700                 goto out;
701
702         if (!dm_task_set_sector(dmt, (uint64_t) 0))
703                 goto out;
704
705         if (!dm_task_set_message(dmt, msg))
706                 goto out;
707
708         r = dm_task_run(dmt);
709
710       out:
711         dm_task_destroy(dmt);
712         return r;
713 }
714
715 int dm_suspend_and_wipe_key(const char *name)
716 {
717         if (!_dm_check_versions())
718                 return -ENOTSUP;
719
720         if (!_dm_crypt_wipe_key_supported)
721                 return -ENOTSUP;
722
723         if (!_dm_simple(DM_DEVICE_SUSPEND, name, 0))
724                 return -EINVAL;
725
726         if (!_dm_message(name, "key wipe")) {
727                 _dm_simple(DM_DEVICE_RESUME, name, 1);
728                 return -EINVAL;
729         }
730
731         return 0;
732 }
733
734 int dm_resume_and_reinstate_key(const char *name,
735                                 size_t key_size,
736                                 const char *key)
737 {
738         int msg_size = key_size * 2 + 10; // key set <key>
739         char *msg;
740         int r = 0;
741
742         if (!_dm_check_versions())
743                 return -ENOTSUP;
744
745         if (!_dm_crypt_wipe_key_supported)
746                 return -ENOTSUP;
747
748         msg = safe_alloc(msg_size);
749         if (!msg)
750                 return -ENOMEM;
751
752         memset(msg, 0, msg_size);
753         strcpy(msg, "key set ");
754         hex_key(&msg[8], key_size, key);
755
756         if (!_dm_message(name, msg) ||
757             !_dm_simple(DM_DEVICE_RESUME, name, 1))
758                 r = -EINVAL;
759
760         safe_free(msg);
761         return r;
762 }
763
764 const char *dm_get_dir(void)
765 {
766         return dm_dir();
767 }