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