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