1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <stddef.h>
5 #include <stdarg.h>
6 #include <errno.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <sys/ioctl.h>
12 #include <fcntl.h>
13 #include <termios.h>
14 #include <sys/mman.h>
15 #include <sys/resource.h>
16 #include <cpu/param.h>
17 #include <sys/diskslice.h>
18
19 #include "libcryptsetup.h"
20 #include "internal.h"
21
22 struct safe_allocation {
23 size_t size;
24 char data[1];
25 };
26
27 static char *error=NULL;
28
set_error_va(const char * fmt,va_list va)29 void set_error_va(const char *fmt, va_list va)
30 {
31 int r;
32
33 if(error) {
34 free(error);
35 error = NULL;
36 }
37
38 if(!fmt) return;
39
40 r = vasprintf(&error, fmt, va);
41 if (r < 0) {
42 free(error);
43 error = NULL;
44 return;
45 }
46
47 if (r && error[r - 1] == '\n')
48 error[r - 1] = '\0';
49 }
50
set_error(const char * fmt,...)51 void set_error(const char *fmt, ...)
52 {
53 va_list va;
54
55 va_start(va, fmt);
56 set_error_va(fmt, va);
57 va_end(va);
58 }
59
get_error(void)60 const char *get_error(void)
61 {
62 return error;
63 }
64
safe_alloc(size_t size)65 void *safe_alloc(size_t size)
66 {
67 struct safe_allocation *alloc;
68
69 if (!size)
70 return NULL;
71
72 alloc = malloc(size + offsetof(struct safe_allocation, data));
73 if (!alloc)
74 return NULL;
75
76 alloc->size = size;
77
78 return &alloc->data;
79 }
80
safe_free(void * data)81 void safe_free(void *data)
82 {
83 struct safe_allocation *alloc;
84
85 if (!data)
86 return;
87
88 alloc = data - offsetof(struct safe_allocation, data);
89
90 memset(data, 0, alloc->size);
91
92 alloc->size = 0x55aa55aa;
93 free(alloc);
94 }
95
safe_realloc(void * data,size_t size)96 void *safe_realloc(void *data, size_t size)
97 {
98 void *new_data;
99
100 new_data = safe_alloc(size);
101
102 if (new_data && data) {
103 struct safe_allocation *alloc;
104
105 alloc = data - offsetof(struct safe_allocation, data);
106
107 if (size > alloc->size)
108 size = alloc->size;
109
110 memcpy(new_data, data, size);
111 }
112
113 safe_free(data);
114 return new_data;
115 }
116
safe_strdup(const char * s)117 char *safe_strdup(const char *s)
118 {
119 char *s2 = safe_alloc(strlen(s) + 1);
120
121 if (!s2)
122 return NULL;
123
124 return strcpy(s2, s);
125 }
126
get_alignment(int fd)127 static int get_alignment(int fd)
128 {
129 int alignment = DEFAULT_ALIGNMENT;
130
131 #ifdef _PC_REC_XFER_ALIGN
132 alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
133 if (alignment < 0)
134 alignment = DEFAULT_ALIGNMENT;
135 #endif
136 return alignment;
137 }
138
aligned_malloc(void ** base,int size,int alignment)139 static void *aligned_malloc(void **base, int size, int alignment)
140 {
141 #ifdef HAVE_POSIX_MEMALIGN
142 return posix_memalign(base, alignment, size) ? NULL : *base;
143 #else
144 /* Credits go to Michal's padlock patches for this alignment code */
145 char *ptr;
146
147 ptr = malloc(size + alignment);
148 if(ptr == NULL) return NULL;
149
150 *base = ptr;
151 if(alignment > 1 && ((long)ptr & (alignment - 1))) {
152 ptr += alignment - ((long)(ptr) & (alignment - 1));
153 }
154 return ptr;
155 #endif
156 }
sector_size(int fd)157 static int sector_size(int fd)
158 {
159 int bsize;
160 return DEV_BSIZE;
161 #if 0
162 if (ioctl(fd,BLKSSZGET, &bsize) < 0)
163 return -EINVAL;
164 else
165 return bsize;
166 #endif
167 }
168
sector_size_for_device(const char * device)169 int sector_size_for_device(const char *device)
170 {
171 int fd = open(device, O_RDONLY);
172 int r;
173 if(fd < 0)
174 return -EINVAL;
175 r = sector_size(fd);
176 close(fd);
177 return r;
178 }
179
write_blockwise(int fd,const void * orig_buf,size_t count)180 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
181 {
182 void *hangover_buf, *hangover_buf_base = NULL;
183 void *buf, *buf_base = NULL;
184 int r, hangover, solid, bsize, alignment;
185 ssize_t ret = -1;
186
187 if ((bsize = sector_size(fd)) < 0)
188 return bsize;
189
190 hangover = count % bsize;
191 solid = count - hangover;
192 alignment = get_alignment(fd);
193
194 if ((long)orig_buf & (alignment - 1)) {
195 buf = aligned_malloc(&buf_base, count, alignment);
196 if (!buf)
197 goto out;
198 memcpy(buf, orig_buf, count);
199 } else
200 buf = (void *)orig_buf;
201
202 r = write(fd, buf, solid);
203 if (r < 0 || r != solid)
204 goto out;
205
206 if (hangover) {
207 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
208 if (!hangover_buf)
209 goto out;
210
211 r = read(fd, hangover_buf, bsize);
212 if(r < 0 || r != bsize) goto out;
213
214 r = lseek(fd, -bsize, SEEK_CUR);
215 if (r < 0)
216 goto out;
217 memcpy(hangover_buf, buf + solid, hangover);
218
219 r = write(fd, hangover_buf, bsize);
220 if(r < 0 || r != bsize) goto out;
221 free(hangover_buf_base);
222 }
223 ret = count;
224 out:
225 if (buf != orig_buf)
226 free(buf_base);
227 return ret;
228 }
229
read_blockwise(int fd,void * orig_buf,size_t count)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;
234 ssize_t ret = -1;
235
236 if ((bsize = sector_size(fd)) < 0)
237 return bsize;
238
239 hangover = count % bsize;
240 solid = count - hangover;
241 alignment = get_alignment(fd);
242
243 if ((long)orig_buf & (alignment - 1)) {
244 buf = aligned_malloc(&buf_base, count, alignment);
245 if (!buf)
246 goto out;
247 } else
248 buf = orig_buf;
249
250 r = read(fd, buf, solid);
251 if(r < 0 || r != solid)
252 goto out;
253
254 if (hangover) {
255 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
256 if (!hangover_buf)
257 goto out;
258 r = read(fd, hangover_buf, bsize);
259 if (r < 0 || r != bsize)
260 goto out;
261
262 memcpy(buf + solid, hangover_buf, hangover);
263 free(hangover_buf_base);
264 }
265 ret = count;
266 out:
267 if (buf != orig_buf) {
268 memcpy(orig_buf, buf, count);
269 free(buf_base);
270 }
271 return ret;
272 }
273
274 /*
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.
279 */
280
write_lseek_blockwise(int fd,const char * buf,size_t count,off_t offset)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;
286 int r;
287 int innerCount = count < bsize ? count : bsize;
288
289 if (bsize < 0)
290 return bsize;
291
292 lseek(fd, offset - frontHang, SEEK_SET);
293 if(offset % bsize) {
294 r = read(fd,frontPadBuf,bsize);
295 if(r < 0) return -1;
296
297 memcpy(frontPadBuf+frontHang, buf, innerCount);
298
299 lseek(fd, offset - frontHang, SEEK_SET);
300 r = write(fd,frontPadBuf,bsize);
301 if(r < 0) return -1;
302
303 buf += innerCount;
304 count -= innerCount;
305 }
306 if(count <= 0) return buf - orig_buf;
307
308 return write_blockwise(fd, buf, count) + innerCount;
309 }
310
311 /* Password reading helpers */
312
untimed_read(int fd,char * pass,size_t maxlen)313 static int untimed_read(int fd, char *pass, size_t maxlen)
314 {
315 ssize_t i;
316
317 i = read(fd, pass, maxlen);
318 if (i > 0) {
319 pass[i-1] = '\0';
320 i = 0;
321 } else if (i == 0) { /* EOF */
322 *pass = 0;
323 i = -1;
324 }
325 return i;
326 }
327
timed_read(int fd,char * pass,size_t maxlen,long timeout)328 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
329 {
330 struct timeval t;
331 fd_set fds;
332 int failed = -1;
333
334 FD_ZERO(&fds);
335 FD_SET(fd, &fds);
336 t.tv_sec = timeout;
337 t.tv_usec = 0;
338
339 if (select(fd+1, &fds, NULL, NULL, &t) > 0)
340 failed = untimed_read(fd, pass, maxlen);
341
342 return failed;
343 }
344
interactive_pass(const char * prompt,char * pass,size_t maxlen,long timeout)345 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
346 long timeout)
347 {
348 struct termios orig, tmp;
349 int failed = -1;
350 int infd = STDIN_FILENO, outfd;
351
352 if (maxlen < 1)
353 goto out_err;
354
355 /* Read and write to /dev/tty if available */
356 if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
357 infd = STDIN_FILENO;
358 outfd = STDERR_FILENO;
359 }
360
361 if (tcgetattr(infd, &orig))
362 goto out_err;
363
364 memcpy(&tmp, &orig, sizeof(tmp));
365 tmp.c_lflag &= ~ECHO;
366
367 if (write(outfd, prompt, strlen(prompt)) < 0)
368 goto out_err;
369
370 tcsetattr(infd, TCSAFLUSH, &tmp);
371 if (timeout)
372 failed = timed_read(infd, pass, maxlen, timeout);
373 else
374 failed = untimed_read(infd, pass, maxlen);
375 tcsetattr(infd, TCSAFLUSH, &orig);
376
377 out_err:
378 if (!failed && write(outfd, "\n", 1));
379
380 if (infd != STDIN_FILENO)
381 close(infd);
382 return failed;
383 }
384
385 /*
386 * Password reading behaviour matrix of get_key
387 * FIXME: rewrite this from scratch.
388 * p v n h
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
393 *
394 * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
395 *
396 * Note: --key-file=- is interpreted as a read from a binary file (stdin)
397 */
398
get_key(char * prompt,char ** key,unsigned int * passLen,int key_size,const char * key_file,int timeout,int how2verify,struct crypt_device * cd)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)
402 {
403 int fd = -1;
404 const int verify = how2verify & CRYPT_FLAG_VERIFY;
405 const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
406 char *pass = NULL;
407 int read_horizon;
408 int regular_file = 0;
409 int read_stdin;
410 int r;
411 struct stat st;
412
413 /* Passphrase read from stdin? */
414 read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
415
416 /* read_horizon applies only for real keyfile, not stdin or terminal */
417 read_horizon = (key_file && !read_stdin) ? key_size : 0 /* until EOF */;
418
419 /* Setup file descriptior */
420 fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
421 if (fd < 0) {
422 log_err(cd, _("Failed to open key file %s.\n"), key_file ?: "-");
423 goto out_err;
424 }
425
426 /* Interactive case */
427 if(isatty(fd)) {
428 int i;
429
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"));
433 goto out_err;
434 }
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"));
440 goto out_err;
441 }
442 memset(pass_verify, 0, sizeof(pass_verify));
443 }
444 *passLen = strlen(pass);
445 *key = pass;
446 } else {
447 /*
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.
450 */
451 int buflen, i;
452
453 if(verify) {
454 log_err(cd, _("Can't do passphrase verification on non-tty inputs.\n"));
455 goto out_err;
456 }
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
462 * will read forever.
463 */
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);
467 goto out_err;
468 }
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"),
472 key_file);
473 else
474 regular_file = 1;
475 }
476 buflen = 0;
477 for(i = 0; read_horizon == 0 || i < read_horizon; i++) {
478 if(i >= buflen - 1) {
479 buflen += 128;
480 pass = safe_realloc(pass, buflen);
481 if (!pass) {
482 log_err(cd, _("Out of memory while reading passphrase.\n"));
483 goto out_err;
484 }
485 }
486
487 r = read(fd, pass + i, 1);
488 if (r < 0) {
489 log_err(cd, _("Error reading passphrase.\n"));
490 goto out_err;
491 }
492
493 /* Stop on newline only if not requested read from keyfile */
494 if(r == 0 || (!key_file && pass[i] == '\n'))
495 break;
496 }
497 /* Fail if piped input dies reading nothing */
498 if(!i && !regular_file) {
499 log_dbg("Error reading passphrase.");
500 goto out_err;
501 }
502 pass[i] = 0;
503 *key = pass;
504 *passLen = i;
505 }
506 if(fd != STDIN_FILENO)
507 close(fd);
508 return;
509
510 out_err:
511 if(fd >= 0 && fd != STDIN_FILENO)
512 close(fd);
513 if(pass)
514 safe_free(pass);
515 *key = NULL;
516 *passLen = 0;
517 }
518
device_ready(struct crypt_device * cd,const char * device,int mode)519 int device_ready(struct crypt_device *cd, const char *device, int mode)
520 {
521 int devfd, r = 1;
522 ssize_t s;
523 struct stat st;
524 char buf[512];
525
526 if(stat(device, &st) < 0) {
527 log_err(cd, _("Device %s doesn't exist or access denied.\n"), device);
528 return 0;
529 }
530
531 log_dbg("Trying to open and read device %s.", device);
532 devfd = open(device, mode | O_DIRECT | O_SYNC);
533 if(devfd < 0) {
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"));
537 return 0;
538 }
539
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);
544 r = 0;
545 }
546
547 memset(buf, 0, sizeof(buf));
548 close(devfd);
549
550 return r;
551 }
552
get_device_infos(const char * device,struct device_infos * infos,struct crypt_device * cd)553 int get_device_infos(const char *device, struct device_infos *infos, struct crypt_device *cd)
554 {
555 struct partinfo pinfo;
556 uint64_t size;
557 unsigned long size_small;
558 int readonly = 0;
559 int ret = -1;
560 int fd;
561
562 /* Try to open read-write to check whether it is a read-only device */
563 fd = open(device, O_RDWR);
564 if (fd < 0) {
565 if (errno == EROFS) {
566 readonly = 1;
567 fd = open(device, O_RDONLY);
568 }
569 } else {
570 close(fd);
571 fd = open(device, O_RDONLY);
572 }
573 if (fd < 0) {
574 log_err(cd, _("Cannot open device: %s\n"), device);
575 return -1;
576 }
577
578 #ifdef BLKGETSIZE64
579 if (ioctl(fd, BLKGETSIZE64, &size) >= 0) {
580 size >>= SECTOR_SHIFT;
581 ret = 0;
582 goto out;
583 }
584 #endif
585
586 #ifdef BLKGETSIZE
587 if (ioctl(fd, BLKGETSIZE, &size_small) >= 0) {
588 size = (uint64_t)size_small;
589 ret = 0;
590 goto out;
591 }
592 #else
593 if (ioctl(fd, DIOCGPART, &pinfo) >= 0) {
594 size = pinfo.media_blocks;
595 ret = 0;
596 goto out;
597 }
598 #endif
599
600 log_err(cd, _("BLKGETSIZE failed on device %s.\n"), device);
601 out:
602 if (ret == 0) {
603 infos->size = size;
604 infos->readonly = readonly;
605 }
606 close(fd);
607 return ret;
608 }
609
wipe_device_header(const char * device,int sectors)610 int wipe_device_header(const char *device, int sectors)
611 {
612 char *buffer;
613 int size = sectors * SECTOR_SIZE;
614 int r = -1;
615 int devfd;
616
617 devfd = open(device, O_RDWR | O_DIRECT | O_SYNC);
618 if(devfd == -1)
619 return -EINVAL;
620
621 buffer = malloc(size);
622 if (!buffer) {
623 close(devfd);
624 return -ENOMEM;
625 }
626 memset(buffer, 0, size);
627
628 r = write_blockwise(devfd, buffer, size) < size ? -EIO : 0;
629
630 free(buffer);
631 close(devfd);
632
633 return r;
634 }
635
636 /* MEMLOCK */
637 #define DEFAULT_PROCESS_PRIORITY -18
638
639 static int _priority;
640 static int _memlock_count = 0;
641
642 // return 1 if memory is locked
crypt_memlock_inc(struct crypt_device * ctx)643 int crypt_memlock_inc(struct crypt_device *ctx)
644 {
645 if (!_memlock_count++) {
646 log_dbg("Locking memory.");
647 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
648 log_err(ctx, _("WARNING!!! Possibly insecure memory. Are you root?\n"));
649 _memlock_count--;
650 return 0;
651 }
652 errno = 0;
653 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
654 log_err(ctx, _("Cannot get process priority.\n"));
655 else
656 if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
657 log_err(ctx, _("setpriority %u failed: %s"),
658 DEFAULT_PROCESS_PRIORITY, strerror(errno));
659 }
660 return _memlock_count ? 1 : 0;
661 }
662
crypt_memlock_dec(struct crypt_device * ctx)663 int crypt_memlock_dec(struct crypt_device *ctx)
664 {
665 if (_memlock_count && (!--_memlock_count)) {
666 log_dbg("Unlocking memory.");
667 if (munlockall())
668 log_err(ctx, _("Cannot unlock memory."));
669 if (setpriority(PRIO_PROCESS, 0, _priority))
670 log_err(ctx, _("setpriority %u failed: %s"), _priority, strerror(errno));
671 }
672 return _memlock_count ? 1 : 0;
673 }
674
675 /* DEVICE TOPOLOGY */
676
677 /* block device topology ioctls, introduced in 2.6.32 */
678 #ifndef BLKIOMIN
679 #define BLKIOMIN _IO(0x12,120)
680 #define BLKIOOPT _IO(0x12,121)
681 #define BLKALIGNOFF _IO(0x12,122)
682 #endif
683
get_topology_alignment(const char * device,unsigned long * required_alignment,unsigned long * alignment_offset,unsigned long default_alignment)684 void get_topology_alignment(const char *device,
685 unsigned long *required_alignment, /* bytes */
686 unsigned long *alignment_offset, /* bytes */
687 unsigned long default_alignment)
688 {
689 unsigned int dev_alignment_offset = 0;
690 unsigned long min_io_size = 0, opt_io_size = 0;
691 int fd;
692
693 *required_alignment = default_alignment;
694 *alignment_offset = 0;
695
696 fd = open(device, O_RDONLY);
697 if (fd == -1)
698 return;
699
700 /* minimum io size */
701 if (ioctl(fd, BLKIOMIN, &min_io_size) == -1) {
702 log_dbg("Topology info for %s not supported, using default offset %lu bytes.",
703 device, default_alignment);
704 goto out;
705 }
706
707 /* optimal io size */
708 if (ioctl(fd, BLKIOOPT, &opt_io_size) == -1)
709 opt_io_size = min_io_size;
710
711 /* alignment offset, bogus -1 means misaligned/unknown */
712 if (ioctl(fd, BLKALIGNOFF, &dev_alignment_offset) == -1 || (int)dev_alignment_offset < 0)
713 dev_alignment_offset = 0;
714
715 if (*required_alignment < min_io_size)
716 *required_alignment = min_io_size;
717
718 if (*required_alignment < opt_io_size)
719 *required_alignment = opt_io_size;
720
721 *alignment_offset = (unsigned long)dev_alignment_offset;
722
723 log_dbg("Topology: IO (%lu/%lu), offset = %lu; Required alignment is %lu bytes.",
724 min_io_size, opt_io_size, *alignment_offset, *required_alignment);
725 out:
726 (void)close(fd);
727 }
728