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