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