Fix typo
[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 <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 = (struct safe_allocation *)
96                 ((char *)data - offsetof(struct safe_allocation, data));
97
98         memset(data, 0, alloc->size);
99
100         alloc->size = 0x55aa55aa;
101         free(alloc);
102 }
103
104 void *crypt_safe_realloc(void *data, size_t size)
105 {
106         struct safe_allocation *alloc;
107         void *new_data;
108
109         new_data = crypt_safe_alloc(size);
110
111         if (new_data && data) {
112
113                 alloc = (struct safe_allocation *)
114                         ((char *)data - offsetof(struct safe_allocation, data));
115
116                 if (size > alloc->size)
117                         size = alloc->size;
118
119                 memcpy(new_data, data, size);
120         }
121
122         crypt_safe_free(data);
123         return new_data;
124 }
125
126 /* Password reading helpers */
127 static int untimed_read(int fd, char *pass, size_t maxlen)
128 {
129         ssize_t i;
130
131         i = read(fd, pass, maxlen);
132         if (i > 0) {
133                 pass[i-1] = '\0';
134                 i = 0;
135         } else if (i == 0) { /* EOF */
136                 *pass = 0;
137                 i = -1;
138         }
139         return i;
140 }
141
142 static int timed_read(int fd, char *pass, size_t maxlen, long timeout)
143 {
144         struct timeval t;
145         fd_set fds;
146         int failed = -1;
147
148         FD_ZERO(&fds);
149         FD_SET(fd, &fds);
150         t.tv_sec = timeout;
151         t.tv_usec = 0;
152
153         if (select(fd+1, &fds, NULL, NULL, &t) > 0)
154                 failed = untimed_read(fd, pass, maxlen);
155
156         return failed;
157 }
158
159 static int interactive_pass(const char *prompt, char *pass, size_t maxlen,
160                 long timeout)
161 {
162         struct termios orig, tmp;
163         int failed = -1;
164         int infd = STDIN_FILENO, outfd;
165
166         if (maxlen < 1)
167                 goto out_err;
168
169         /* Read and write to /dev/tty if available */
170         if ((infd = outfd = open("/dev/tty", O_RDWR)) == -1) {
171                 infd = STDIN_FILENO;
172                 outfd = STDERR_FILENO;
173         }
174
175         if (tcgetattr(infd, &orig))
176                 goto out_err;
177
178         memcpy(&tmp, &orig, sizeof(tmp));
179         tmp.c_lflag &= ~ECHO;
180
181         if (prompt && write(outfd, prompt, strlen(prompt)) < 0)
182                 goto out_err;
183
184         tcsetattr(infd, TCSAFLUSH, &tmp);
185         if (timeout)
186                 failed = timed_read(infd, pass, maxlen, timeout);
187         else
188                 failed = untimed_read(infd, pass, maxlen);
189         tcsetattr(infd, TCSAFLUSH, &orig);
190
191 out_err:
192         if (!failed && write(outfd, "\n", 1)) {};
193
194         if (infd != STDIN_FILENO)
195                 close(infd);
196         return failed;
197 }
198
199 static int crypt_get_key_tty(const char *prompt,
200                              char **key, size_t *key_size,
201                              int timeout, int verify,
202                              struct crypt_device *cd)
203 {
204         int key_size_max = DEFAULT_PASSPHRASE_SIZE_MAX;
205         int r = -EINVAL;
206         char *pass = NULL, *pass_verify = NULL;
207
208         log_dbg("Interactive passphrase entry requested.");
209
210         pass = crypt_safe_alloc(key_size_max + 1);
211         if (!pass) {
212                 log_err(cd, _("Out of memory while reading passphrase.\n"));
213                 return -ENOMEM;
214         }
215
216         if (interactive_pass(prompt, pass, key_size_max, timeout)) {
217                 log_err(cd, _("Error reading passphrase from terminal.\n"));
218                 goto out_err;
219         }
220         pass[key_size_max] = '\0';
221
222         if (verify) {
223                 pass_verify = crypt_safe_alloc(key_size_max);
224                 if (!pass_verify) {
225                         log_err(cd, _("Out of memory while reading passphrase.\n"));
226                         r = -ENOMEM;
227                         goto out_err;
228                 }
229
230                 if (interactive_pass(_("Verify passphrase: "),
231                     pass_verify, key_size_max, timeout)) {
232                         log_err(cd, _("Error reading passphrase from terminal.\n"));
233                         goto out_err;
234                 }
235
236                 if (strncmp(pass, pass_verify, key_size_max)) {
237                         log_err(cd, _("Passphrases do not match.\n"));
238                         r = -EPERM;
239                         goto out_err;
240                 }
241         }
242
243         *key = pass;
244         *key_size = strlen(pass);
245         r = 0;
246 out_err:
247         crypt_safe_free(pass_verify);
248         if (r)
249                 crypt_safe_free(pass);
250         return r;
251 }
252
253 /*
254  * Note: --key-file=- is interpreted as a read from a binary file (stdin)
255  * key_size_max == 0 means detect maximum according to input type (tty/file)
256  * timeout and verify options only applies to tty input
257  */
258 int crypt_get_key(const char *prompt,
259                   char **key, size_t *key_size,
260                   size_t keyfile_offset, size_t keyfile_size_max,
261                   const char *key_file, int timeout, int verify,
262                   struct crypt_device *cd)
263 {
264         int fd, regular_file, read_stdin, char_read, unlimited_read = 0;
265         int r = -EINVAL;
266         char *pass = NULL, tmp;
267         size_t buflen, i, file_read_size;
268         struct stat st;
269
270         *key = NULL;
271         *key_size = 0;
272
273         /* Passphrase read from stdin? */
274         read_stdin = (!key_file || !strcmp(key_file, "-")) ? 1 : 0;
275
276         if (read_stdin && isatty(STDIN_FILENO)) {
277                 if (keyfile_offset) {
278                         log_err(cd, _("Cannot use offset with terminal input.\n"));
279                         return -EINVAL;
280                 }
281                 return crypt_get_key_tty(prompt, key, key_size, timeout, verify, cd);
282         }
283
284         if (read_stdin)
285                 log_dbg("STDIN descriptor passphrase entry requested.");
286         else
287                 log_dbg("File descriptor passphrase entry requested.");
288
289         /* If not requsted otherwise, we limit input to prevent memory exhaustion */
290         if (keyfile_size_max == 0) {
291                 keyfile_size_max = DEFAULT_KEYFILE_SIZE_MAXKB * 1024;
292                 unlimited_read = 1;
293         }
294
295         fd = read_stdin ? STDIN_FILENO : open(key_file, O_RDONLY);
296         if (fd < 0) {
297                 log_err(cd, _("Failed to open key file.\n"));
298                 return -EINVAL;
299         }
300
301         /* use 4k for buffer (page divisor but avoid huge pages) */
302         buflen = 4096 - sizeof(struct safe_allocation);
303         regular_file = 0;
304         if(!read_stdin) {
305                 if(stat(key_file, &st) < 0) {
306                         log_err(cd, _("Failed to stat key file.\n"));
307                         goto out_err;
308                 }
309                 if(S_ISREG(st.st_mode)) {
310                         regular_file = 1;
311                         file_read_size = (size_t)st.st_size;
312
313                         if (keyfile_offset > file_read_size) {
314                                 log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
315                                 goto out_err;
316                         }
317                         file_read_size -= keyfile_offset;
318
319                         /* known keyfile size, alloc it in one step */
320                         if (file_read_size >= keyfile_size_max)
321                                 buflen = keyfile_size_max;
322                         else if (file_read_size)
323                                 buflen = file_read_size;
324                 }
325         }
326
327         pass = crypt_safe_alloc(buflen);
328         if (!pass) {
329                 log_err(cd, _("Out of memory while reading passphrase.\n"));
330                 goto out_err;
331         }
332
333         /* Discard keyfile_offset bytes on input */
334         for(i = 0; i < keyfile_offset; i++)
335                 if (read(fd, &tmp, 1) != 1) {
336                         log_err(cd, _("Cannot seek to requested keyfile offset.\n"));
337                         goto out_err;
338                 }
339
340         for(i = 0; i < keyfile_size_max; i++) {
341                 if(i == buflen) {
342                         buflen += 4096;
343                         pass = crypt_safe_realloc(pass, buflen);
344                         if (!pass) {
345                                 log_err(cd, _("Out of memory while reading passphrase.\n"));
346                                 r = -ENOMEM;
347                                 goto out_err;
348                         }
349                 }
350
351                 char_read = read(fd, &pass[i], 1);
352                 if (char_read < 0) {
353                         log_err(cd, _("Error reading passphrase.\n"));
354                         goto out_err;
355                 }
356
357                 /* Stop on newline only if not requested read from keyfile */
358                 if(char_read == 0 || (!key_file && pass[i] == '\n'))
359                         break;
360         }
361
362         /* Fail if piped input dies reading nothing */
363         if(!i && !regular_file) {
364                 log_dbg("Nothing read on input.");
365                 r = -EPIPE;
366                 goto out_err;
367         }
368
369         /* Fail if we exceeded internal default (no specified size) */
370         if (unlimited_read && i == keyfile_size_max) {
371                 log_err(cd, _("Maximum keyfile size exceeded.\n"));
372                 goto out_err;
373         }
374
375         if (!unlimited_read && i != keyfile_size_max) {
376                 log_err(cd, _("Cannot read requested amount of data.\n"));
377                 goto out_err;
378         }
379
380         *key = pass;
381         *key_size = i;
382         r = 0;
383 out_err:
384         if(fd != STDIN_FILENO)
385                 close(fd);
386
387         if (r)
388                 crypt_safe_free(pass);
389         return r;
390 }