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