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