ec5773ea2710be20f2840339217e0533c5167232
[platform/upstream/cryptsetup.git] / lib / utils_crypt.c
1 /*
2  * util_crypt - cipher utilities for cryptsetup
3  *
4  * Copyright (C) 2004-2007, Clemens Fruhwirth <clemens@endorphin.org>
5  * Copyright (C) 2009-2011, 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 <sys/types.h>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 #include <fcntl.h>
30 #include <termios.h>
31
32 #include "libcryptsetup.h"
33 #include "nls.h"
34 #include "utils_crypt.h"
35
36 #define log_dbg(x) crypt_log(NULL, CRYPT_LOG_DEBUG, x)
37 #define log_err(cd, x) crypt_log(cd, CRYPT_LOG_ERROR, x)
38
39 struct safe_allocation {
40         size_t  size;
41         char    data[0];
42 };
43
44 int crypt_parse_name_and_mode(const char *s, char *cipher, int *key_nums,
45                               char *cipher_mode)
46 {
47         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]-%" MAX_CIPHER_LEN_STR "s",
48                    cipher, cipher_mode) == 2) {
49                 if (!strcmp(cipher_mode, "plain"))
50                         strncpy(cipher_mode, "cbc-plain", 10);
51                 if (key_nums) {
52                         char *tmp = strchr(cipher, ':');
53                         *key_nums = tmp ? atoi(++tmp) : 1;
54                         if (!*key_nums)
55                                 return -EINVAL;
56                 }
57
58                 return 0;
59         }
60
61         if (sscanf(s, "%" MAX_CIPHER_LEN_STR "[^-]", cipher) == 1) {
62                 strncpy(cipher_mode, "cbc-plain", 10);
63                 if (key_nums)
64                         *key_nums = 1;
65                 return 0;
66         }
67
68         return -EINVAL;
69 }
70
71 /* safe allocations */
72 void *crypt_safe_alloc(size_t size)
73 {
74         struct safe_allocation *alloc;
75
76         if (!size)
77                 return NULL;
78
79         alloc = malloc(size + offsetof(struct safe_allocation, data));
80         if (!alloc)
81                 return NULL;
82
83         alloc->size = size;
84
85         return &alloc->data;
86 }
87
88 void crypt_safe_free(void *data)
89 {
90         struct safe_allocation *alloc;
91
92         if (!data)
93                 return;
94
95         alloc = data - offsetof(struct safe_allocation, data);
96
97         memset(data, 0, alloc->size);
98
99         alloc->size = 0x55aa55aa;
100         free(alloc);
101 }
102
103 void *crypt_safe_realloc(void *data, size_t size)
104 {
105         struct safe_allocation *alloc;
106         void *new_data;
107
108         new_data = crypt_safe_alloc(size);
109
110         if (new_data && data) {
111
112                 alloc = data - offsetof(struct safe_allocation, data);
113
114                 if (size > alloc->size)
115                         size = alloc->size;
116
117                 memcpy(new_data, data, size);
118         }
119
120         crypt_safe_free(data);
121         return new_data;
122 }
123
124 /* Password reading helpers */
125 static int untimed_read(int fd, char *pass, size_t maxlen)
126 {
127         ssize_t i;
128
129         i = read(fd, pass, maxlen);
130         if (i > 0) {
131                 pass[i-1] = '\0';
132                 i = 0;
133         } else if (i == 0) { /* EOF */
134                 *pass = 0;
135                 i = -1;
136         }
137         return i;
138 }
139
140 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
141 {
142         struct timeval t;
143         fd_set fds;
144         int failed = -1;
145
146         FD_ZERO(&fds);
147         FD_SET(fd, &fds);
148         t.tv_sec = timeout;
149         t.tv_usec = 0;
150
151         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
152                 failed = untimed_read(fd, pass, maxlen);
153
154         return failed;
155 }
156
157 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
158                 long timeout)
159 {
160         struct termios orig, tmp;
161         int failed = -1;
162         int infd = STDIN_FILENO, outfd;
163
164         if (maxlen < 1)
165                 goto out_err;
166
167         /* Read and write to /dev/tty if available */
168         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
169                 infd = STDIN_FILENO;
170                 outfd = STDERR_FILENO;
171         }
172
173         if (tcgetattr(infd, &orig))
174                 goto out_err;
175
176         memcpy(&tmp, &orig, sizeof(tmp));
177         tmp.c_lflag &= ~ECHO;
178
179         if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
180                 goto out_err;
181
182         tcsetattr(infd, TCSAFLUSH, &tmp);
183         if (timeout)
184                 failed = timed_read(infd, pass, maxlen, timeout);
185         else
186                 failed = untimed_read(infd, pass, maxlen);
187         tcsetattr(infd, TCSAFLUSH, &orig);
188
189 out_err:
190         if (!failed && write(outfd, "\n", 1)) {};
191
192         if (infd != STDIN_FILENO)
193                 close(infd);
194         return failed;
195 }
196
197 static int crypt_get_key_tty(const char *prompt,
198                              char **key, size_t *key_size,
199                              int timeout, int verify,
200                              struct crypt_device *cd)
201 {
202         int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
203         int r = -EINVAL;
204         char *pass = NULL, *pass_verify = NULL;
205
206         log_dbg("Interactive passphrase entry requested.");
207
208         pass = crypt_safe_alloc(key_size_max + 1);
209         if (!pass) {
210                 log_err(cd, _("Out of memory while reading passphrase.\n"));
211                 return -ENOMEM;
212         }
213
214         if (interactive_pass(prompt, pass, key_size_max, timeout)) {
215                 log_err(cd, _("Error reading passphrase from terminal.\n"));
216                 goto out_err;
217         }
218         pass[key_size_max] = '\0';
219
220         if (verify) {
221                 pass_verify = crypt_safe_alloc(key_size_max);
222                 if (!pass_verify) {
223                         log_err(cd, _("Out of memory while reading passphrase.\n"));
224                         r = -ENOMEM;
225                         goto out_err;
226                 }
227
228                 if (interactive_pass(_("Verify passphrase: "),
229                     pass_verify, key_size_max, timeout)) {
230                         log_err(cd, _("Error reading passphrase from terminal.\n"));
231                         goto out_err;
232                 }
233
234                 if (strncmp(pass, pass_verify, key_size_max)) {
235                         log_err(cd, _("Passphrases do not match.\n"));
236                         goto out_err;
237                 }
238         }
239
240         *key = pass;
241         *key_size = strlen(pass);
242         r = 0;
243 out_err:
244         crypt_safe_free(pass_verify);
245         if (r)
246                 crypt_safe_free(pass);
247         return r;
248 }
249
250 /*
251  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
252  * key_size_max == 0 means detect maximum according to input type (tty/file)
253  * timeout and verify options only applies to tty input
254  */
255 int crypt_get_key(const char *prompt,
256                   char **key, size_t *key_size,
257                   size_t keyfile_size_max, const char *key_file,
258                   int timeout, int verify,
259                   struct crypt_device *cd)
260 {
261         int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
262         int r = -EINVAL;
263         char *pass = NULL;
264         size_t buflen, i;
265         struct stat st;
266
267         *key = NULL;
268         *key_size = 0;
269
270         /* Passphrase read from stdin? */
271         read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
272
273         if(read_stdin && isatty(STDIN_FILENO))
274                 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
275
276         if (keyfile_size_max < 0) {
277                 log_err(cd, _("Negative keyfile size not permitted.\n"));
278                 return -EINVAL;
279         }
280
281         if (read_stdin)
282                 log_dbg("STDIN descriptor passphrase entry requested.");
283         else
284                 log_dbg("File descriptor passphrase entry requested.");
285
286         /* If not requsted otherwise, we limit input to prevent memory exhaustion */
287         if (keyfile_size_max == 0) {
288                 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
289                 unlimited_read = 1;
290         }
291
292         fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
293         if (fd < 0) {
294                 log_err(cd, _("Failed to open key file.\n"));
295                 return -EINVAL;
296         }
297
298         /* use 4k for buffer (page divisor but avoid huge pages) */
299         buflen = 4096 - sizeof(struct safe_allocation);
300         regular_file = 0;
301         if(!read_stdin) {
302                 if(stat(key_file, &st) < 0) {
303                         log_err(cd, _("Failed to stat key file.\n"));
304                         goto out_err;
305                 }
306                 if(S_ISREG(st.st_mode)) {
307                         regular_file = 1;
308                         /* known keyfile size, alloc it in one step */
309                         if (st.st_size >= keyfile_size_max)
310                                 buflen = keyfile_size_max;
311                         else
312                                 buflen = st.st_size;
313                 }
314         }
315
316         pass = crypt_safe_alloc(buflen);
317         if (!pass) {
318                 log_err(cd, _("Out of memory while reading passphrase.\n"));
319                 goto out_err;
320         }
321
322         for(i = 0; i < keyfile_size_max; i++) {
323                 if(i == buflen) {
324                         buflen += 4096;
325                         pass = crypt_safe_realloc(pass, buflen);
326                         if (!pass) {
327                                 log_err(cd, _("Out of memory while reading passphrase.\n"));
328                                 r = -ENOMEM;
329                                 goto out_err;
330                         }
331                 }
332
333                 char_read = read(fd, &pass[i], 1);
334                 if (char_read < 0) {
335                         log_err(cd, _("Error reading passphrase.\n"));
336                         goto out_err;
337                 }
338
339                 /* Stop on newline only if not requested read from keyfile */
340                 if(char_read == 0 || (!key_file && pass[i] == '\n'))
341                         break;
342         }
343
344         /* Fail if piped input dies reading nothing */
345         if(!i && !regular_file) {
346                 log_dbg("Nothing read on input.");
347                 r = -EPIPE;
348                 goto out_err;
349         }
350
351         /* Fail if we exceeded internal default (no specified size) */
352         if (unlimited_read && i == keyfile_size_max) {
353                 log_err(cd, _("Maximum keyfile size exceeeded.\n"));
354                 goto out_err;
355         }
356
357         if (!unlimited_read && i != keyfile_size_max) {
358                 log_err(cd, _("Cannot read requested amount of data.\n"));
359                 goto out_err;
360         }
361
362         /* Well, for historical reasons reading empty keyfile is not fail. */
363         if(!i) {
364                 crypt_safe_free(pass);
365                 pass = NULL;
366         }
367
368         *key = pass;
369         *key_size = i;
370         r = 0;
371 out_err:
372         if(fd != STDIN_FILENO)
373                 close(fd);
374
375         if (r)
376                 crypt_safe_free(pass);
377         return r;
378 }