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