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