11 #include <sys/ioctl.h>
15 #include <sys/resource.h>
16 #include <cpu/param.h>
17 #include <sys/diskslice.h>
19 #include "libcryptsetup.h"
22 struct safe_allocation {
27 static char *error=NULL;
29 void set_error_va(const char *fmt, va_list va)
40 r = vasprintf(&error, fmt, va);
47 if (r && error[r - 1] == '\n')
51 void set_error(const char *fmt, ...)
56 set_error_va(fmt, va);
60 const char *get_error(void)
65 void *safe_alloc(size_t size)
67 struct safe_allocation *alloc;
72 alloc = malloc(size + offsetof(struct safe_allocation, data));
81 void safe_free(void *data)
83 struct safe_allocation *alloc;
88 alloc = data - offsetof(struct safe_allocation, data);
90 memset(data, 0, alloc->size);
92 alloc->size = 0x55aa55aa;
96 void *safe_realloc(void *data, size_t size)
100 new_data = safe_alloc(size);
102 if (new_data && data) {
103 struct safe_allocation *alloc;
105 alloc = data - offsetof(struct safe_allocation, data);
107 if (size > alloc->size)
110 memcpy(new_data, data, size);
117 char *safe_strdup(const char *s)
119 char *s2 = safe_alloc(strlen(s) + 1);
124 return strcpy(s2, s);
127 static int get_alignment(int fd)
129 int alignment = DEFAULT_ALIGNMENT;
131 #ifdef _PC_REC_XFER_ALIGN
132 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
134 alignment = DEFAULT_ALIGNMENT;
139 static void *aligned_malloc(void **base, int size, int alignment)
141 #ifdef HAVE_POSIX_MEMALIGN
142 return posix_memalign(base, alignment, size) ? NULL : *base;
144 /* Credits go to Michal's padlock patches for this alignment code */
147 ptr = malloc(size + alignment);
148 if(ptr == NULL) return NULL;
151 if(alignment > 1 && ((long)ptr & (alignment - 1))) {
152 ptr += alignment - ((long)(ptr) & (alignment - 1));
157 static int sector_size(int fd)
162 if (ioctl(fd,BLKSSZGET, &bsize) < 0)
169 int sector_size_for_device(const char *device)
171 int fd = open(device, O_RDONLY);
180 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
182 void *hangover_buf, *hangover_buf_base = NULL;
183 void *buf, *buf_base = NULL;
184 int r, hangover, solid, bsize, alignment;
187 if ((bsize = sector_size(fd)) < 0)
190 hangover = count % bsize;
191 solid = count - hangover;
192 alignment = get_alignment(fd);
194 if ((long)orig_buf & (alignment - 1)) {
195 buf = aligned_malloc(&buf_base, count, alignment);
198 memcpy(buf, orig_buf, count);
200 buf = (void *)orig_buf;
202 r = write(fd, buf, solid);
203 if (r < 0 || r != solid)
207 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
211 r = read(fd, hangover_buf, bsize);
212 if(r < 0 || r != bsize) goto out;
214 r = lseek(fd, -bsize, SEEK_CUR);
217 memcpy(hangover_buf, buf + solid, hangover);
219 r = write(fd, hangover_buf, bsize);
220 if(r < 0 || r != bsize) goto out;
221 free(hangover_buf_base);
230 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
231 void *hangover_buf, *hangover_buf_base;
232 void *buf, *buf_base = NULL;
233 int r, hangover, solid, bsize, alignment;
236 if ((bsize = sector_size(fd)) < 0)
239 hangover = count % bsize;
240 solid = count - hangover;
241 alignment = get_alignment(fd);
243 if ((long)orig_buf & (alignment - 1)) {
244 buf = aligned_malloc(&buf_base, count, alignment);
250 r = read(fd, buf, solid);
251 if(r < 0 || r != solid)
255 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
258 r = read(fd, hangover_buf, bsize);
259 if (r < 0 || r != bsize)
262 memcpy(buf + solid, hangover_buf, hangover);
263 free(hangover_buf_base);
267 if (buf != orig_buf) {
268 memcpy(orig_buf, buf, count);
275 * Combines llseek with blockwise write. write_blockwise can already deal with short writes
276 * but we also need a function to deal with short writes at the start. But this information
277 * is implicitly included in the read/write offset, which can not be set to non-aligned
278 * boundaries. Hence, we combine llseek with write.
281 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
282 int bsize = sector_size(fd);
283 const char *orig_buf = buf;
284 char frontPadBuf[bsize];
285 int frontHang = offset % bsize;
287 int innerCount = count < bsize ? count : bsize;
292 lseek(fd, offset - frontHang, SEEK_SET);
294 r = read(fd,frontPadBuf,bsize);
297 memcpy(frontPadBuf+frontHang, buf, innerCount);
299 lseek(fd, offset - frontHang, SEEK_SET);
300 r = write(fd,frontPadBuf,bsize);
306 if(count <= 0) return buf - orig_buf;
308 return write_blockwise(fd, buf, count) + innerCount;
311 /* Password reading helpers */
313 static int untimed_read(int fd, char *pass, size_t maxlen)
317 i = read(fd, pass, maxlen);
321 } else if (i == 0) { /* EOF */
328 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
339 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
340 failed = untimed_read(fd, pass, maxlen);
345 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
348 struct termios orig, tmp;
350 int infd = STDIN_FILENO, outfd;
355 /* Read and write to /dev/tty if available */
356 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
358 outfd = STDERR_FILENO;
361 if (tcgetattr(infd, &orig))
364 memcpy(&tmp, &orig, sizeof(tmp));
365 tmp.c_lflag &= ~ECHO;
367 if (write(outfd, prompt, strlen(prompt)) < 0)
370 tcsetattr(infd, TCSAFLUSH, &tmp);
372 failed = timed_read(infd, pass, maxlen, timeout);
374 failed = untimed_read(infd, pass, maxlen);
375 tcsetattr(infd, TCSAFLUSH, &orig);
378 if (!failed && write(outfd, "\n", 1));
380 if (infd != STDIN_FILENO)
386 * Password reading behaviour matrix of get_key
387 * FIXME: rewrite this from scratch.
389 * -----------------+---+---+---+---
390 * interactive | Y | Y | Y | Inf
391 * from fd | N | N | Y | Inf
392 * from binary file | N | N | N | Inf or options->key_size
394 * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
396 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
399 void get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
400 const char *key_file, int timeout, int how2verify,
401 struct crypt_device *cd)
404 const int verify = how2verify & CRYPT_FLAG_VERIFY;
405 const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
408 int regular_file = 0;
413 /* Passphrase read from stdin? */
414 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
416 /* read_horizon applies only for real keyfile, not stdin or terminal */
417 read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
419 /* Setup file descriptior */
420 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
422 log_err(cd, _("Failed to open key file %s.\n"), key_file ?: "-");
426 /* Interactive case */
430 pass = safe_alloc(MAX_TTY_PASSWORD_LEN);
431 if (!pass || (i = interactive_pass(prompt, pass, MAX_TTY_PASSWORD_LEN, timeout))) {
432 log_err(cd, _("Error reading passphrase from terminal.\n"));
435 if (verify || verify_if_possible) {
436 char pass_verify[MAX_TTY_PASSWORD_LEN];
437 i = interactive_pass(_("Verify passphrase: "), pass_verify, sizeof(pass_verify), timeout);
438 if (i || strcmp(pass, pass_verify) != 0) {
439 log_err(cd, _("Passphrases do not match.\n"));
442 memset(pass_verify, 0, sizeof(pass_verify));
444 *passLen = strlen(pass);
448 * This is either a fd-input or a file, in neither case we can verify the input,
449 * however we don't stop on new lines if it's a binary file.
454 log_err(cd, _("Can't do passphrase verification on non-tty inputs.\n"));
457 /* The following for control loop does an exhausting
458 * read on the key material file, if requested with
459 * key_size == 0, as it's done by LUKS. However, we
460 * should warn the user, if it's a non-regular file,
461 * such as /dev/random, because in this case, the loop
464 if(!read_stdin && read_horizon == 0) {
465 if(stat(key_file, &st) < 0) {
466 log_err(cd, _("Failed to stat key file %s.\n"), key_file);
469 if(!S_ISREG(st.st_mode))
470 log_std(cd, _("Warning: exhausting read requested, but key file %s"
471 " is not a regular file, function might never return.\n"),
477 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
478 if(i >= buflen - 1) {
480 pass = safe_realloc(pass, buflen);
482 log_err(cd, _("Out of memory while reading passphrase.\n"));
487 r = read(fd, pass + i, 1);
489 log_err(cd, _("Error reading passphrase.\n"));
493 /* Stop on newline only if not requested read from keyfile */
494 if(r == 0 || (!key_file && pass[i] == '\n'))
497 /* Fail if piped input dies reading nothing */
498 if(!i && !regular_file) {
499 log_dbg("Error reading passphrase.");
506 if(fd != STDIN_FILENO)
511 if(fd >= 0 && fd != STDIN_FILENO)
519 int device_ready(struct crypt_device *cd, const char *device, int mode)
526 if(stat(device, &st) < 0) {
527 log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
531 log_dbg("Trying to open and read device %s.", device);
532 devfd = open(device, mode | O_DIRECT | O_SYNC);
534 log_err(cd, _("Cannot open device %s for %s%s access.\n"), device,
535 (mode & O_EXCL) ? _("exclusive ") : "",
536 (mode & O_RDWR) ? _("writable") : _("read-only"));
540 /* Try to read first sector */
541 s = read_blockwise(devfd, buf, sizeof(buf));
542 if (s < 0 || s != sizeof(buf)) {
543 log_err(cd, _("Cannot read device %s.\n"), device);
547 memset(buf, 0, sizeof(buf));
553 int get_device_infos(const char *device, struct device_infos *infos, struct crypt_device *cd)
555 struct partinfo pinfo;
557 unsigned long size_small;
562 /* Try to open read-write to check whether it is a read-only device */
563 fd = open(device, O_RDWR);
565 if (errno == EROFS) {
567 fd = open(device, O_RDONLY);
571 fd = open(device, O_RDONLY);
574 log_err(cd, _("Cannot open device: %s\n"), device);
579 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
580 size >>= SECTOR_SHIFT;
587 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
588 size = (uint64_t)size_small;
593 if (ioctl(fd, DIOCGPART, &pinfo) >= 0) {
594 size = pinfo.media_blocks;
600 log_err(cd, _("BLKGETSIZE failed on device %s.\n"), device);
604 infos->readonly = readonly;
610 int wipe_device_header(const char *device, int sectors)
613 int size = sectors * SECTOR_SIZE;
617 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
621 buffer = malloc(size);
626 memset(buffer, 0, size);
628 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
637 #define DEFAULT_PROCESS_PRIORITY -18
639 static int _priority;
640 static int _memlock_count = 0;
642 // return 1 if memory is locked
643 int crypt_memlock_inc(struct crypt_device *ctx)
645 if (!_memlock_count++) {
646 log_dbg("Locking memory.");
647 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
649 log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
651 log_err(ctx, _("WARNING!!! Possibly insecure memory, missing mlockall()\n"));
656 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
657 log_err(ctx, _("Cannot get process priority.\n"));
659 if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
660 log_err(ctx, _("setpriority %u failed: %s"),
661 DEFAULT_PROCESS_PRIORITY, strerror(errno));
663 return _memlock_count ? 1 : 0;
666 int crypt_memlock_dec(struct crypt_device *ctx)
668 if (_memlock_count && (!--_memlock_count)) {
669 log_dbg("Unlocking memory.");
671 log_err(ctx, _("Cannot unlock memory."));
672 if (setpriority(PRIO_PROCESS, 0, _priority))
673 log_err(ctx, _("setpriority %u failed: %s"), _priority, strerror(errno));
675 return _memlock_count ? 1 : 0;
678 /* DEVICE TOPOLOGY */
680 /* block device topology ioctls, introduced in 2.6.32 */
682 #define BLKIOMIN _IO(0x12,120)
683 #define BLKIOOPT _IO(0x12,121)
684 #define BLKALIGNOFF _IO(0x12,122)
687 void get_topology_alignment(const char *device,
688 unsigned long *required_alignment, /* bytes */
689 unsigned long *alignment_offset, /* bytes */
690 unsigned long default_alignment)
692 unsigned int dev_alignment_offset = 0;
693 unsigned long min_io_size = 0, opt_io_size = 0;
696 *required_alignment = default_alignment;
697 *alignment_offset = 0;
699 fd = open(device, O_RDONLY);
703 /* minimum io size */
704 if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
705 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
706 device, default_alignment);
710 /* optimal io size */
711 if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
712 opt_io_size = min_io_size;
714 /* alignment offset, bogus -1 means misaligned/unknown */
715 if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || (int)dev_alignment_offset < 0)
716 dev_alignment_offset = 0;
718 if (*required_alignment < min_io_size)
719 *required_alignment = min_io_size;
721 if (*required_alignment < opt_io_size)
722 *required_alignment = opt_io_size;
724 *alignment_offset = (unsigned long)dev_alignment_offset;
726 log_dbg("Topology: IO (%lu/%lu), offset = %lu; Required alignment is %lu bytes.",
727 min_io_size, opt_io_size, *alignment_offset, *required_alignment);