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