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