10 #include <sys/types.h>
12 #include <sys/ioctl.h>
16 #include <sys/resource.h>
18 #include "libcryptsetup.h"
21 static char *error=NULL;
23 void set_error_va(const char *fmt, va_list va)
34 r = vasprintf(&error, fmt, va);
41 if (r && error[r - 1] == '\n')
45 void set_error(const char *fmt, ...)
50 set_error_va(fmt, va);
54 const char *get_error(void)
59 static int get_alignment(int fd)
61 int alignment = DEFAULT_MEM_ALIGNMENT;
63 #ifdef _PC_REC_XFER_ALIGN
64 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
66 alignment = DEFAULT_MEM_ALIGNMENT;
71 static void *aligned_malloc(void **base, int size, int alignment)
73 #ifdef HAVE_POSIX_MEMALIGN
74 return posix_memalign(base, alignment, size) ? NULL : *base;
76 /* Credits go to Michal's padlock patches for this alignment code */
79 ptr = malloc(size + alignment);
80 if(ptr == NULL) return NULL;
83 if(alignment > 1 && ((long)ptr & (alignment - 1))) {
84 ptr += alignment - ((long)(ptr) & (alignment - 1));
89 static int sector_size(int fd)
92 if (ioctl(fd,BLKSSZGET, &bsize) < 0)
98 int sector_size_for_device(const char *device)
100 int fd = open(device, O_RDONLY);
109 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
111 void *hangover_buf, *hangover_buf_base = NULL;
112 void *buf, *buf_base = NULL;
113 int r, hangover, solid, bsize, alignment;
116 if ((bsize = sector_size(fd)) < 0)
119 hangover = count % bsize;
120 solid = count - hangover;
121 alignment = get_alignment(fd);
123 if ((long)orig_buf & (alignment - 1)) {
124 buf = aligned_malloc(&buf_base, count, alignment);
127 memcpy(buf, orig_buf, count);
129 buf = (void *)orig_buf;
131 r = write(fd, buf, solid);
132 if (r < 0 || r != solid)
136 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
140 r = read(fd, hangover_buf, bsize);
141 if(r < 0 || r != bsize) goto out;
143 r = lseek(fd, -bsize, SEEK_CUR);
146 memcpy(hangover_buf, buf + solid, hangover);
148 r = write(fd, hangover_buf, bsize);
149 if(r < 0 || r != bsize) goto out;
150 free(hangover_buf_base);
159 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
160 void *hangover_buf, *hangover_buf_base;
161 void *buf, *buf_base = NULL;
162 int r, hangover, solid, bsize, alignment;
165 if ((bsize = sector_size(fd)) < 0)
168 hangover = count % bsize;
169 solid = count - hangover;
170 alignment = get_alignment(fd);
172 if ((long)orig_buf & (alignment - 1)) {
173 buf = aligned_malloc(&buf_base, count, alignment);
179 r = read(fd, buf, solid);
180 if(r < 0 || r != solid)
184 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
187 r = read(fd, hangover_buf, bsize);
188 if (r < 0 || r != bsize)
191 memcpy(buf + solid, hangover_buf, hangover);
192 free(hangover_buf_base);
196 if (buf != orig_buf) {
197 memcpy(orig_buf, buf, count);
204 * Combines llseek with blockwise write. write_blockwise can already deal with short writes
205 * but we also need a function to deal with short writes at the start. But this information
206 * is implicitly included in the read/write offset, which can not be set to non-aligned
207 * boundaries. Hence, we combine llseek with write.
210 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
211 int bsize = sector_size(fd);
212 const char *orig_buf = buf;
213 char frontPadBuf[bsize];
214 int frontHang = offset % bsize;
216 int innerCount = count < bsize ? count : bsize;
221 lseek(fd, offset - frontHang, SEEK_SET);
223 r = read(fd,frontPadBuf,bsize);
226 memcpy(frontPadBuf+frontHang, buf, innerCount);
228 lseek(fd, offset - frontHang, SEEK_SET);
229 r = write(fd,frontPadBuf,bsize);
235 if(count <= 0) return buf - orig_buf;
237 return write_blockwise(fd, buf, count) + innerCount;
240 /* Password reading helpers */
242 static int untimed_read(int fd, char *pass, size_t maxlen)
246 i = read(fd, pass, maxlen);
250 } else if (i == 0) { /* EOF */
257 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
268 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
269 failed = untimed_read(fd, pass, maxlen);
274 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
277 struct termios orig, tmp;
279 int infd = STDIN_FILENO, outfd;
284 /* Read and write to /dev/tty if available */
285 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
287 outfd = STDERR_FILENO;
290 if (tcgetattr(infd, &orig))
293 memcpy(&tmp, &orig, sizeof(tmp));
294 tmp.c_lflag &= ~ECHO;
296 if (write(outfd, prompt, strlen(prompt)) < 0)
299 tcsetattr(infd, TCSAFLUSH, &tmp);
301 failed = timed_read(infd, pass, maxlen, timeout);
303 failed = untimed_read(infd, pass, maxlen);
304 tcsetattr(infd, TCSAFLUSH, &orig);
307 if (!failed && write(outfd, "\n", 1));
309 if (infd != STDIN_FILENO)
315 * Password reading behaviour matrix of get_key
316 * FIXME: rewrite this from scratch.
318 * -----------------+---+---+---+---
319 * interactive | Y | Y | Y | Inf
320 * from fd | N | N | Y | Inf
321 * from binary file | N | N | N | Inf or options->key_size
323 * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
325 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
328 void get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
329 const char *key_file, int timeout, int how2verify,
330 struct crypt_device *cd)
333 const int verify = how2verify & CRYPT_FLAG_VERIFY;
334 const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
337 int regular_file = 0;
342 /* Passphrase read from stdin? */
343 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
345 /* read_horizon applies only for real keyfile, not stdin or terminal */
346 read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
348 /* Setup file descriptior */
349 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
351 log_err(cd, _("Failed to open key file %s.\n"), key_file ?: "-");
355 /* Interactive case */
359 pass = crypt_safe_alloc(MAX_TTY_PASSWORD_LEN);
360 if (!pass || (i = interactive_pass(prompt, pass, MAX_TTY_PASSWORD_LEN, timeout))) {
361 log_err(cd, _("Error reading passphrase from terminal.\n"));
364 if (verify || verify_if_possible) {
365 char pass_verify[MAX_TTY_PASSWORD_LEN];
366 i = interactive_pass(_("Verify passphrase: "), pass_verify, sizeof(pass_verify), timeout);
367 if (i || strcmp(pass, pass_verify) != 0) {
368 log_err(cd, _("Passphrases do not match.\n"));
371 memset(pass_verify, 0, sizeof(pass_verify));
373 *passLen = strlen(pass);
377 * This is either a fd-input or a file, in neither case we can verify the input,
378 * however we don't stop on new lines if it's a binary file.
383 log_err(cd, _("Can't do passphrase verification on non-tty inputs.\n"));
386 /* The following for control loop does an exhausting
387 * read on the key material file, if requested with
388 * key_size == 0, as it's done by LUKS. However, we
389 * should warn the user, if it's a non-regular file,
390 * such as /dev/random, because in this case, the loop
393 if(!read_stdin && read_horizon == 0) {
394 if(stat(key_file, &st) < 0) {
395 log_err(cd, _("Failed to stat key file %s.\n"), key_file);
398 if(!S_ISREG(st.st_mode))
399 log_std(cd, _("Warning: exhausting read requested, but key file %s"
400 " is not a regular file, function might never return.\n"),
406 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
407 if(i >= buflen - 1) {
409 pass = crypt_safe_realloc(pass, buflen);
411 log_err(cd, _("Out of memory while reading passphrase.\n"));
416 r = read(fd, pass + i, 1);
418 log_err(cd, _("Error reading passphrase.\n"));
422 /* Stop on newline only if not requested read from keyfile */
423 if(r == 0 || (!key_file && pass[i] == '\n'))
426 /* Fail if piped input dies reading nothing */
427 if(!i && !regular_file) {
428 log_dbg("Error reading passphrase.");
435 if(fd != STDIN_FILENO)
440 if(fd >= 0 && fd != STDIN_FILENO)
443 crypt_safe_free(pass);
448 int device_ready(struct crypt_device *cd, const char *device, int mode)
455 if(stat(device, &st) < 0) {
456 log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
460 log_dbg("Trying to open and read device %s.", device);
461 devfd = open(device, mode | O_DIRECT | O_SYNC);
463 log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
464 (mode & O_EXCL) ? _("exclusive ") : "",
465 (mode & O_RDWR) ? _("writable") : _("read-only"));
469 /* Try to read first sector */
470 s = read_blockwise(devfd, buf, sizeof(buf));
471 if (s < 0 || s != sizeof(buf)) {
472 log_err(cd, _("Cannot read device %s.\n"), device);
476 memset(buf, 0, sizeof(buf));
482 int get_device_infos(const char *device, struct device_infos *infos, struct crypt_device *cd)
485 unsigned long size_small;
490 /* Try to open read-write to check whether it is a read-only device */
491 fd = open(device, O_RDWR);
493 if (errno == EROFS) {
495 fd = open(device, O_RDONLY);
499 fd = open(device, O_RDONLY);
502 log_err(cd, _("Cannot open device: %s\n"), device);
507 /* If the device can be opened read-write, i.e. readonly is still 0, then
508 * check whether BKROGET says that it is read-only. E.g. read-only loop
509 * devices may be openend read-write but are read-only according to BLKROGET
511 if (readonly == 0 && ioctl(fd, BLKROGET, &readonly) < 0) {
512 log_err(cd, _("BLKROGET failed on device %s.\n"), device);
516 #error BLKROGET not available
520 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
521 size >>= SECTOR_SHIFT;
528 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
529 size = (uint64_t)size_small;
534 # error Need at least the BLKGETSIZE ioctl!
537 log_err(cd, _("BLKGETSIZE failed on device %s.\n"), device);
541 infos->readonly = readonly;
547 int wipe_device_header(const char *device, int sectors)
550 int size = sectors * SECTOR_SIZE;
554 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
558 buffer = malloc(size);
563 memset(buffer, 0, size);
565 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
574 #define DEFAULT_PROCESS_PRIORITY -18
576 static int _priority;
577 static int _memlock_count = 0;
579 // return 1 if memory is locked
580 int crypt_memlock_inc(struct crypt_device *ctx)
582 if (!_memlock_count++) {
583 log_dbg("Locking memory.");
584 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
585 log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
590 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
591 log_err(ctx, _("Cannot get process priority.\n"));
593 if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
594 log_err(ctx, _("setpriority %u failed: %s"),
595 DEFAULT_PROCESS_PRIORITY, strerror(errno));
597 return _memlock_count ? 1 : 0;
600 int crypt_memlock_dec(struct crypt_device *ctx)
602 if (_memlock_count && (!--_memlock_count)) {
603 log_dbg("Unlocking memory.");
605 log_err(ctx, _("Cannot unlock memory."));
606 if (setpriority(PRIO_PROCESS, 0, _priority))
607 log_err(ctx, _("setpriority %u failed: %s"), _priority, strerror(errno));
609 return _memlock_count ? 1 : 0;
612 /* DEVICE TOPOLOGY */
614 /* block device topology ioctls, introduced in 2.6.32 */
616 #define BLKIOMIN _IO(0x12,120)
617 #define BLKIOOPT _IO(0x12,121)
618 #define BLKALIGNOFF _IO(0x12,122)
621 void get_topology_alignment(const char *device,
622 unsigned long *required_alignment, /* bytes */
623 unsigned long *alignment_offset, /* bytes */
624 unsigned long default_alignment)
626 int dev_alignment_offset = 0;
627 unsigned int min_io_size = 0, opt_io_size = 0;
628 unsigned long temp_alignment = 0;
631 *required_alignment = default_alignment;
632 *alignment_offset = 0;
634 fd = open(device, O_RDONLY);
638 /* minimum io size */
639 if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
640 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
641 device, default_alignment);
645 /* optimal io size */
646 if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
647 opt_io_size = min_io_size;
649 /* alignment offset, bogus -1 means misaligned/unknown */
650 if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || dev_alignment_offset < 0)
651 dev_alignment_offset = 0;
652 *alignment_offset = (unsigned long)dev_alignment_offset;
654 temp_alignment = (unsigned long)min_io_size;
656 if (temp_alignment < (unsigned long)opt_io_size)
657 temp_alignment = (unsigned long)opt_io_size;
659 /* If calculated alignment is multiple of default, keep default */
660 if (temp_alignment && (default_alignment % temp_alignment))
661 *required_alignment = temp_alignment;
663 log_dbg("Topology: IO (%u/%u), offset = %lu; Required alignment is %lu bytes.",
664 min_io_size, opt_io_size, *alignment_offset, *required_alignment);