Fix some problems found by Coverity static analysis.
[platform/upstream/cryptsetup.git] / lib / utils_crypt.c
1 /*
2  * utils_crypt - cipher utilities for cryptsetup
3  *
4  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2009-2012, Red Hat, Inc. All rights reserved.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <stdlib.h>
22 #include <stddef.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <ctype.h>
27 #include <limits.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <unistd.h>
31 #include <fcntl.h>
32 #include <termios.h>
33
34 #include "libcryptsetup.h"
35 #include "nls.h"
36 #include "utils_crypt.h"
37
38 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
39 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
40
41 struct safe_allocation {
42         size_t  size;
43         char    data[0];
44 };
45
46 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
47                               char *cipher_mode)
48 {
49         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
50                    cipher, cipher_mode) == 2) {
51                 if (!strcmp(cipher_mode, "plain"))
52                         strncpy(cipher_mode, "cbc-plain", 10);
53                 if (key_nums) {
54                         char *tmp = strchr(cipher, ':');
55                         *key_nums = tmp ? atoi(++tmp) : 1;
56                         if (!*key_nums)
57                                 return -EINVAL;
58                 }
59
60                 return 0;
61         }
62
63         /* Short version for "empty" cipher */
64         if (!strcmp(s, "null")) {
65                 strncpy(cipher, "cipher_null", MAX_CIPHER_LEN);
66                 strncpy(cipher_mode, "ecb", 9);
67                 if (key_nums)
68                         *key_nums = 0;
69                 return 0;
70         }
71
72         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
73                 strncpy(cipher_mode, "cbc-plain", 10);
74                 if (key_nums)
75                         *key_nums = 1;
76                 return 0;
77         }
78
79         return -EINVAL;
80 }
81
82 /* safe allocations */
83 void *crypt_safe_alloc(size_t size)
84 {
85         struct safe_allocation *alloc;
86
87         if (!size)
88                 return NULL;
89
90         alloc = malloc(size + offsetof(struct safe_allocation, data));
91         if (!alloc)
92                 return NULL;
93
94         alloc->size = size;
95         memset(&alloc->data, 0, size);
96
97         /* coverity[leaked_storage] */
98         return &alloc->data;
99 }
100
101 void crypt_safe_free(void *data)
102 {
103         struct safe_allocation *alloc;
104
105         if (!data)
106                 return;
107
108         alloc = (struct safe_allocation *)
109                 ((char *)data - offsetof(struct safe_allocation, data));
110
111         memset(data, 0, alloc->size);
112
113         alloc->size = 0x55aa55aa;
114         free(alloc);
115 }
116
117 void *crypt_safe_realloc(void *data, size_t size)
118 {
119         struct safe_allocation *alloc;
120         void *new_data;
121
122         new_data = crypt_safe_alloc(size);
123
124         if (new_data && data) {
125
126                 alloc = (struct safe_allocation *)
127                         ((char *)data - offsetof(struct safe_allocation, data));
128
129                 if (size > alloc->size)
130                         size = alloc->size;
131
132                 memcpy(new_data, data, size);
133         }
134
135         crypt_safe_free(data);
136         return new_data;
137 }
138
139 /* Password reading helpers */
140 static int untimed_read(int fd, char *pass, size_t maxlen)
141 {
142         ssize_t i;
143
144         i = read(fd, pass, maxlen);
145         if (i > 0) {
146                 pass[i-1] = '\0';
147                 i = 0;
148         } else if (i == 0) { /* EOF */
149                 *pass = 0;
150                 i = -1;
151         }
152         return i;
153 }
154
155 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
156 {
157         struct timeval t;
158         fd_set fds;
159         int failed = -1;
160
161         FD_ZERO(&fds);
162         FD_SET(fd, &fds);
163         t.tv_sec = timeout;
164         t.tv_usec = 0;
165
166         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
167                 failed = untimed_read(fd, pass, maxlen);
168
169         return failed;
170 }
171
172 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
173                 long timeout)
174 {
175         struct termios orig, tmp;
176         int failed = -1;
177         int infd = STDIN_FILENO, outfd;
178
179         if (maxlen < 1)
180                 goto out_err;
181
182         /* Read and write to /dev/tty if available */
183         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
184                 infd = STDIN_FILENO;
185                 outfd = STDERR_FILENO;
186         }
187
188         if (tcgetattr(infd, &orig))
189                 goto out_err;
190
191         memcpy(&tmp, &orig, sizeof(tmp));
192         tmp.c_lflag &= ~ECHO;
193
194         if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
195                 goto out_err;
196
197         tcsetattr(infd, TCSAFLUSH, &tmp);
198         if (timeout)
199                 failed = timed_read(infd, pass, maxlen, timeout);
200         else
201                 failed = untimed_read(infd, pass, maxlen);
202         tcsetattr(infd, TCSAFLUSH, &orig);
203
204 out_err:
205         if (!failed && write(outfd, "\n", 1)) {};
206
207         if (infd != STDIN_FILENO)
208                 close(infd);
209         return failed;
210 }
211
212 static int crypt_get_key_tty(const char *prompt,
213                              char **key, size_t *key_size,
214                              int timeout, int verify,
215                              struct crypt_device *cd)
216 {
217         int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
218         int r = -EINVAL;
219         char *pass = NULL, *pass_verify = NULL;
220
221         log_dbg("Interactive passphrase entry requested.");
222
223         pass = crypt_safe_alloc(key_size_max + 1);
224         if (!pass) {
225                 log_err(cd, _("Out of memory while reading passphrase.\n"));
226                 return -ENOMEM;
227         }
228
229         if (interactive_pass(prompt, pass, key_size_max, timeout)) {
230                 log_err(cd, _("Error reading passphrase from terminal.\n"));
231                 goto out_err;
232         }
233         pass[key_size_max] = '\0';
234
235         if (verify) {
236                 pass_verify = crypt_safe_alloc(key_size_max);
237                 if (!pass_verify) {
238                         log_err(cd, _("Out of memory while reading passphrase.\n"));
239                         r = -ENOMEM;
240                         goto out_err;
241                 }
242
243                 if (interactive_pass(_("Verify passphrase: "),
244                     pass_verify, key_size_max, timeout)) {
245                         log_err(cd, _("Error reading passphrase from terminal.\n"));
246                         goto out_err;
247                 }
248
249                 if (strncmp(pass, pass_verify, key_size_max)) {
250                         log_err(cd, _("Passphrases do not match.\n"));
251                         r = -EPERM;
252                         goto out_err;
253                 }
254         }
255
256         *key = pass;
257         *key_size = strlen(pass);
258         r = 0;
259 out_err:
260         crypt_safe_free(pass_verify);
261         if (r)
262                 crypt_safe_free(pass);
263         return r;
264 }
265
266 /*
267  * A simple call to lseek(3) might not be possible for some inputs (e.g.
268  * reading from a pipe), so this function instead reads of up to BUFSIZ bytes
269  * at a time until the specified number of bytes. It returns -1 on read error
270  * or when it reaches EOF before the requested number of bytes have been
271  * discarded.
272  */
273 static int keyfile_seek(int fd, size_t bytes)
274 {
275         char tmp[BUFSIZ];
276         size_t next_read;
277         ssize_t bytes_r;
278         off_t r;
279
280         r = lseek(fd, bytes, SEEK_CUR);
281         if (r > 0)
282                 return 0;
283         if (r < 0 && errno != ESPIPE)
284                 return -1;
285
286         while (bytes > 0) {
287                 /* figure out how much to read */
288                 next_read = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
289
290                 bytes_r = read(fd, tmp, next_read);
291                 if (bytes_r < 0) {
292                         if (errno == EINTR)
293                                 continue;
294
295                         /* read error */
296                         return -1;
297                 }
298
299                 if (bytes_r == 0)
300                         /* EOF */
301                         break;
302
303                 bytes -= bytes_r;
304         }
305
306         return bytes == 0 ? 0 : -1;
307 }
308
309 /*
310  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
311  * key_size_max == 0 means detect maximum according to input type (tty/file)
312  * timeout and verify options only applies to tty input
313  */
314 int crypt_get_key(const char *prompt,
315                   char **key, size_t *key_size,
316                   size_t keyfile_offset, size_t keyfile_size_max,
317                   const char *key_file, int timeout, int verify,
318                   struct crypt_device *cd)
319 {
320         int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
321         int r = -EINVAL;
322         char *pass = NULL;
323         size_t buflen, i, file_read_size;
324         struct stat st;
325
326         *key = NULL;
327         *key_size = 0;
328
329         /* Passphrase read from stdin? */
330         read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
331
332         if (read_stdin && isatty(STDIN_FILENO)) {
333                 if (keyfile_offset) {
334                         log_err(cd, _("Cannot use offset with terminal input.\n"));
335                         return -EINVAL;
336                 }
337                 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
338         }
339
340         if (read_stdin)
341                 log_dbg("STDIN descriptor passphrase entry requested.");
342         else
343                 log_dbg("File descriptor passphrase entry requested.");
344
345         /* If not requsted otherwise, we limit input to prevent memory exhaustion */
346         if (keyfile_size_max == 0) {
347                 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
348                 unlimited_read = 1;
349         }
350
351         fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
352         if (fd < 0) {
353                 log_err(cd, _("Failed to open key file.\n"));
354                 return -EINVAL;
355         }
356
357         /* use 4k for buffer (page divisor but avoid huge pages) */
358         buflen = 4096 - sizeof(struct safe_allocation);
359         regular_file = 0;
360         if(!read_stdin) {
361                 if(stat(key_file, &st) < 0) {
362                         log_err(cd, _("Failed to stat key file.\n"));
363                         goto out_err;
364                 }
365                 if(S_ISREG(st.st_mode)) {
366                         regular_file = 1;
367                         file_read_size = (size_t)st.st_size;
368
369                         if (keyfile_offset > file_read_size) {
370                                 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
371                                 goto out_err;
372                         }
373                         file_read_size -= keyfile_offset;
374
375                         /* known keyfile size, alloc it in one step */
376                         if (file_read_size >= keyfile_size_max)
377                                 buflen = keyfile_size_max;
378                         else if (file_read_size)
379                                 buflen = file_read_size;
380                 }
381         }
382
383         pass = crypt_safe_alloc(buflen);
384         if (!pass) {
385                 log_err(cd, _("Out of memory while reading passphrase.\n"));
386                 goto out_err;
387         }
388
389         /* Discard keyfile_offset bytes on input */
390         if (keyfile_offset && keyfile_seek(fd, keyfile_offset) < 0) {
391                 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
392                 goto out_err;
393         }
394
395         for(i = 0; i < keyfile_size_max; i++) {
396                 if(i == buflen) {
397                         buflen += 4096;
398                         pass = crypt_safe_realloc(pass, buflen);
399                         if (!pass) {
400                                 log_err(cd, _("Out of memory while reading passphrase.\n"));
401                                 r = -ENOMEM;
402                                 goto out_err;
403                         }
404                 }
405
406                 char_read = read(fd, &pass[i], 1);
407                 if (char_read < 0) {
408                         log_err(cd, _("Error reading passphrase.\n"));
409                         goto out_err;
410                 }
411
412                 /* Stop on newline only if not requested read from keyfile */
413                 if(char_read == 0 || (!key_file && pass[i] == '\n'))
414                         break;
415         }
416
417         /* Fail if piped input dies reading nothing */
418         if(!i && !regular_file) {
419                 log_dbg("Nothing read on input.");
420                 r = -EPIPE;
421                 goto out_err;
422         }
423
424         /* Fail if we exceeded internal default (no specified size) */
425         if (unlimited_read && i == keyfile_size_max) {
426                 log_err(cd, _("Maximum keyfile size exceeded.\n"));
427                 goto out_err;
428         }
429
430         if (!unlimited_read && i != keyfile_size_max) {
431                 log_err(cd, _("Cannot read requested amount of data.\n"));
432                 goto out_err;
433         }
434
435         *key = pass;
436         *key_size = i;
437         r = 0;
438 out_err:
439         if(fd != STDIN_FILENO)
440                 close(fd);
441
442         if (r)
443                 crypt_safe_free(pass);
444         return r;
445 }
446
447 ssize_t crypt_hex_to_bytes(const char *hex, char **result, int safe_alloc)
448 {
449         char buf[3] = "xx\0", *endp, *bytes;
450         size_t i, len;
451
452         len = strlen(hex);
453         if (len % 2)
454                 return -EINVAL;
455         len /= 2;
456
457         bytes = safe_alloc ? crypt_safe_alloc(len) : malloc(len);
458         if (!bytes)
459                 return -ENOMEM;
460
461         for (i = 0; i < len; i++) {
462                 memcpy(buf, &hex[i * 2], 2);
463                 bytes[i] = strtoul(buf, &endp, 16);
464                 if (endp != &buf[2]) {
465                         safe_alloc ? crypt_safe_free(bytes) : free(bytes);
466                         return -EINVAL;
467                 }
468         }
469         *result = bytes;
470         return i;
471 }
472
473 /*
474  * Device size string parsing, suffixes:
475  * s|S - 512 bytes sectors
476  * k  |K  |m  |M  |g  |G  |t  |T   - 1024 base
477  * kiB|KiB|miB|MiB|giB|GiB|tiB|TiB - 1024 base
478  * kb |KB |mM |MB |gB |GB |tB |TB  - 1000 base
479  */
480 int crypt_string_to_size(struct crypt_device *cd, const char *s, uint64_t *size)
481 {
482         char *endp = NULL;
483         size_t len;
484         uint64_t mult_base, mult, tmp;
485
486         *size = strtoull(s, &endp, 10);
487         if (!isdigit(s[0]) ||
488             (errno == ERANGE && *size == ULLONG_MAX) ||
489             (errno != 0 && *size == 0))
490                 return -EINVAL;
491
492         if (!endp || !*endp)
493                 return 0;
494
495         len = strlen(endp);
496         /* Allow "B" and "iB" suffixes */
497         if (len > 3 ||
498            (len == 3 && (endp[1] != 'i' || endp[2] != 'B')) ||
499            (len == 2 && endp[1] != 'B'))
500                 return -EINVAL;
501
502         if (len == 1 || len == 3)
503                 mult_base = 1024;
504         else
505                 mult_base = 1000;
506
507         mult = 1;
508         switch (endp[0]) {
509         case 's':
510         case 'S': mult = 512;
511                 break;
512         case 't':
513         case 'T': mult *= mult_base;
514                  /* Fall through */
515         case 'g':
516         case 'G': mult *= mult_base;
517                  /* Fall through */
518         case 'm':
519         case 'M': mult *= mult_base;
520                  /* Fall through */
521         case 'k':
522         case 'K': mult *= mult_base;
523                 break;
524         default:
525                 return -EINVAL;
526         }
527
528         tmp = *size * mult;
529         if ((tmp / *size) != mult) {
530                 log_dbg("Device size overflow.");
531                 return -EINVAL;
532         }
533
534         *size = tmp;
535         return 0;
536 }