1 #include <machine/inttypes.h>
2 #include <sys/ioctl.h>
3 #include <sys/param.h>
4 #include <sys/stat.h>
5 #include <stdio.h>
6 #include <string.h>
7 #include <stdlib.h>
8 #include <dirent.h>
9 #include <errno.h>
10 #include <libdm.h>
11 #include <fcntl.h>
12 #include <uuid.h>
13 
14 #include "internal.h"
15 #include "luks.h"
16 
17 #define DEVICE_DIR		"/dev"
18 #define DM_UUID_LEN		129
19 #define DM_UUID_PREFIX		"CRYPT-"
20 #define DM_UUID_PREFIX_LEN	6
21 #define DM_CRYPT_TARGET		"crypt"
22 #define RETRY_COUNT		5
23 
24 /* Set if dm-crypt version was probed */
25 static int _dm_crypt_checked = 0;
26 static int _dm_crypt_wipe_key_supported = 0;
27 
28 static int _dm_use_count = 0;
29 static struct crypt_device *_context = NULL;
30 
31 /* Compatibility for old device-mapper without udev support */
32 #ifndef HAVE_DM_TASK_SET_COOKIE
33 #define CRYPT_TEMP_UDEV_FLAGS	0
34 #else
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 #endif
39 
40 static int _dm_use_udev()
41 {
42 #ifdef USE_UDEV /* cannot be enabled if devmapper is too old */
43 	return dm_udev_get_sync_support();
44 #else
45 	return 0;
46 #endif
47 }
48 
49 static void set_dm_error(int level, const char *file, int line,
50 			 const char *f, ...)
51 {
52 	char *msg = NULL;
53 	va_list va;
54 
55 	va_start(va, f);
56 	if (vasprintf(&msg, f, va) > 0) {
57 		if (level < 4) {
58 			log_err(_context, msg);
59 			log_err(_context, "\n");
60 		} else
61 			log_dbg(msg);
62 	}
63 	free(msg);
64 	va_end(va);
65 }
66 
67 static int _dm_simple(int task, const char *name, int udev_wait);
68 
69 static void _dm_set_crypt_compat(int maj, int min, int patch)
70 {
71 	log_dbg("Detected dm-crypt target of version %i.%i.%i.", maj, min, patch);
72 
73 	if (maj >= 1 && min >=2)
74 		_dm_crypt_wipe_key_supported = 1;
75 	else
76 		log_dbg("Suspend and resume disabled, no wipe key support.");
77 
78 	_dm_crypt_checked = 1;
79 }
80 
81 static int _dm_check_versions(void)
82 {
83 	struct dm_task *dmt;
84 	struct dm_versions *target, *last_target;
85 
86 	if (_dm_crypt_checked)
87 		return 1;
88 
89 	if (!(dmt = dm_task_create(DM_DEVICE_LIST_VERSIONS)))
90 		return 0;
91 
92 	if (!dm_task_run(dmt)) {
93 		dm_task_destroy(dmt);
94 		return 0;
95 	}
96 
97 	target = dm_task_get_versions(dmt);
98 	do {
99 		last_target = target;
100 		if (!strcmp(DM_CRYPT_TARGET, target->name)) {
101 			_dm_set_crypt_compat((int)target->version[0],
102 					     (int)target->version[1],
103 					     (int)target->version[2]);
104 		}
105 		target = (void *) target + target->next;
106 	} while (last_target != target);
107 
108 	dm_task_destroy(dmt);
109 	return 1;
110 }
111 
112 int dm_init(struct crypt_device *context, int check_kernel)
113 {
114 	if (!_dm_use_count++) {
115 		log_dbg("Initialising device-mapper backend%s, UDEV is %sabled.",
116 			check_kernel ? "" : " (NO kernel check requested)",
117 			_dm_use_udev() ? "en" : "dis");
118 		if (check_kernel && !_dm_check_versions()) {
119 			log_err(context, _("Cannot initialize device-mapper. Is dm kernel module loaded?\n"));
120 			return -1;
121 		}
122 		if (getuid() || geteuid())
123 			log_dbg(("WARNING: Running as a non-root user. Functionality may be unavailable."));
124 		dm_log_init(set_dm_error);
125 		dm_log_init_verbose(10);
126 	}
127 
128 	// FIXME: global context is not safe
129 	if (context)
130 		_context = context;
131 
132 	return 1;	/* unsafe memory */
133 }
134 
135 void dm_exit(void)
136 {
137 	if (_dm_use_count && (!--_dm_use_count)) {
138 		log_dbg("Releasing device-mapper backend.");
139 		dm_log_init_verbose(0);
140 		dm_log_init(NULL);
141 		dm_lib_release();
142 		_context = NULL;
143 	}
144 }
145 
146 static char *__lookup_dev(char *path, dev_t dev, int dir_level, const int max_level)
147 {
148 	struct dirent *entry;
149 	struct stat st;
150 	char *ptr;
151 	char *result = NULL;
152 	DIR *dir;
153 	int space;
154 
155 	/* Ignore strange nested directories */
156 	if (dir_level > max_level)
157 		return NULL;
158 
159 	path[PATH_MAX - 1] = '\0';
160 	ptr = path + strlen(path);
161 	*ptr++ = '/';
162 	*ptr = '\0';
163 	space = PATH_MAX - (ptr - path);
164 
165 	dir = opendir(path);
166 	if (!dir)
167 		return NULL;
168 
169 	while((entry = readdir(dir))) {
170 		if (entry->d_name[0] == '.' ||
171 		    !strncmp(entry->d_name, "..", 2))
172 			continue;
173 
174 		strncpy(ptr, entry->d_name, space);
175 		if (stat(path, &st) < 0)
176 			continue;
177 
178 		if (S_ISDIR(st.st_mode)) {
179 			result = __lookup_dev(path, dev, dir_level + 1, max_level);
180 			if (result)
181 				break;
182 		} else if (S_ISBLK(st.st_mode)) {
183 			/* workaround: ignore dm-X devices, these are internal kernel names */
184 			if (dir_level == 0 && !strncmp(entry->d_name, "dm-", 3))
185 				continue;
186 			if (st.st_rdev == dev) {
187 				result = strdup(path);
188 				break;
189 			}
190 		}
191 	}
192 
193 	closedir(dir);
194 	return result;
195 }
196 
197 static char *lookup_dev(const char *dev_id)
198 {
199 	uint32_t major, minor;
200 	dev_t dev;
201 	char *result = NULL, buf[PATH_MAX + 1];
202 
203 	if (sscanf(dev_id, "%" PRIu32 ":%" PRIu32, &major, &minor) != 2)
204 		return NULL;
205 
206 	dev = makedev(major, minor);
207 	strncpy(buf, DEVICE_DIR, PATH_MAX);
208 	buf[PATH_MAX] = '\0';
209 
210 	/* First try low level device */
211 	if ((result = __lookup_dev(buf, dev, 0, 0)))
212 		return result;
213 
214 	/* If it is dm, try DM dir  */
215 	if (dm_is_dm_major(major)) {
216 		strncpy(buf, dm_dir(), PATH_MAX);
217 		if ((result = __lookup_dev(buf, dev, 0, 0)))
218 			return result;
219 	}
220 
221 	strncpy(buf, DEVICE_DIR, PATH_MAX);
222 	result = __lookup_dev(buf, dev, 0, 4);
223 
224 	/* If not found, return NULL */
225 	return result;
226 }
227 
228 static int _dev_read_ahead(const char *dev, uint32_t *read_ahead)
229 {
230 	int fd, r = 0;
231 	long read_ahead_long;
232 
233 	if ((fd = open(dev, O_RDONLY)) < 0)
234 		return 0;
235 
236 	r = 0;
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 	uint32_t ret;
392 
393 	/* Remove '-' chars */
394 	if (uuid) {
395 		uuid_from_string(uuid, &uu, &ret);
396 		if (ret != uuid_s_ok) {
397 			printf("error in uuid_from_string(%s), err = %d\n", uuid, ret);
398 			for (ptr = uuid2, i = 0; i < UUID_LEN; i++) {
399 				if (uuid[i] != '-') {
400 					*ptr = uuid[i];
401 					ptr++;
402 				}
403 			}
404 		}
405 	}
406 
407 	i = snprintf(buf, buflen, DM_UUID_PREFIX "%s%s%s%s%s",
408 		type ?: "", type ? "-" : "",
409 		uuid2[0] ? uuid2 : "", uuid2[0] ? "-" : "",
410 		name);
411 
412 	log_dbg("DM-UUID is %s", buf);
413 	if (i >= buflen)
414 		log_err(NULL, _("DM-UUID for device %s was truncated.\n"), name);
415 }
416 
417 int dm_create_device(const char *name,
418 		     const char *device,
419 		     const char *cipher,
420 		     const char *type,
421 		     const char *uuid,
422 		     uint64_t size,
423 		     uint64_t skip,
424 		     uint64_t offset,
425 		     size_t key_size,
426 		     const char *key,
427 		     int read_only,
428 		     int reload)
429 {
430 	struct dm_task *dmt = NULL;
431 	struct dm_info dmi;
432 	char *params = NULL;
433 	char *error = NULL;
434 	char dev_uuid[DM_UUID_LEN] = {0};
435 	int r = -EINVAL;
436 	uint32_t read_ahead = 0;
437 	uint32_t cookie = 0;
438 	uint16_t udev_flags = 0;
439 
440 	params = get_params(device, skip, offset, cipher, key_size, key);
441 	if (!params)
442 		goto out_no_removal;
443 
444 	if (type && !strncmp(type, "TEMP", 4))
445 		udev_flags = CRYPT_TEMP_UDEV_FLAGS;
446 
447 	/* All devices must have DM_UUID, only resize on old device is exception */
448 	if (reload) {
449 		if (!(dmt = dm_task_create(DM_DEVICE_RELOAD)))
450 			goto out_no_removal;
451 
452 		if (!dm_task_set_name(dmt, name))
453 			goto out_no_removal;
454 	} else {
455 		dm_prepare_uuid(name, type, uuid, dev_uuid, sizeof(dev_uuid));
456 
457 		if (!(dmt = dm_task_create(DM_DEVICE_CREATE)))
458 			goto out_no_removal;
459 
460 		if (!dm_task_set_name(dmt, name))
461 			goto out_no_removal;
462 
463 		if (!dm_task_set_uuid(dmt, dev_uuid))
464 			goto out_no_removal;
465 
466 		if (_dm_use_udev() && !dm_task_set_cookie(dmt, &cookie, udev_flags))
467 			goto out_no_removal;
468 	}
469 
470 	if (read_only && !dm_task_set_ro(dmt))
471 		goto out_no_removal;
472 	if (!dm_task_add_target(dmt, 0, size, DM_CRYPT_TARGET, params))
473 		goto out_no_removal;
474 
475 #ifdef DM_READ_AHEAD_MINIMUM_FLAG
476 	if (_dev_read_ahead(device, &read_ahead) &&
477 	    !dm_task_set_read_ahead(dmt, read_ahead, DM_READ_AHEAD_MINIMUM_FLAG))
478 		goto out_no_removal;
479 #endif
480 
481 	if (!dm_task_run(dmt))
482 		goto out_no_removal;
483 
484 	if (reload) {
485 		dm_task_destroy(dmt);
486 		if (!(dmt = dm_task_create(DM_DEVICE_RESUME)))
487 			goto out;
488 		if (!dm_task_set_name(dmt, name))
489 			goto out;
490 		if (uuid && !dm_task_set_uuid(dmt, dev_uuid))
491 			goto out;
492 		if (_dm_use_udev() && !dm_task_set_cookie(dmt, &cookie, udev_flags))
493 			goto out;
494 		if (!dm_task_run(dmt))
495 			goto out;
496 	}
497 
498 	if (!dm_task_get_info(dmt, &dmi))
499 		goto out;
500 
501 	r = 0;
502 out:
503 	if (_dm_use_udev()) {
504 		(void)dm_udev_wait(cookie);
505 		cookie = 0;
506 	}
507 
508 	if (r < 0 && !reload) {
509 		if (get_error())
510 			error = strdup(get_error());
511 
512 		dm_remove_device(name, 0, 0);
513 
514 		if (error) {
515 			set_error(error);
516 			free(error);
517 		}
518 	}
519 
520 out_no_removal:
521 	if (cookie && _dm_use_udev())
522 		(void)dm_udev_wait(cookie);
523 
524 	if (params)
525 		safe_free(params);
526 	if (dmt)
527 		dm_task_destroy(dmt);
528 
529 	dm_task_update_nodes();
530 	return r;
531 }
532 
533 int dm_status_device(const char *name)
534 {
535 	struct dm_task *dmt;
536 	struct dm_info dmi;
537 	uint64_t start, length;
538 	char *target_type, *params;
539 	void *next = NULL;
540 	int r = -EINVAL;
541 
542 	if (!(dmt = dm_task_create(DM_DEVICE_STATUS)))
543 		return -EINVAL;
544 
545 	if (!dm_task_set_name(dmt, name)) {
546 		r = -EINVAL;
547 		goto out;
548 	}
549 
550 	if (!dm_task_run(dmt)) {
551 		r = -EINVAL;
552 		goto out;
553 	}
554 
555 	if (!dm_task_get_info(dmt, &dmi)) {
556 		r = -EINVAL;
557 		goto out;
558 	}
559 
560 	if (!dmi.exists) {
561 		r = -ENODEV;
562 		goto out;
563 	}
564 
565 	next = dm_get_next_target(dmt, next, &start, &length,
566 	                          &target_type, &params);
567 	if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
568 	    start != 0 || next)
569 		r = -EINVAL;
570 	else
571 		r = (dmi.open_count > 0);
572 out:
573 	if (dmt)
574 		dm_task_destroy(dmt);
575 
576 	return r;
577 }
578 
579 int dm_query_device(const char *name,
580 		    char **device,
581 		    uint64_t *size,
582 		    uint64_t *skip,
583 		    uint64_t *offset,
584 		    char **cipher,
585 		    int *key_size,
586 		    char **key,
587 		    int *read_only,
588 		    int *suspended,
589 		    char **uuid)
590 {
591 	struct dm_task *dmt;
592 	struct dm_info dmi;
593 	uint64_t start, length, val64;
594 	char *target_type, *params, *rcipher, *key_, *rdevice, *endp, buffer[3], *tmp_uuid;
595 	void *next = NULL;
596 	int i, r = -EINVAL;
597 
598 	if (!(dmt = dm_task_create(DM_DEVICE_TABLE)))
599 		goto out;
600 	if (!dm_task_set_name(dmt, name))
601 		goto out;
602 	r = -ENODEV;
603 	if (!dm_task_run(dmt))
604 		goto out;
605 
606 	r = -EINVAL;
607 	if (!dm_task_get_info(dmt, &dmi))
608 		goto out;
609 
610 	if (!dmi.exists) {
611 		r = -ENODEV;
612 		goto out;
613 	}
614 
615 	next = dm_get_next_target(dmt, next, &start, &length,
616 	                          &target_type, &params);
617 	if (!target_type || strcmp(target_type, DM_CRYPT_TARGET) != 0 ||
618 	    start != 0 || next)
619 		goto out;
620 
621 	if (size)
622 		*size = length;
623 
624 	rcipher = strsep(&params, " ");
625 	/* cipher */
626 	if (cipher)
627 		*cipher = strdup(rcipher);
628 
629 	/* skip */
630 	key_ = strsep(&params, " ");
631 	if (!params)
632 		goto out;
633 	val64 = strtoull(params, &params, 10);
634 	if (*params != ' ')
635 		goto out;
636 	params++;
637 	if (skip)
638 		*skip = val64;
639 
640 	/* device */
641 	rdevice = strsep(&params, " ");
642 	if (device)
643 		*device = lookup_dev(rdevice);
644 
645 	/*offset */
646 	if (!params)
647 		goto out;
648 	val64 = strtoull(params, &params, 10);
649 	if (*params)
650 		goto out;
651 	if (offset)
652 		*offset = val64;
653 
654 	/* key_size */
655 	if (key_size)
656 		*key_size = strlen(key_) / 2;
657 
658 	/* key */
659 	if (key_size && key) {
660 		*key = safe_alloc(*key_size);
661 		if (!*key) {
662 			r = -ENOMEM;
663 			goto out;
664 		}
665 
666 		buffer[2] = '\0';
667 		for(i = 0; i < *key_size; i++) {
668 			memcpy(buffer, &key_[i * 2], 2);
669 			(*key)[i] = strtoul(buffer, &endp, 16);
670 			if (endp != &buffer[2]) {
671 				safe_free(key);
672 				*key = NULL;
673 				goto out;
674 			}
675 		}
676 	}
677 	memset(key_, 0, strlen(key_));
678 
679 	if (read_only)
680 		*read_only = dmi.read_only;
681 
682 	if (suspended)
683 		*suspended = dmi.suspended;
684 
685 	if (uuid && (tmp_uuid = (char*)dm_task_get_uuid(dmt)) &&
686 	    !strncmp(tmp_uuid, DM_UUID_PREFIX, DM_UUID_PREFIX_LEN))
687 		*uuid = strdup(tmp_uuid + DM_UUID_PREFIX_LEN);
688 
689 	r = (dmi.open_count > 0);
690 out:
691 	if (dmt)
692 		dm_task_destroy(dmt);
693 
694 	return r;
695 }
696 
697 static int _dm_message(const char *name, const char *msg)
698 {
699 	int r = 0;
700 	struct dm_task *dmt;
701 
702 	if (!(dmt = dm_task_create(DM_DEVICE_TARGET_MSG)))
703 		return 0;
704 
705 	if (name && !dm_task_set_name(dmt, name))
706 		goto out;
707 
708 	if (!dm_task_set_sector(dmt, (uint64_t) 0))
709 		goto out;
710 
711 	if (!dm_task_set_message(dmt, msg))
712 		goto out;
713 
714 	r = dm_task_run(dmt);
715 
716       out:
717 	dm_task_destroy(dmt);
718 	return r;
719 }
720 
721 int dm_suspend_and_wipe_key(const char *name)
722 {
723 	if (!_dm_check_versions())
724 		return -ENOTSUP;
725 
726 	if (!_dm_crypt_wipe_key_supported)
727 		return -ENOTSUP;
728 
729 	if (!_dm_simple(DM_DEVICE_SUSPEND, name, 0))
730 		return -EINVAL;
731 
732 	if (!_dm_message(name, "key wipe")) {
733 		_dm_simple(DM_DEVICE_RESUME, name, 1);
734 		return -EINVAL;
735 	}
736 
737 	return 0;
738 }
739 
740 int dm_resume_and_reinstate_key(const char *name,
741 				size_t key_size,
742 				const char *key)
743 {
744 	int msg_size = key_size * 2 + 10; // key set <key>
745 	char *msg;
746 	int r = 0;
747 
748 	if (!_dm_check_versions())
749 		return -ENOTSUP;
750 
751 	if (!_dm_crypt_wipe_key_supported)
752 		return -ENOTSUP;
753 
754 	msg = safe_alloc(msg_size);
755 	if (!msg)
756 		return -ENOMEM;
757 
758 	memset(msg, 0, msg_size);
759 	strcpy(msg, "key set ");
760 	hex_key(&msg[8], key_size, key);
761 
762 	if (!_dm_message(name, msg) ||
763 	    !_dm_simple(DM_DEVICE_RESUME, name, 1))
764 		r = -EINVAL;
765 
766 	safe_free(msg);
767 	return r;
768 }
769 
770 const char *dm_get_dir(void)
771 {
772 	return dm_dir();
773 }
774