10 #include <sys/types.h>
12 #include <sys/ioctl.h>
16 #include <sys/resource.h>
18 #include "libcryptsetup.h"
21 struct safe_allocation {
26 static char *error=NULL;
28 void set_error_va(const char *fmt, va_list va)
39 r = vasprintf(&error, fmt, va);
46 if (r && error[r - 1] == '\n')
50 void set_error(const char *fmt, ...)
55 set_error_va(fmt, va);
59 const char *get_error(void)
64 void *safe_alloc(size_t size)
66 struct safe_allocation *alloc;
71 alloc = malloc(size + offsetof(struct safe_allocation, data));
80 void safe_free(void *data)
82 struct safe_allocation *alloc;
87 alloc = data - offsetof(struct safe_allocation, data);
89 memset(data, 0, alloc->size);
91 alloc->size = 0x55aa55aa;
95 void *safe_realloc(void *data, size_t size)
99 new_data = safe_alloc(size);
101 if (new_data && data) {
102 struct safe_allocation *alloc;
104 alloc = data - offsetof(struct safe_allocation, data);
106 if (size > alloc->size)
109 memcpy(new_data, data, size);
116 char *safe_strdup(const char *s)
118 char *s2 = safe_alloc(strlen(s) + 1);
123 return strcpy(s2, s);
126 static int get_alignment(int fd)
128 int alignment = DEFAULT_ALIGNMENT;
130 #ifdef _PC_REC_XFER_ALIGN
131 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
133 alignment = DEFAULT_ALIGNMENT;
138 static void *aligned_malloc(void **base, int size, int alignment)
140 #ifdef HAVE_POSIX_MEMALIGN
141 return posix_memalign(base, alignment, size) ? NULL : *base;
143 /* Credits go to Michal's padlock patches for this alignment code */
146 ptr = malloc(size + alignment);
147 if(ptr == NULL) return NULL;
150 if(alignment > 1 && ((long)ptr & (alignment - 1))) {
151 ptr += alignment - ((long)(ptr) & (alignment - 1));
156 static int sector_size(int fd)
159 if (ioctl(fd,BLKSSZGET, &bsize) < 0)
165 int sector_size_for_device(const char *device)
167 int fd = open(device, O_RDONLY);
176 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
178 void *hangover_buf, *hangover_buf_base = NULL;
179 void *buf, *buf_base = NULL;
180 int r, hangover, solid, bsize, alignment;
183 if ((bsize = sector_size(fd)) < 0)
186 hangover = count % bsize;
187 solid = count - hangover;
188 alignment = get_alignment(fd);
190 if ((long)orig_buf & (alignment - 1)) {
191 buf = aligned_malloc(&buf_base, count, alignment);
194 memcpy(buf, orig_buf, count);
196 buf = (void *)orig_buf;
198 r = write(fd, buf, solid);
199 if (r < 0 || r != solid)
203 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
207 r = read(fd, hangover_buf, bsize);
208 if(r < 0 || r != bsize) goto out;
210 r = lseek(fd, -bsize, SEEK_CUR);
213 memcpy(hangover_buf, buf + solid, hangover);
215 r = write(fd, hangover_buf, bsize);
216 if(r < 0 || r != bsize) goto out;
217 free(hangover_buf_base);
226 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
227 void *hangover_buf, *hangover_buf_base;
228 void *buf, *buf_base = NULL;
229 int r, hangover, solid, bsize, alignment;
232 if ((bsize = sector_size(fd)) < 0)
235 hangover = count % bsize;
236 solid = count - hangover;
237 alignment = get_alignment(fd);
239 if ((long)orig_buf & (alignment - 1)) {
240 buf = aligned_malloc(&buf_base, count, alignment);
246 r = read(fd, buf, solid);
247 if(r < 0 || r != solid)
251 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
254 r = read(fd, hangover_buf, bsize);
255 if (r < 0 || r != bsize)
258 memcpy(buf + solid, hangover_buf, hangover);
259 free(hangover_buf_base);
263 if (buf != orig_buf) {
264 memcpy(orig_buf, buf, count);
271 * Combines llseek with blockwise write. write_blockwise can already deal with short writes
272 * but we also need a function to deal with short writes at the start. But this information
273 * is implicitly included in the read/write offset, which can not be set to non-aligned
274 * boundaries. Hence, we combine llseek with write.
277 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
278 int bsize = sector_size(fd);
279 const char *orig_buf = buf;
280 char frontPadBuf[bsize];
281 int frontHang = offset % bsize;
283 int innerCount = count < bsize ? count : bsize;
288 lseek(fd, offset - frontHang, SEEK_SET);
290 r = read(fd,frontPadBuf,bsize);
293 memcpy(frontPadBuf+frontHang, buf, innerCount);
295 lseek(fd, offset - frontHang, SEEK_SET);
296 r = write(fd,frontPadBuf,bsize);
302 if(count <= 0) return buf - orig_buf;
304 return write_blockwise(fd, buf, count) + innerCount;
307 /* Password reading helpers */
309 static int untimed_read(int fd, char *pass, size_t maxlen)
313 i = read(fd, pass, maxlen);
317 } else if (i == 0) { /* EOF */
324 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
335 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
336 failed = untimed_read(fd, pass, maxlen);
341 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
344 struct termios orig, tmp;
346 int infd = STDIN_FILENO, outfd;
351 /* Read and write to /dev/tty if available */
352 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
354 outfd = STDERR_FILENO;
357 if (tcgetattr(infd, &orig))
360 memcpy(&tmp, &orig, sizeof(tmp));
361 tmp.c_lflag &= ~ECHO;
363 if (write(outfd, prompt, strlen(prompt)) < 0)
366 tcsetattr(infd, TCSAFLUSH, &tmp);
368 failed = timed_read(infd, pass, maxlen, timeout);
370 failed = untimed_read(infd, pass, maxlen);
371 tcsetattr(infd, TCSAFLUSH, &orig);
374 if (!failed && write(outfd, "\n", 1));
376 if (infd != STDIN_FILENO)
382 * Password reading behaviour matrix of get_key
383 * FIXME: rewrite this from scratch.
385 * -----------------+---+---+---+---
386 * interactive | Y | Y | Y | Inf
387 * from fd | N | N | Y | Inf
388 * from binary file | N | N | N | Inf or options->key_size
390 * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
392 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
395 void get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
396 const char *key_file, int timeout, int how2verify,
397 struct crypt_device *cd)
400 const int verify = how2verify & CRYPT_FLAG_VERIFY;
401 const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
404 int regular_file = 0;
409 /* Passphrase read from stdin? */
410 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
412 /* read_horizon applies only for real keyfile, not stdin or terminal */
413 read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
415 /* Setup file descriptior */
416 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
418 log_err(cd, _("Failed to open key file %s.\n"), key_file ?: "-");
422 /* Interactive case */
426 pass = safe_alloc(MAX_TTY_PASSWORD_LEN);
427 if (!pass || (i = interactive_pass(prompt, pass, MAX_TTY_PASSWORD_LEN, timeout))) {
428 log_err(cd, _("Error reading passphrase from terminal.\n"));
431 if (verify || verify_if_possible) {
432 char pass_verify[MAX_TTY_PASSWORD_LEN];
433 i = interactive_pass(_("Verify passphrase: "), pass_verify, sizeof(pass_verify), timeout);
434 if (i || strcmp(pass, pass_verify) != 0) {
435 log_err(cd, _("Passphrases do not match.\n"));
438 memset(pass_verify, 0, sizeof(pass_verify));
440 *passLen = strlen(pass);
444 * This is either a fd-input or a file, in neither case we can verify the input,
445 * however we don't stop on new lines if it's a binary file.
450 log_err(cd, _("Can't do passphrase verification on non-tty inputs.\n"));
453 /* The following for control loop does an exhausting
454 * read on the key material file, if requested with
455 * key_size == 0, as it's done by LUKS. However, we
456 * should warn the user, if it's a non-regular file,
457 * such as /dev/random, because in this case, the loop
460 if(!read_stdin && read_horizon == 0) {
461 if(stat(key_file, &st) < 0) {
462 log_err(cd, _("Failed to stat key file %s.\n"), key_file);
465 if(!S_ISREG(st.st_mode))
466 log_std(cd, _("Warning: exhausting read requested, but key file %s"
467 " is not a regular file, function might never return.\n"),
473 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
474 if(i >= buflen - 1) {
476 pass = safe_realloc(pass, buflen);
478 log_err(cd, _("Out of memory while reading passphrase.\n"));
483 r = read(fd, pass + i, 1);
485 log_err(cd, _("Error reading passphrase.\n"));
489 /* Stop on newline only if not requested read from keyfile */
490 if(r == 0 || (!key_file && pass[i] == '\n'))
493 /* Fail if piped input dies reading nothing */
494 if(!i && !regular_file) {
495 log_dbg("Error reading passphrase.");
502 if(fd != STDIN_FILENO)
507 if(fd >= 0 && fd != STDIN_FILENO)
515 int device_ready(struct crypt_device *cd, const char *device, int mode)
522 if(stat(device, &st) < 0) {
523 log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
527 log_dbg("Trying to open and read device %s.", device);
528 devfd = open(device, mode | O_DIRECT | O_SYNC);
530 log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
531 (mode & O_EXCL) ? _("exclusive ") : "",
532 (mode & O_RDWR) ? _("writable") : _("read-only"));
536 /* Try to read first sector */
537 s = read_blockwise(devfd, buf, sizeof(buf));
538 if (s < 0 || s != sizeof(buf)) {
539 log_err(cd, _("Cannot read device %s.\n"), device);
543 memset(buf, 0, sizeof(buf));
549 int get_device_infos(const char *device, struct device_infos *infos, struct crypt_device *cd)
552 unsigned long size_small;
557 /* Try to open read-write to check whether it is a read-only device */
558 fd = open(device, O_RDWR);
560 if (errno == EROFS) {
562 fd = open(device, O_RDONLY);
566 fd = open(device, O_RDONLY);
569 log_err(cd, _("Cannot open device: %s\n"), device);
574 /* If the device can be opened read-write, i.e. readonly is still 0, then
575 * check whether BKROGET says that it is read-only. E.g. read-only loop
576 * devices may be openend read-write but are read-only according to BLKROGET
578 if (readonly == 0 && ioctl(fd, BLKROGET, &readonly) < 0) {
579 log_err(cd, _("BLKROGET failed on device %s.\n"), device);
583 #error BLKROGET not available
587 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
588 size >>= SECTOR_SHIFT;
595 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
596 size = (uint64_t)size_small;
601 # error Need at least the BLKGETSIZE ioctl!
604 log_err(cd, _("BLKGETSIZE failed on device %s.\n"), device);
608 infos->readonly = readonly;
614 int wipe_device_header(const char *device, int sectors)
617 int size = sectors * SECTOR_SIZE;
621 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
625 buffer = malloc(size);
630 memset(buffer, 0, size);
632 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
641 #define DEFAULT_PROCESS_PRIORITY -18
643 static int _priority;
644 static int _memlock_count = 0;
646 // return 1 if memory is locked
647 int crypt_memlock_inc(struct crypt_device *ctx)
649 if (!_memlock_count++) {
650 log_dbg("Locking memory.");
651 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
652 log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
657 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
658 log_err(ctx, _("Cannot get process priority.\n"));
660 if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
661 log_err(ctx, _("setpriority %u failed: %s"),
662 DEFAULT_PROCESS_PRIORITY, strerror(errno));
664 return _memlock_count ? 1 : 0;
667 int crypt_memlock_dec(struct crypt_device *ctx)
669 if (_memlock_count && (!--_memlock_count)) {
670 log_dbg("Unlocking memory.");
672 log_err(ctx, _("Cannot unlock memory."));
673 if (setpriority(PRIO_PROCESS, 0, _priority))
674 log_err(ctx, _("setpriority %u failed: %s"), _priority, strerror(errno));
676 return _memlock_count ? 1 : 0;
679 /* DEVICE TOPOLOGY */
681 /* block device topology ioctls, introduced in 2.6.32 */
683 #define BLKIOMIN _IO(0x12,120)
684 #define BLKIOOPT _IO(0x12,121)
685 #define BLKALIGNOFF _IO(0x12,122)
688 void get_topology_alignment(const char *device,
689 unsigned long *required_alignment, /* bytes */
690 unsigned long *alignment_offset, /* bytes */
691 unsigned long default_alignment)
693 unsigned int dev_alignment_offset = 0;
694 unsigned long min_io_size = 0, opt_io_size = 0;
697 *required_alignment = default_alignment;
698 *alignment_offset = 0;
700 fd = open(device, O_RDONLY);
704 /* minimum io size */
705 if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
706 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
707 device, default_alignment);
711 /* optimal io size */
712 if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
713 opt_io_size = min_io_size;
715 /* alignment offset, bogus -1 means misaligned/unknown */
716 if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || (int)dev_alignment_offset < 0)
717 dev_alignment_offset = 0;
719 if (*required_alignment < min_io_size)
720 *required_alignment = min_io_size;
722 if (*required_alignment < opt_io_size)
723 *required_alignment = opt_io_size;
725 *alignment_offset = (unsigned long)dev_alignment_offset;
727 log_dbg("Topology: IO (%lu/%lu), offset = %lu; Required alignment is %lu bytes.",
728 min_io_size, opt_io_size, *alignment_offset, *required_alignment);