* Move memory locking and dm initialization to command layer.
[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
22 struct safe_allocation {
23         size_t  size;
24         char    data[1];
25 };
26
27 static char *error=NULL;
28
29 void set_error_va(const char *fmt, va_list va)
30 {
31
32         if(error) {
33             free(error);
34             error=NULL;
35         }
36
37         if(!fmt) return;
38
39         if (vasprintf(&error, fmt, va) < 0) {
40                 free(error);
41                 error = NULL;
42         }
43 }
44
45 void set_error(const char *fmt, ...)
46 {
47         va_list va;
48
49         va_start(va, fmt);
50         set_error_va(fmt, va);
51         va_end(va);
52 }
53
54 const char *get_error(void)
55 {
56         return error;
57 }
58
59 void *safe_alloc(size_t size)
60 {
61         struct safe_allocation *alloc;
62
63         if (!size)
64                 return NULL;
65
66         alloc = malloc(size + offsetof(struct safe_allocation, data));
67         if (!alloc)
68                 return NULL;
69
70         alloc->size = size;
71
72         return &alloc->data;
73 }
74
75 void safe_free(void *data)
76 {
77         struct safe_allocation *alloc;
78
79         if (!data)
80                 return;
81
82         alloc = data - offsetof(struct safe_allocation, data);
83
84         memset(data, 0, alloc->size);
85
86         alloc->size = 0x55aa55aa;
87         free(alloc);
88 }
89
90 void *safe_realloc(void *data, size_t size)
91 {
92         void *new_data;
93
94         new_data = safe_alloc(size);
95
96         if (new_data && data) {
97                 struct safe_allocation *alloc;
98
99                 alloc = data - offsetof(struct safe_allocation, data);
100
101                 if (size > alloc->size)
102                         size = alloc->size;
103
104                 memcpy(new_data, data, size);
105         }
106
107         safe_free(data);
108         return new_data;
109 }
110
111 char *safe_strdup(const char *s)
112 {
113         char *s2 = safe_alloc(strlen(s) + 1);
114
115         if (!s2)
116                 return NULL;
117
118         return strcpy(s2, s);
119 }
120
121 static int get_alignment(int fd)
122 {
123         int alignment = DEFAULT_ALIGNMENT;
124
125 #ifdef _PC_REC_XFER_ALIGN
126         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
127         if (alignment < 0)
128                 alignment = DEFAULT_ALIGNMENT;
129 #endif
130         return alignment;
131 }
132
133 static void *aligned_malloc(void **base, int size, int alignment)
134 {
135 #ifdef HAVE_POSIX_MEMALIGN
136         return posix_memalign(base, alignment, size) ? NULL : *base;
137 #else
138 /* Credits go to Michal's padlock patches for this alignment code */
139         char *ptr;
140
141         ptr  = malloc(size + alignment);
142         if(ptr == NULL) return NULL;
143
144         *base = ptr;
145         if(alignment > 1 && ((long)ptr & (alignment - 1))) {
146                 ptr += alignment - ((long)(ptr) & (alignment - 1));
147         }
148         return ptr;
149 #endif
150 }
151 static int sector_size(int fd) 
152 {
153         int bsize;
154         if (ioctl(fd,BLKSSZGET, &bsize) < 0)
155                 return -EINVAL;
156         else
157                 return bsize;
158 }
159
160 int sector_size_for_device(const char *device)
161 {
162         int fd = open(device, O_RDONLY);
163         int r;
164         if(fd < 0)
165                 return -EINVAL;
166         r = sector_size(fd);
167         close(fd);
168         return r;
169 }
170
171 ssize_t write_blockwise(int fd, const void *orig_buf, size_t count)
172 {
173         void *hangover_buf, *hangover_buf_base = NULL;
174         void *buf, *buf_base = NULL;
175         int r, hangover, solid, bsize, alignment;
176         ssize_t ret = -1;
177
178         if ((bsize = sector_size(fd)) < 0)
179                 return bsize;
180
181         hangover = count % bsize;
182         solid = count - hangover;
183         alignment = get_alignment(fd);
184
185         if ((long)orig_buf & (alignment - 1)) {
186                 buf = aligned_malloc(&buf_base, count, alignment);
187                 if (!buf)
188                         goto out;
189                 memcpy(buf, orig_buf, count);
190         } else
191                 buf = (void *)orig_buf;
192
193         r = write(fd, buf, solid);
194         if (r < 0 || r != solid)
195                 goto out;
196
197         if (hangover) {
198                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
199                 if (!hangover_buf)
200                         goto out;
201
202                 r = read(fd, hangover_buf, bsize);
203                 if(r < 0 || r != bsize) goto out;
204
205                 r = lseek(fd, -bsize, SEEK_CUR);
206                 if (r < 0)
207                         goto out;
208                 memcpy(hangover_buf, buf + solid, hangover);
209
210                 r = write(fd, hangover_buf, bsize);
211                 if(r < 0 || r != bsize) goto out;
212                 free(hangover_buf_base);
213         }
214         ret = count;
215  out:
216         if (buf != orig_buf)
217                 free(buf_base);
218         return ret;
219 }
220
221 ssize_t read_blockwise(int fd, void *orig_buf, size_t count) {
222         void *hangover_buf, *hangover_buf_base;
223         void *buf, *buf_base = NULL;
224         int r, hangover, solid, bsize, alignment;
225         ssize_t ret = -1;
226
227         if ((bsize = sector_size(fd)) < 0)
228                 return bsize;
229
230         hangover = count % bsize;
231         solid = count - hangover;
232         alignment = get_alignment(fd);
233
234         if ((long)orig_buf & (alignment - 1)) {
235                 buf = aligned_malloc(&buf_base, count, alignment);
236                 if (!buf)
237                         goto out;
238         } else
239                 buf = orig_buf;
240
241         r = read(fd, buf, solid);
242         if(r < 0 || r != solid) {
243                 set_error("read failed in read_blockwise.\n");
244                 goto out;
245         }
246
247         if (hangover) {
248                 hangover_buf = aligned_malloc(&hangover_buf_base, bsize, alignment);
249                 if (!hangover_buf)
250                         goto out;
251                 r = read(fd, hangover_buf, bsize);
252                 if (r <  0 || r != bsize)
253                         goto out;
254
255                 memcpy(buf + solid, hangover_buf, hangover);
256                 free(hangover_buf_base);
257         }
258         ret = count;
259  out:
260         if (buf != orig_buf) {
261                 memcpy(orig_buf, buf, count);
262                 free(buf_base);
263         }
264         return ret;
265 }
266
267 /* 
268  * Combines llseek with blockwise write. write_blockwise can already deal with short writes
269  * but we also need a function to deal with short writes at the start. But this information
270  * is implicitly included in the read/write offset, which can not be set to non-aligned 
271  * boundaries. Hence, we combine llseek with write.
272  */
273
274 ssize_t write_lseek_blockwise(int fd, const char *buf, size_t count, off_t offset) {
275         int bsize = sector_size(fd);
276         const char *orig_buf = buf;
277         char frontPadBuf[bsize];
278         int frontHang = offset % bsize;
279         int r;
280         int innerCount = count < bsize ? count : bsize;
281
282         if (bsize < 0)
283                 return bsize;
284
285         lseek(fd, offset - frontHang, SEEK_SET);
286         if(offset % bsize) {
287                 r = read(fd,frontPadBuf,bsize);
288                 if(r < 0) return -1;
289
290                 memcpy(frontPadBuf+frontHang, buf, innerCount);
291
292                 lseek(fd, offset - frontHang, SEEK_SET);
293                 r = write(fd,frontPadBuf,bsize);
294                 if(r < 0) return -1;
295
296                 buf += innerCount;
297                 count -= innerCount;
298         }
299         if(count <= 0) return buf - orig_buf;
300
301         return write_blockwise(fd, buf, count) + innerCount;
302 }
303
304 /* Password reading helpers */
305
306 static int untimed_read(int fd, char *pass, size_t maxlen)
307 {
308         ssize_t i;
309
310         i = read(fd, pass, maxlen);
311         if (i > 0) {
312                 pass[i-1] = '\0';
313                 i = 0;
314         } else if (i == 0) { /* EOF */
315                 *pass = 0;
316                 i = -1;
317         }
318         return i;
319 }
320
321 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
322 {
323         struct timeval t;
324         fd_set fds;
325         int failed = -1;
326
327         FD_ZERO(&fds);
328         FD_SET(fd, &fds);
329         t.tv_sec = timeout;
330         t.tv_usec = 0;
331
332         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
333                 failed = untimed_read(fd, pass, maxlen);
334         else
335                 set_error("Operation timed out");
336         return failed;
337 }
338
339 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
340                 long timeout)
341 {
342         struct termios orig, tmp;
343         int failed = -1;
344         int infd = STDIN_FILENO, outfd;
345
346         if (maxlen < 1)
347                 goto out_err;
348
349         /* Read and write to /dev/tty if available */
350         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
351                 infd = STDIN_FILENO;
352                 outfd = STDERR_FILENO;
353         }
354
355         if (tcgetattr(infd, &orig)) {
356                 set_error("Unable to get terminal");
357                 goto out_err;
358         }
359         memcpy(&tmp, &orig, sizeof(tmp));
360         tmp.c_lflag &= ~ECHO;
361
362         if (write(outfd, prompt, strlen(prompt)) < 0)
363                 goto out_err;
364
365         tcsetattr(infd, TCSAFLUSH, &tmp);
366         if (timeout)
367                 failed = timed_read(infd, pass, maxlen, timeout);
368         else
369                 failed = untimed_read(infd, pass, maxlen);
370         tcsetattr(infd, TCSAFLUSH, &orig);
371
372 out_err:
373         if (!failed)
374                 (void)write(outfd, "\n", 1);
375         if (infd != STDIN_FILENO)
376                 close(infd);
377         return failed;
378 }
379
380 /*
381  * Password reading behaviour matrix of get_key
382  * 
383  *                    p   v   n   h
384  * -----------------+---+---+---+---
385  * interactive      | Y | Y | Y | Inf
386  * from fd          | N | N | Y | Inf
387  * from binary file | N | N | N | Inf or options->key_size
388  *
389  * Legend: p..prompt, v..can verify, n..newline-stop, h..read horizon
390  *
391  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
392  *
393  * Returns true when more keys are available (that is when password
394  * reading can be retried as for interactive terminals).
395  */
396
397 int get_key(char *prompt, char **key, unsigned int *passLen, int key_size,
398             const char *key_file, int passphrase_fd, int timeout, int how2verify)
399 {
400         int fd;
401         const int verify = how2verify & CRYPT_FLAG_VERIFY;
402         const int verify_if_possible = how2verify & CRYPT_FLAG_VERIFY_IF_POSSIBLE;
403         char *pass = NULL;
404         int newline_stop;
405         int read_horizon;
406
407         if(key_file && !strcmp(key_file, "-")) {
408                 /* Allow binary reading from stdin */
409                 fd = passphrase_fd;
410                 newline_stop = 0;
411                 read_horizon = 0;
412         } else if (key_file) {
413                 fd = open(key_file, O_RDONLY);
414                 if (fd < 0) {
415                         char buf[128];
416                         set_error("Error opening key file: %s",
417                                   strerror_r(errno, buf, 128));
418                         goto out_err;
419                 }
420                 newline_stop = 0;
421
422                 /* This can either be 0 (LUKS) or the actually number
423                  * of key bytes (default or passed by -s) */
424                 read_horizon = key_size;
425         } else {
426                 fd = passphrase_fd;
427                 newline_stop = 1;
428                 read_horizon = 0;   /* Infinite, if read from terminal or fd */
429         }
430
431         /* Interactive case */
432         if(isatty(fd)) {
433                 int i;
434
435                 pass = safe_alloc(512);
436                 if (!pass || (i = interactive_pass(prompt, pass, 512, timeout))) {
437                         set_error("Error reading passphrase");
438                         goto out_err;
439                 }
440                 if (verify || verify_if_possible) {
441                         char pass_verify[512];
442                         i = interactive_pass("Verify passphrase: ", pass_verify, sizeof(pass_verify), timeout);
443                         if (i || strcmp(pass, pass_verify) != 0) {
444                                 set_error("Passphrases do not match");
445                                 goto out_err;
446                         }
447                         memset(pass_verify, 0, sizeof(pass_verify));
448                 }
449                 *passLen = strlen(pass);
450                 *key = pass;
451         } else {
452                 /* 
453                  * This is either a fd-input or a file, in neither case we can verify the input,
454                  * however we don't stop on new lines if it's a binary file.
455                  */
456                 int buflen, i;
457
458                 if(verify) {
459                         set_error("Can't do passphrase verification on non-tty inputs");
460                         goto out_err;
461                 }
462                 /* The following for control loop does an exhausting
463                  * read on the key material file, if requested with
464                  * key_size == 0, as it's done by LUKS. However, we
465                  * should warn the user, if it's a non-regular file,
466                  * such as /dev/random, because in this case, the loop
467                  * will read forever.
468                  */ 
469                 if(key_file && strcmp(key_file, "-") && read_horizon == 0) {
470                         struct stat st;
471                         if(stat(key_file, &st) < 0) {
472                                 set_error("Can't stat key file");
473                                 goto out_err;
474                         }
475                         if(!S_ISREG(st.st_mode)) {
476                                 //                              set_error("Can't do exhausting read on non regular files");
477                                 // goto out_err;
478                                 fprintf(stderr,"Warning: exhausting read requested, but key file is not a regular file, function might never return.\n");
479                         }
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                                         set_error("Not enough memory while "
488                                                   "reading passphrase");
489                                         goto out_err;
490                                 }
491                         }
492                         if(read(fd, pass + i, 1) != 1 || (newline_stop && pass[i] == '\n'))
493                                 break;
494                 }
495                 if(key_file)
496                         close(fd);
497                 pass[i] = 0;
498                 *key = pass;
499                 *passLen = i;
500         }
501
502         return isatty(fd); /* Return true, when password reading can be tried on interactive fds */
503
504 out_err:
505         if(pass)
506                 safe_free(pass);
507         *key = NULL;
508         *passLen = 0;
509         return 0;
510 }
511
512 /* MEMLOCK */
513 #define DEFAULT_PROCESS_PRIORITY -18
514
515 static int _priority;
516 static int _memlock_count = 0;
517
518 // return 1 if memory is locked
519 int memlock_inc(struct crypt_device *ctx)
520 {
521         if (!_memlock_count++) {
522                 if (mlockall(MCL_CURRENT | MCL_FUTURE)) {
523                         set_error(_("WARNING!!! Possibly insecure memory. Are you root?\n"));
524                         _memlock_count--;
525                         return 0;
526                 }
527                 errno = 0;
528                 if (((_priority = getpriority(PRIO_PROCESS, 0)) == -1) && errno)
529                         set_error(_("Cannot get process priority.\n"));
530                 else
531                         if (setpriority(PRIO_PROCESS, 0, DEFAULT_PROCESS_PRIORITY))
532                                 set_error(_("setpriority %u failed: %s"),
533                                         DEFAULT_PROCESS_PRIORITY, strerror(errno));
534         }
535         return _memlock_count ? 1 : 0;
536 }
537
538 int memlock_dec(struct crypt_device *ctx)
539 {
540         if (_memlock_count && (!--_memlock_count)) {
541                 if (munlockall())
542                         set_error(_("Cannot unlock memory."));
543                 if (setpriority(PRIO_PROCESS, 0, _priority))
544                         set_error(_("setpriority %u failed: %s"), _priority, strerror(errno));
545         }
546         return _memlock_count ? 1 : 0;
547 }