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