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